-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.cs
More file actions
90 lines (74 loc) · 2.07 KB
/
Parser.cs
File metadata and controls
90 lines (74 loc) · 2.07 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
using System;
/*
expr :term
| expr ('+' |'-') term;
term:factor
|factor ('*'|'/') term;
factor:NUMBER;
*/
namespace LexerParser
{
public class Parser
{
private Lexer lexer;
private Token currentToken;
public Parser(String source)
{
var charArray = source.Trim(' ').ToCharArray();
lexer = new Lexer(charArray);
currentToken = lexer.Lookahead(0);
}
public Node Expr()
{
var node = Term();
while ((IsToken("+") || IsToken("-")))
{
var @operator = lexer.Consume().Value;
var right = this.Term();
node = new Expression(node, @operator[0], right);
}
return node;
}
public Node Term()
{
var node = Factor();
while (IsToken("*") || IsToken("/"))
{
var @operator = lexer.Consume().Value; // read *//
var right = this.Factor();
node = new Expression(node, @operator[0], right);
}
return node;
}
public Node Factor()
{
if (IsToken("("))
{
lexer.Consume();
var exp = Expr();
lexer.Consume();
return exp;
}
else
{
var token = lexer.Consume();
if (token.Type == TokenType.Number)
{
var val = int.Parse(token.Value);
return new Number(val);
}
else
{
throw new LexerException("Invalid Token");
}
}
}
public bool IsToken(string name)
{
if (name == null) throw new ArgumentNullException(nameof(name));
var token = lexer.Lookahead(0);
var isMatch = token.Value.Trim().Equals(name.Trim());
return token.Type == TokenType.Operator && isMatch;
}
}
}