-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.cs
More file actions
146 lines (133 loc) · 5.48 KB
/
Parser.cs
File metadata and controls
146 lines (133 loc) · 5.48 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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
using System.Globalization;
namespace ExpressionParser
{
// The parser builds an AST from the token stream.
class Parser
{
private Tokeniser tokeniser;
private Dictionary<string, Type> _variableTypes;
public Parser(Tokeniser tokeniser, Dictionary<string, Type> variableTypes)
{
this.tokeniser = tokeniser;
_variableTypes = variableTypes;
}
// Expression : Term ((+ | -) Term)*
public ExpressionNode ParseExpression()
{
ExpressionNode expr = ParseTerm();
while (tokeniser.CurrentToken.Type == TokenType.Plus ||
tokeniser.CurrentToken.Type == TokenType.Minus)
{
TokenType op = tokeniser.CurrentToken.Type;
tokeniser.NextToken();
ExpressionNode right = ParseTerm();
expr = new BinaryOpNode(expr, op, right);
}
return expr;
}
// Term : Factor ((* | /) Factor)*
private ExpressionNode ParseTerm()
{
ExpressionNode expr = ParseFactor();
while (tokeniser.CurrentToken.Type == TokenType.Multiply ||
tokeniser.CurrentToken.Type == TokenType.Divide)
{
TokenType op = tokeniser.CurrentToken.Type;
tokeniser.NextToken();
ExpressionNode right = ParseFactor();
expr = new BinaryOpNode(expr, op, right);
}
return expr;
}
// Factor : -Factor | Primary
private ExpressionNode ParseFactor()
{
if (tokeniser.CurrentToken.Type == TokenType.Minus)
{
TokenType op = tokeniser.CurrentToken.Type;
tokeniser.NextToken();
ExpressionNode factor = ParseFactor();
return new UnaryOpNode(op, factor);
}
return ParsePrimary();
}
// Primary : Number | String | Variable | Identifier (possibly function call) | ( Expression )
private ExpressionNode ParsePrimary()
{
Token token = tokeniser.CurrentToken;
switch (token.Type)
{
case TokenType.Number:
tokeniser.NextToken();
if (!double.TryParse(token.Text, NumberStyles.Any, CultureInfo.InvariantCulture, out double number))
throw new Exception($"Invalid number literal: {token.Text}");
return new LiteralNode(number);
case TokenType.String:
tokeniser.NextToken();
return new LiteralNode(token.Text);
case TokenType.Variable:
tokeniser.NextToken();
return new VariableNode(token.Text, _variableTypes);
case TokenType.Identifier:
{
// For our purposes the only identifiers outside of functions are the boolean literals TRUE/FALSE.
string id = token.Text;
tokeniser.NextToken();
if (id.Equals("TRUE", StringComparison.OrdinalIgnoreCase))
return new LiteralNode(true);
if (id.Equals("FALSE", StringComparison.OrdinalIgnoreCase))
return new LiteralNode(false);
// Function call: if an identifier is immediately followed by '(' then call it.
if (tokeniser.CurrentToken.Type == TokenType.LeftParen)
{
tokeniser.NextToken(); // consume '('
List<ExpressionNode> args = new List<ExpressionNode>();
if (tokeniser.CurrentToken.Type != TokenType.RightParen)
{
while (true)
{
ExpressionNode arg = ParseExpression();
args.Add(arg);
if (tokeniser.CurrentToken.Type == TokenType.Comma)
{
tokeniser.NextToken();
continue;
}
else if (tokeniser.CurrentToken.Type == TokenType.RightParen)
{
break;
}
else
{
throw new Exception("Expected ',' or ')' in function parameters.");
}
}
}
if (tokeniser.CurrentToken.Type != TokenType.RightParen)
throw new Exception("Expected ')' after function arguments.");
tokeniser.NextToken(); // consume ')'
return new FunctionCallNode(id, args);
}
throw new Exception($"Unexpected identifier: {id}");
}
case TokenType.LeftParen:
tokeniser.NextToken();
ExpressionNode expr = ParseExpression();
if (tokeniser.CurrentToken.Type != TokenType.RightParen)
throw new Exception("Missing closing parenthesis.");
tokeniser.NextToken(); // consume ')'
return expr;
default:
throw new Exception($"Unexpected token: {token.Text}");
}
}
public static bool IsNumeric(object obj)
{
return obj is sbyte || obj is byte ||
obj is short || obj is ushort ||
obj is int || obj is uint ||
obj is long || obj is ulong ||
obj is float || obj is double || obj is decimal;
}
}
}