-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerator.cs
More file actions
53 lines (51 loc) · 1.78 KB
/
Copy pathGenerator.cs
File metadata and controls
53 lines (51 loc) · 1.78 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
using System;
using System.Collections.Generic;
using System.Reflection.Emit;
namespace expr
{
class Generator
{
private List<Token> tokens;
public Generator()
{
this.tokens = new List<Token>();
}
public void Feed(string code)
{
Lexer lexer = new Lexer(code);
Parser parser = new Parser(lexer);
this.tokens = parser.Parse();
}
public int Evaluate()
{
var AssemblyMain = new DynamicMethod("_main", typeof(int), null, typeof(Program).Module);
var il = AssemblyMain.GetILGenerator();
foreach(Token token in this.tokens) {
if(token.Type == TokenType.OPERAND) {
int value = int.Parse(token.Value);
il.Emit(OpCodes.Ldc_I4, value);
} else {
switch(token.Operator) {
case OperatorsType.PLUS:
il.Emit(OpCodes.Add);
break;
case OperatorsType.MINUS:
il.Emit(OpCodes.Sub);
break;
case OperatorsType.MULTIPLY:
il.Emit(OpCodes.Mul);
break;
case OperatorsType.DIVIDE:
il.Emit(OpCodes.Div);
break;
default:
throw new Exception("Error evaluating operator");
}
}
}
il.Emit(OpCodes.Ret);
var AssemblyMethodCallable = (Func<int>)AssemblyMain.CreateDelegate(typeof(Func<int>));
return AssemblyMethodCallable();
}
}
}