-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExtendedCompiler.cs
365 lines (300 loc) · 10.6 KB
/
ExtendedCompiler.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
using System.Linq;
namespace ExtendedCompiler
{
public enum TokenType
{
Number,
String,
Identifier,
Plus,
Minus,
Multiply,
Divide,
LeftParen,
RightParen,
Comma,
Dot,
EOF
}
public class Token
{
public TokenType Type { get; }
public string Value { get; }
public int Position { get; }
public Token(TokenType type, string value, int position)
{
Type = type;
Value = value;
Position = position;
}
}
public class Lexer
{
private readonly string _input;
private int _position;
public Lexer(string input)
{
_input = input;
_position = 0;
}
public Token GetNextToken()
{
while (_position < _input.Length)
{
char currentChar = _input[_position];
if (char.IsWhiteSpace(currentChar))
{
_position++;
continue;
}
// Handle string literals
if (currentChar == '"')
{
_position++; // Skip opening quote
int startPos = _position;
string value = "";
while (_position < _input.Length && _input[_position] != '"')
{
value += _input[_position];
_position++;
}
if (_position >= _input.Length)
throw new Exception("Unterminated string literal");
_position++; // Skip closing quote
return new Token(TokenType.String, value, startPos);
}
// Handle identifiers
if (char.IsLetter(currentChar))
{
string identifier = "";
int startPos = _position;
while (_position < _input.Length &&
(char.IsLetterOrDigit(_input[_position]) || _input[_position] == '_'))
{
identifier += _input[_position];
_position++;
}
return new Token(TokenType.Identifier, identifier, startPos);
}
// Handle numbers
if (char.IsDigit(currentChar))
{
string number = "";
int startPos = _position;
while (_position < _input.Length &&
(char.IsDigit(_input[_position]) || _input[_position] == '.'))
{
number += _input[_position];
_position++;
}
return new Token(TokenType.Number, number, startPos);
}
switch (currentChar)
{
case '+':
_position++;
return new Token(TokenType.Plus, "+", _position - 1);
case '-':
_position++;
return new Token(TokenType.Minus, "-", _position - 1);
case '*':
_position++;
return new Token(TokenType.Multiply, "*", _position - 1);
case '/':
_position++;
return new Token(TokenType.Divide, "/", _position - 1);
case '(':
_position++;
return new Token(TokenType.LeftParen, "(", _position - 1);
case ')':
_position++;
return new Token(TokenType.RightParen, ")", _position - 1);
case ',':
_position++;
return new Token(TokenType.Comma, ",", _position - 1);
case '.':
_position++;
return new Token(TokenType.Dot, ".", _position - 1);
}
throw new Exception($"Invalid character: {currentChar} at position {_position}");
}
return new Token(TokenType.EOF, "", _position);
}
}
public abstract class AstNode
{
public abstract Type GetResultType();
public abstract void Emit(ILGenerator il);
}
public class NumberNode : AstNode
{
private readonly double _value;
public NumberNode(double value)
{
_value = value;
}
public override Type GetResultType() => typeof(double);
public override void Emit(ILGenerator il)
{
il.Emit(OpCodes.Ldc_R8, _value);
}
}
public class StringNode : AstNode
{
private readonly string _value;
public StringNode(string value)
{
_value = value;
}
public override Type GetResultType() => typeof(string);
public override void Emit(ILGenerator il)
{
il.Emit(OpCodes.Ldstr, _value);
}
}
public class SystemCallNode : AstNode
{
private readonly string _typeName;
private readonly string _methodName;
private readonly List<AstNode> _arguments;
private readonly MethodInfo _methodInfo;
public SystemCallNode(string typeName, string methodName, List<AstNode> arguments)
{
_typeName = typeName;
_methodName = methodName;
_arguments = arguments;
// Find the method in the specified type
Type type = Type.GetType(_typeName) ??
Type.GetType($"System.{_typeName}") ??
throw new Exception($"Type not found: {_typeName}");
Type[] parameterTypes = _arguments.Select(arg => arg.GetResultType()).ToArray();
_methodInfo = type.GetMethod(_methodName, parameterTypes) ??
throw new Exception($"Method not found: {_methodName}");
}
public override Type GetResultType() => _methodInfo.ReturnType;
public override void Emit(ILGenerator il)
{
// Emit arguments
foreach (var arg in _arguments)
{
arg.Emit(il);
}
// Emit method call
il.EmitCall(OpCodes.Call, _methodInfo, null);
}
}
public class Parser
{
private readonly Lexer _lexer;
private Token _currentToken;
public Parser(Lexer lexer)
{
_lexer = lexer;
_currentToken = _lexer.GetNextToken();
}
private void Eat(TokenType tokenType)
{
if (_currentToken.Type == tokenType)
_currentToken = _lexer.GetNextToken();
else
throw new Exception($"Expected {tokenType}, got {_currentToken.Type}");
}
public AstNode Parse()
{
return SystemCall();
}
private AstNode SystemCall()
{
if (_currentToken.Type != TokenType.Identifier)
throw new Exception("Expected type name");
string typeName = _currentToken.Value;
Eat(TokenType.Identifier);
if (_currentToken.Type != TokenType.Dot)
throw new Exception("Expected dot operator");
Eat(TokenType.Dot);
if (_currentToken.Type != TokenType.Identifier)
throw new Exception("Expected method name");
string methodName = _currentToken.Value;
Eat(TokenType.Identifier);
// Parse arguments
Eat(TokenType.LeftParen);
var arguments = new List<AstNode>();
if (_currentToken.Type != TokenType.RightParen)
{
arguments.Add(ParseArgument());
while (_currentToken.Type == TokenType.Comma)
{
Eat(TokenType.Comma);
arguments.Add(ParseArgument());
}
}
Eat(TokenType.RightParen);
return new SystemCallNode(typeName, methodName, arguments);
}
private AstNode ParseArgument()
{
switch (_currentToken.Type)
{
case TokenType.Number:
var value = double.Parse(_currentToken.Value);
Eat(TokenType.Number);
return new NumberNode(value);
case TokenType.String:
var strValue = _currentToken.Value;
Eat(TokenType.String);
return new StringNode(strValue);
default:
throw new Exception($"Unexpected token type: {_currentToken.Type}");
}
}
}
public class Compiler
{
private readonly AstNode _ast;
public Compiler(AstNode ast)
{
_ast = ast;
}
public Delegate Compile()
{
var dynamicMethod = new DynamicMethod(
"Execute",
_ast.GetResultType(),
Type.EmptyTypes,
typeof(Compiler).Module,
true);
var il = dynamicMethod.GetILGenerator();
_ast.Emit(il);
il.Emit(OpCodes.Ret);
return dynamicMethod.CreateDelegate(typeof(Func<>).MakeGenericType(_ast.GetResultType()));
}
}
public class Program
{
public static void Main()
{
// Example: Console.WriteLine("Hello, World!")
string input = @"Console.WriteLine(""Hello, World!"")";
var lexer = new Lexer(input);
var parser = new Parser(lexer);
var ast = parser.Parse();
var compiler = new Compiler(ast);
var method = compiler.Compile();
// Execute the compiled code
method.DynamicInvoke();
// Example: Math.Pow(2, 3)
input = "Math.Pow(2, 3)";
lexer = new Lexer(input);
parser = new Parser(lexer);
ast = parser.Parse();
compiler = new Compiler(ast);
method = compiler.Compile();
var result = method.DynamicInvoke();
Console.WriteLine($"Math.Pow(2, 3) = {result}");
}
}
}