-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParser.cs
135 lines (110 loc) · 2.98 KB
/
Parser.cs
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
135
namespace SimpleInterpreter.Parser;
using SimpleInterpreter.Types;
using SimpleInterpreter.Lexer;
using System.Linq.Expressions;
class Parser(IEnumerable<Token> tokens)
{
private readonly IEnumerable<Token> tokens = tokens;
private int current = 0;
private bool isAtEnd(int offset = 0) => tokens.ElementAt(current + offset).type == TokenType.EOF;
private Token peek(int offset = 0)
{
if (!isAtEnd(offset))
{
return tokens.ElementAt(current + offset);
}
return new Token(TokenType.EOF, "\0", null, 0);
}
private Token previous() => peek(-1);
private void advance() => current++;
private Token take()
{
var token = peek();
advance();
return token;
}
private void consume(TokenType type)
{
var token = peek();
if (token.type == type)
{
advance();
return;
}
throw new Exception($"[line: {token.line}] {token.lexeme} should be {type}, instead of {token.type}");
}
private bool match(TokenType type)
{
if (peek().type == type)
{
advance();
return true;
}
return false;
}
private IExpression number()
{
var token = take();
if (token.type != TokenType.NUMBER)
{
throw new Exception($"{token.lexeme} should be a number, instead of {token.type}");
}
return new NumberExpression(token);
}
private IExpression primary()
{
if (match(TokenType.LEFT_PARENT))
{
var expr = term();
consume(TokenType.RIGHT_PARENT);
return expr;
}
return number();
}
private IExpression unary()
{
if (match(TokenType.MINUS))
{
var op = previous();
return new SimpleInterpreter.Types.UnaryExpression(op, unary());
}
return primary();
}
private IExpression factor()
{
var expr = unary();
while (match(TokenType.STAR) || match(TokenType.SLASH))
{
var op = previous();
var right = unary();
expr = new SimpleInterpreter.Types.BinaryExpression(op, expr, right);
}
return expr;
}
private IExpression term()
{
var expr = factor();
while (match(TokenType.PLUS) || match(TokenType.MINUS))
{
var op = previous();
var right = factor();
expr = new SimpleInterpreter.Types.BinaryExpression(op, expr, right);
}
return expr;
}
private Statment expressionStatment()
{
var expression = term();
consume(TokenType.SEMICOLON);
return new Statment(expression);
}
public IEnumerable<Statment> prase()
{
var statments = Enumerable.Empty<Statment>();
while (!isAtEnd())
{
statments = statments.Append(expressionStatment());
}
return statments;
}
}