forked from aasmundeldhuset/Compiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CilCodeGenerator.cs
309 lines (281 loc) · 10.4 KB
/
CilCodeGenerator.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
using System;
using System.IO;
using System.Linq;
namespace Compiler
{
public class CilCodeGenerator : ICodeGenerator, ISyntaxNodeVisitor
{
private readonly TextWriter _output;
private int _labelCount;
private int? _innermostWhileLabelIndex;
public CilCodeGenerator(TextWriter output)
{
_output = output;
}
public void Generate(ProgramNode program)
{
Visit(program);
}
public void Visit(ProgramNode program)
{
_labelCount = 0;
_innermostWhileLabelIndex = null;
EmitHead();
foreach (var function in program.Functions)
{
function.Accept(this);
}
EmitTail();
}
public void Visit(FunctionNode function)
{
string parameterTypes = string.Join(", ", Enumerable.Repeat("int32", function.Parameters.Count));
_output.WriteLine(" .method public static int32 {0}({1}) cil managed {{", function.Name.Name, parameterTypes);
if (function.Name.Name == "Main")
Emit(".entrypoint");
if (function.LocalVariableCount > 0)
{
var variableTypes = string.Join(", ", Enumerable.Repeat("int32", function.LocalVariableCount));
Emit(string.Format(".locals init ({0})", variableTypes));
}
function.Body.Accept(this);
_output.WriteLine(" }");
}
public void Visit(BlockStatementNode block)
{
EmitComment("Begin block");
foreach (var statement in block.Statements)
{
statement.Accept(this);
}
EmitComment("End block");
}
public void Visit(AssignmentStatementNode assignment)
{
assignment.Expression.Accept(this);
EmitComment("Assign to {0}", assignment.Variable.Name);
if (assignment.SymbolTableEntry.Type == SymbolTableEntryType.Variable)
Emit("stloc", assignment.SymbolTableEntry.Index);
else // Parameter
Emit("starg", assignment.SymbolTableEntry.Index);
}
public void Visit(ReturnStatementNode statement)
{
statement.Expression.Accept(this);
EmitComment("Return");
Emit("ret");
}
public void Visit(NullStatementNode statement)
{
if (_innermostWhileLabelIndex == null)
throw new Exception("There is no loop to continue or break out of");
if (statement.Type == NullStatementType.Continue)
{
EmitComment("Continue");
Emit("br", "while_cond_" + _innermostWhileLabelIndex);
}
else if (statement.Type == NullStatementType.Break)
{
EmitComment("Break");
Emit("br", "while_end_" + _innermostWhileLabelIndex);
}
else
{
throw new Exception("Unknown null statement type " + statement.Type);
}
}
public void Visit(IfStatementNode statement)
{
int labelIndex = _labelCount++;
string falseLabel = "if_false_" + labelIndex;
string endLabel = "if_end_" + labelIndex;
EmitComment("If: condition");
statement.Condition.Accept(this);
EmitComment("If: jump");
Emit("brfalse", falseLabel);
EmitComment("If: begin true part");
statement.ThenBody.Accept(this);
if (statement.ElseBody != null)
Emit("br", endLabel);
EmitComment("If: end true part");
EmitLabel(falseLabel);
if (statement.ElseBody != null)
{
EmitComment("If: begin false part");
statement.ElseBody.Accept(this);
EmitComment("If: end false part");
EmitLabel(endLabel);
}
}
public void Visit(WhileStatementNode statement)
{
int labelIndex = _labelCount++;
int? previousInnermostWhileLabelIndex = _innermostWhileLabelIndex;
_innermostWhileLabelIndex = labelIndex;
string conditionLabel = "while_condition_" + labelIndex;
string endLabel = "while_end_" + labelIndex;
EmitComment("While: condition");
EmitLabel(conditionLabel);
statement.Condition.Accept(this);
Emit("brfalse", endLabel);
EmitComment("While: body");
statement.Body.Accept(this);
Emit("br", conditionLabel);
EmitLabel(endLabel);
_innermostWhileLabelIndex = previousInnermostWhileLabelIndex;
}
public void Visit(PrintStatementNode print)
{
foreach (var item in print.Items)
{
item.Accept(this);
EmitComment("Print one item");
if (item is StringNode)
Emit("call", "void [mscorlib]System.Console::Write(string)");
else
Emit("call", "void [mscorlib]System.Console::Write(int32)");
}
EmitComment("Done printing");
Emit("call", "void [mscorlib]System.Console::WriteLine()");
}
public void Visit(InputStatementNode input)
{
foreach (var target in input.TargetVariables)
{
EmitComment("Input to " + target.Variable.Name);
Emit("call", "string [mscorlib]System.Console::ReadLine()");
Emit("call", "int32 [mscorlib]System.Int32::Parse(string)");
if (target.SymbolTableEntry.Type == SymbolTableEntryType.Variable)
Emit("stloc", target.SymbolTableEntry.Index);
else // Parameter
Emit("starg", target.SymbolTableEntry.Index);
}
}
public void Visit(BinaryExpressionNode expression)
{
if (new[] {Operator.NotEqual, Operator.LessThanOrEqual, Operator.GreaterThanOrEqual}.Contains(expression.Operator))
{
EmitComment("Prepare for binary operator " + expression.Operator);
Emit("ldc.i4", 1);
}
expression.Left.Accept(this);
expression.Right.Accept(this);
EmitComment("Binary operator " + expression.Operator);
switch (expression.Operator)
{
case Operator.Equal:
Emit("ceq");
break;
case Operator.NotEqual:
Emit("ceq");
Emit("sub");
break;
case Operator.LessThan:
Emit("clt");
break;
case Operator.LessThanOrEqual:
Emit("cgt");
Emit("sub");
break;
case Operator.GreaterThan:
Emit("cgt");
break;
case Operator.GreaterThanOrEqual:
Emit("clt");
Emit("sub");
break;
case Operator.Add:
Emit("add");
break;
case Operator.Subtract:
Emit("sub");
break;
case Operator.Multiply:
Emit("mul");
break;
case Operator.Divide:
Emit("div");
break;
default:
throw new Exception("Unsupported binary operator: " + expression.Operator);
}
}
public void Visit(UnaryExpressionNode expression)
{
expression.Child.Accept(this);
EmitComment("Unary operator " + expression.Operator);
if (expression.Operator == Operator.Subtract)
Emit("neg");
else
throw new Exception("Unsupported unary operator: " + expression.Operator);
}
public void Visit(FunctionCallNode call)
{
foreach (var argument in call.Arguments)
{
argument.Accept(this);
}
string argumentTypes = string.Join(", ", Enumerable.Repeat("int32", call.Arguments.Count));
string signature = string.Format("int32 Vsl.VslMain::{0}({1})", call.Name.Name, argumentTypes);
EmitComment("Call function " + call.Name.Name);
Emit("call", signature);
}
public void Visit(ConstantExpressionNode constant)
{
constant.Value.Accept(this);
}
public void Visit(VariableReferenceNode reference)
{
EmitComment("{0}", reference.Variable.Name);
if (reference.SymbolTableEntry.Type == SymbolTableEntryType.Variable)
Emit("ldloc", reference.SymbolTableEntry.Index);
else // Parameter
Emit("ldarg", reference.SymbolTableEntry.Index);
}
public void Visit(DeclarationNode declaration)
{
// Declarations only have semantic meaning; no instructions are needed
}
public void Visit(IdentifierNode identifier)
{
// Identifiers are handled (if necessary) by their parent node
}
public void Visit(IntegerNode integer)
{
EmitComment("{0}", integer.Value);
Emit("ldc.i4", integer.Value);
}
public void Visit(StringNode str)
{
EmitComment('"' + str.Value + '"');
Emit("ldstr", '"' + str.Value + '"');
}
private void Emit(string instruction, params object[] args)
{
_output.WriteLine(" " + string.Join("\t", new[] {instruction}.Concat(args)));
}
private void EmitLabel(string labelName)
{
_output.WriteLine(labelName + ":");
}
private void EmitHead()
{
_output.WriteLine(
@".assembly extern mscorlib {}
.assembly VSL {}
.module VSL.exe
.namespace Vsl {
.class public auto ansi VslMain extends [mscorlib]System.Object {");
}
private void EmitTail()
{
_output.WriteLine(
@" }
}");
}
private void EmitComment(string format, params object[] args)
{
_output.WriteLine(" // " + format, args);
}
}
}