Repository navigation
Expand file tree
/
Copy pathparser.cpp
More file actions
118 lines (104 loc) · 2.71 KB
/
Copy pathparser.cpp
File metadata and controls
118 lines (104 loc) · 2.71 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
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
#include "lexer.h"
#include "expr.h"
#include <initializer_list>
class parser
{
dynamic_array<Token> tokens;
int currentposition{0};
public:
Expr parse()
{
Expr expression = ParseExpression();
consume(END_OF_FILE, "Expected EOF");
return expression;
}
private:
Expr ParseExpression()
{
Expr workingExpression = ParseTerm();
while (match({PLUS, MINUS}))
{
Token operator_token = previous();
Expr parsedTerm = ParseTerm();
// left unfolding
workingExpression = Binary(workingExpression, operator_token, parsedTerm);
}
return workingExpression;
}
Expr ParseTerm()
{
Expr WorkingExpression = ParseFactor();
while (match({STAR, SLASH}))
{
Token operator_token = previous();
Expr parsedFactor = ParseFactor();
// left unfolding
WorkingExpression = Binary(WorkingExpression, operator_token, parsedFactor);
}
return WorkingExpression;
}
Expr ParseFactor()
{
// first case is if its an integer
if (match({NUMBER}))
{
return NumberLiteral(to_integer(previous().value));
}
// case 2 is an expression
if (match({OPEN_BRACKET}))
{
Expr ParsedExpression = ParseExpression();
Token expression = consume(CLOSE_BRACKET, "FAILED TO PARSE A FACTOR EXPECTED AN EXPRESSION AN BRACKET");
return ParsedExpression; // he had expression here not parsedexpression double check later
}
throw("unable to parse a factor expected a number or token bracket");
}
Token peek()
{
return tokens[currentposition];
}
bool IsAtEnd()
{
return peek().type == END_OF_FILE;
}
Token previous()
{
return tokens[currentposition - 1];
}
Token advance()
{
if (!IsAtEnd())
{
currentposition += 1;
}
return previous();
}
bool check(TokenType type)
{
if (IsAtEnd())
{
return type == END_OF_FILE;
}
return peek().type == type;
}
Token consume(TokenType type, string message)
{
if (check(type))
{
return advance();
}
throw(message);
}
bool match(std::initializer_list<TokenType> types)
{
for (TokenType type : types)
{
if (check(type))
{
advance();
return true;
}
}
return false;
}
};