-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecursive_descent.c
77 lines (72 loc) · 1.51 KB
/
recursive_descent.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
75
76
77
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>
/**
* this is the language grammar and now lets implement recursive descent parser
* expression -> term ((+) term)*
* term -> factor ((*) factor)*
* factor -> [0-9] | '(' expression ')'
*/
int expression();
int term();
int factor();
bool match(char token);
void moveCursor();
bool isDigit(char *token);
void error(const char *message);
const char *input;
int expression(){
int value = term();
while(match('+')){
value += term();
}
return value;
}
int term(){
int value = factor();
while(match('*')){
value *= factor();
}
return value;
}
int factor(){
if (match('(')) {
int value = expression();
if (!match(')')) {
error("Expected closing parenthesis.");
}
return value;
} else if (isDigit(input)) {
int value = *input - '0';
moveCursor();
return value;
} else {
error("Unexpected token. Expected a digit or '('.");
return -1;
}
}
void moveCursor(){
if(*input != '\0')
input++;
}
bool match(char token){
if(*input == token){
moveCursor();
return true;
}
return false;
}
bool isDigit(char *token){
printf("digit: %d\n",*token);
return *token >= 48 && *token <= 57;
}
void error(const char *message) {
printf("Error: %s\n", message);
exit(1);
}
int main(){
input = "(9+3)*2";
int result = expression();
printf("Final value is: %d\n",result);
return 0;
}