-
Notifications
You must be signed in to change notification settings - Fork 0
/
RECURSIVE DESCENT PARSER.txt
116 lines (104 loc) · 2.01 KB
/
RECURSIVE DESCENT PARSER.txt
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_INPUT_SIZE 100
typedef enum {
LPAREN,
RPAREN,
PLUS,
MULT,
ID,
END,
ERROR
} Token;
Token lookahead;
char input[MAX_INPUT_SIZE];
int index = 0;
int success = 1;
Token get_token() {
char c = input[index++];
while (isspace(c)) {
c = input[index++];
}
switch (c) {
case '(':
return LPAREN;
case ')':
return RPAREN;
case '+':
return PLUS;
case '*':
return MULT;
case 'i':
if (input[index] == 'd') {
index++;
return ID;
} else {
break;
}
case '\0':
return END;
}
success = 0;
return ERROR;
}
void E();
void Eprime();
void T();
void Tprime();
void F();
void match(Token expected) {
if (lookahead == expected) {
lookahead = get_token();
} else {
printf("Error: expected %d, got %d\n", expected, lookahead);
success = 0;
}
}
void E() {
T();
Eprime();
}
void Eprime() {
if (lookahead == PLUS) {
match(PLUS);
T();
Eprime();
}
}
void T() {
F();
Tprime();
}
void Tprime() {
if (lookahead == MULT) {
match(MULT);
F();
Tprime();
}
}
void F() {
if (lookahead == LPAREN) {
match(LPAREN);
E();
match(RPAREN);
} else if (lookahead == ID) {
match(ID);
} else {
printf("Error: expected LPAREN or ID, got %d\n", lookahead);
success = 0;
}
}
int main() {
printf("Enter an expression: ");
fgets(input, MAX_INPUT_SIZE, stdin);
lookahead = get_token();
E();
if (success && lookahead == END) {
printf("Parsing successful\n");
} else {
printf("Parsing unsuccessful\n");
}
return 0;
}