-
Notifications
You must be signed in to change notification settings - Fork 0
/
clr(1).txt
134 lines (123 loc) · 2.6 KB
/
clr(1).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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_INPUT_SIZE 100
typedef enum {
ID,
PLUS,
MINUS,
MULT,
DIV,
LPAREN,
RPAREN,
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 PLUS;
case '-':
return MINUS;
case '*':
return MULT;
case '/':
return DIV;
case '(':
return LPAREN;
case ')':
return RPAREN;
case '\0':
return END;
default:
if (isalpha(c)) {
return ID;
}
printf("Error: unexpected character %c\n", c);
success = 0;
return ERROR;
}
}
void expr();
void term();
void factor();
void id();
void match(Token expected) {
if (lookahead == expected) {
lookahead = get_token();
} else {
printf("Error: expected %d, got %d\n", expected, lookahead);
success = 0;
}
}
void id() {
match(ID);
}
void factor() {
switch (lookahead) {
case ID:
id();
break;
case LPAREN:
match(LPAREN);
expr();
match(RPAREN);
break;
default:
printf("Error: expected ID or LPAREN, got %d\n", lookahead);
success = 0;
break;
}
}
void term() {
factor();
while (lookahead == MULT || lookahead == DIV) {
switch (lookahead) {
case MULT:
match(MULT);
factor();
break;
case DIV:
match(DIV);
factor();
break;
}
}
}
void expr() {
term();
while (lookahead == PLUS || lookahead == MINUS) {
switch (lookahead) {
case PLUS:
match(PLUS);
term();
break;
case MINUS:
match(MINUS);
term();
break;
}
}
}
int main() {
printf("Enter an expression: ");
fgets(input, MAX_INPUT_SIZE, stdin);
lookahead = get_token();
expr();
if (success && lookahead == END) {
printf("Parsing successful\n");
} else {
printf("Parsing unsuccessful\n");
}
return 0;
}
input: a+b