-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
executable file
·74 lines (71 loc) · 1.62 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include "tokenizer.h"
#include "parser.h"
#include "interpreter.h"
#include "talloc.h"
#include "value.h"
#include "linkedlist.h"
#include <unistd.h>
#include <stdio.h>
#include <stdbool.h>
/*
* Returns true if the number of open and close parentheses match in an expression
*/
bool parenthesesMatch(Value *tokens) {
int open = 0;
int close = 0;
while (tokens->type != NULL_TYPE) {
if (car(tokens)->type == OPEN_TYPE) {
open++;
} else if (car(tokens)->type == CLOSE_TYPE) {
close++;
}
tokens = cdr(tokens);
}
if (open == close) {
return true;
} else if (open < close) {
printf("Syntax Error: too many close parentheses.\n");
texit(1);
}
return false;
}
/*
* Takes in two linked lists, returns a list consisting of the contents of the
* first list followed by the contents of the second list.
*/
Value *joinList(Value *list1, Value *list2) {
Value *toReturn = list1;
while (cdr(list1)->type != NULL_TYPE) {
list1 = cdr(list1);
}
list1->c.cdr = list2;
return toReturn;
}
int main(void) {
if (isatty(fileno(stdin)) == 1) {
// We're in a terminal!
printf("> ");
char next = fgetc(stdin);
while (next != EOF) {
ungetc(next, stdin);
Value *list = tokenize();
// check if list has even parentheses. If not, continue.
while (!parenthesesMatch(list)) {
printf(". ");
Value *moreTokens = tokenize();
list = joinList(list, moreTokens);
}
Value *tree = parse(list);
interpret(tree);
printf("> ");
next = fgetc(stdin);
}
tfree();
} else {
Value *list = tokenize();
Value *tree = parse(list);
interpret(tree);
tfree();
return 0;
}
}