-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.cpp
More file actions
67 lines (63 loc) · 1.51 KB
/
parser.cpp
File metadata and controls
67 lines (63 loc) · 1.51 KB
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
#include "parser_impl.hpp"
#include "table.hpp"
double Parser::prim(bool get){
using Lexer::number_value;
using Lexer::string_value;
if(get) get_token();
switch (curr_tok) {
case NUMBER: // Floating-point constant
{
double v = number_value;
get_token();
return v;
}
case NAME:
{
double& v = table[string_value];
if(Lexer::get_token() == ASSIGN) v = expr(true);
return v;
}
case MINUS: // Unary minus
return -prim(true);
case LP:
{
double e = expr(true);
if (curr_tok != RP) throw Syntax_error(") expected");
get_token(); // Eat ')'
return e;
}
default:
throw Syntax_error("primary expected");
}
}
double Parser::term(bool get) {
double left = prim(get);
for(;;)
switch (curr_tok) {
case MUL:
left *= prim(true);
break;
case DIV:
if (double d = prim(true)) {
left /= d;
break;
}
throw Zero_divide();
default:
return left;
}
}
double Parser::expr(bool get) {
double left = term(get);
for(;;)
switch (curr_tok) {
case PLUS:
left += term(true);
break;
case MINUS:
left -= term(true);
break;
default:
return left;
}
}