-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.c
93 lines (82 loc) · 2.16 KB
/
parser.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include "parser.h"
#include "front.h"
static void error();
/**
* This is the example Recursive-Descent Parser in pp. 181 - 185 in the
* textbook
*
* Sebesta, R. W. (2012). Concepts of Programming Languages.
* Pearson, 10th edition.
*
*
* */
/* expr
* Parses strings in the language generated by the rule:
* <expr> -> <term> {(+ | -) <term>}
*/
void expr()
{
//printf("Enter <expr>\n");
/* Parse the first term */
term();
/* As long as the next token is + or -, get
the next token and parse the next term */
while (nextToken == ADD_OP || nextToken == SUB_OP) {
lex();
term();
}
//printf("Exit <expr>\n");
} /* End of function expr */
/* term
* Parses strings in the language generated by the rule:
* <term> -> <factor> {(* | /) <factor>)
*/
void term()
{
//printf("Enter <term>\n");
/* Parse the first factor */
factor();
/* As long as the next token is * or /, get the
next token and parse the next factor */
while (nextToken == MULT_OP || nextToken == DIV_OP) {
lex();
factor();
}
//printf("Exit <term>\n");
} /* End of function term */
/* factor
* Parses strings in the language generated by the rule:
* <factor> -> id | int_constant | ( <expr )
* */
void factor()
{
//printf("Enter <factor>\n");
/* Determine which RHS */
if (nextToken == IDENT || nextToken == INT_LIT) {
lex(); /* Get the next token */
} else {
/* If the RHS is (<expr>), call lex to pass over the
left parenthesis, call expr, and check for the right
parenthesis */
if (nextToken == LEFT_PAREN) {
lex();
expr();
if (nextToken == RIGHT_PAREN) {
lex();
} else {
error();
}
} /* End of if (nextToken == ... */
/* It was not an id, an integer literal, or a left parenthesis */
else
{
error();
}
} /* End of else */
//printf("Exit <factor>\n");;
} /* End of function factor */
static void error()
{
//printf("Error (more is desired, but not implemented).\n");
}