-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInterpreter.cs
45 lines (39 loc) · 1.48 KB
/
Interpreter.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
using SimpleInterpreter.Types;
namespace SimpleInterpreter.Interpreter;
class Interpreter(IEnumerable<Statment> statments)
{
private readonly IEnumerable<Statment> statments = statments;
private float eval(IExpression expression)
{
switch (expression)
{
case NumberExpression expr:
if (expr.value.literal == null)
{
throw new Exception($"{expr.value} is None");
}
return (float)expr.value.literal;
case UnaryExpression expr:
if (expr.op.type != TokenType.MINUS)
{
throw new Exception($"{expr.op} is not correct unary operator");
}
var result = eval(expr);
return -result;
case BinaryExpression expr:
var left = eval(expr.left);
var right = eval(expr.right);
return expr.op.type switch
{
TokenType.PLUS => left + right,
TokenType.MINUS => left - right,
TokenType.STAR => left * right,
TokenType.SLASH => left / right,
_ => throw new Exception("unexpected binary operator"),
};
default:
throw new Exception($"{expression} is not implemented.");
}
}
public IEnumerable<float> cal() => statments.Select(statment => eval(statment.expression));
}