-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
2.4.1.1.c
56 lines (47 loc) · 1.3 KB
/
2.4.1.1.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
/*
Compile with:
gcc -Wall -o parser 2.4.1.1.c
Run: ./parser
The code will quitely parse well-formed expressions. For bad expressions that don't
follow the grammar, it will complain with "Syntax error."
Some example input:
> ++++aaaaa
> +++--+-+-+-+-+++-a-aaaaaaaaaaaaaaaaaa
>
Note that you canot use spaces. The grammar doesn't allow for that.
We could change gettoken() to ignore spaces, but we'd be introducing
a problem. You see, when reading the input, the last lookahead symbol
left is a newline. If we ignored whitespace, we would block on the call
to gettoken() in the last production, because gettoken() would ignore
whitespaces! This is why a lot of languages require statements to be
properly ended, for example, with a semi-colon.
*/
#include <stdio.h>
/* The lookahead symbol */
int token;
int gettoken(void) {
return token = getchar();
}
void s(void) {
if (token == 'a')
gettoken();
else if (token == '+' || token == '-') {
gettoken();
s();
s();
}
else {
fprintf(stderr, "Syntax error.\n");
}
}
int main(void) {
printf("Please enter expressions according to the following grammar:\n");
printf("S -> '+' S S | '-' S S | 'a'\n");
while (1) {
printf("> ");
fflush(stdout);
gettoken();
s();
}
return 0;
}