-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCompiler.cs
1232 lines (1014 loc) · 39.3 KB
/
Compiler.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using GardensPoint;
namespace GardensPoint
{
public sealed partial class Scanner
{
private string[] _sourceLines;
private string SourceLine(int line)
{
if (_sourceLines == null)
_sourceLines = File.ReadAllLines(Buffer.FileName);
return _sourceLines[line];
}
public int Errors { get; private set; }
public override void yyerror(string message, params object[] args)
{
Errors++;
if (yylloc.StartColumn >= 0 && yylloc.EndColumn > yylloc.StartColumn)
{
string line = SourceLine(yylloc.StartLine - 1);
var whitespace = string.Join("", line.Select(c => c == '\t' ? '\t' : ' ').Take(yylloc.StartColumn));
Console.Error.WriteLine(SourceLine(yylloc.StartLine - 1));
Console.Error.WriteLine(whitespace + new string('^', yylloc.EndColumn - yylloc.StartColumn));
}
Console.Error.WriteLine($"Line {yylloc.StartLine}: {message}\n");
}
private void InvalidToken(string token)
{
Errors++;
Console.Error.WriteLine($"Line {yylloc.StartLine}: Invalid token {token}");
}
}
}
namespace mini_lang
{
#region Extensions
/// <inheritdoc />
/// <summary>
/// This attribute is used to attach a string value to an enum.
/// Mostly used to allow for more verbose error messages when there's
/// something wrong with an operator or its operands.
/// </summary>
[AttributeUsage(AttributeTargets.Field)]
public class TokenAttribute : Attribute
{
public string Token { get; }
public TokenAttribute(string value) => Token = value;
}
public static class Extensions
{
/// <summary>
/// Will get the string value for a given enums value.
/// This will only work if there are Token attributes
/// assigned to the items in the enum.
/// </summary>
public static string GetToken(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get FieldInfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the Token attributes
if (fieldInfo.GetCustomAttributes(typeof(TokenAttribute), false) is TokenAttribute[] attribs)
{
// Return the first value if there was a match.
if (attribs.Length > 0)
return attribs[0].Token;
}
return null;
}
}
#endregion
#region Common
/// <summary>
/// An abstract class serving as a root for the type system.
/// </summary>
public abstract class AbstractType
{
private readonly string _repr;
protected AbstractType(string repr) => _repr = repr;
public override string ToString() => _repr;
}
/// <inheritdoc />
/// <summary>
/// A type-safe enumeration defining all primitive types.
/// </summary>
public class PrimType : AbstractType
{
public static PrimType Integer { get; } = new IntegerT();
public static PrimType Double { get; } = new DoubleT();
public static PrimType Bool { get; } = new BoolT();
private PrimType(string token) : base(token) { }
public sealed class IntegerT : PrimType
{
internal IntegerT() : base("int") { }
}
public sealed class DoubleT : PrimType
{
internal DoubleT() : base("double") { }
}
public sealed class BoolT : PrimType
{
internal BoolT() : base("bool") { }
}
}
public class ArrayType : AbstractType
{
public PrimType ElemType { get; }
public int Dimensions { get; }
public ArrayType(PrimType elemType, int dimensions) : base($"{elemType}[{dimensions}]")
{
ElemType = elemType;
Dimensions = dimensions;
if (dimensions > 32)
Compiler.Error("Cannot declare array of more than 32 dimensions");
}
}
/// <summary>
/// An interface for arbitrary nodes in the AST.
/// </summary>
public interface INode
{
void Accept(INodeVisitor visitor);
}
/// <inheritdoc />
/// <summary>
/// An interface for expressions evaluable to some <see cref="PrimType" />.
/// </summary>
public interface IEvaluable : INode
{
PrimType EvalType { get; }
}
/// <inheritdoc />
/// <summary>
/// An interface for things that can be assigned to.
/// </summary>
public interface IAssignable : IEvaluable
{
void PreStore(IAssignableVisitor visitor);
void PostStore(IAssignableVisitor visitor);
}
#endregion
#region AST
public class Block : INode
{
public List<INode> Statements { get; }
public Block(List<INode> statements) => Statements = statements;
public void Accept(INodeVisitor visitor) => visitor.VisitBlock(this);
}
public class Constant : IEvaluable
{
public string Value { get; }
public PrimType EvalType { get; }
public Constant(string value, PrimType type) => (Value, EvalType) = (value, type);
void INode.Accept(INodeVisitor visitor) => visitor.VisitConstant(this);
}
public readonly struct Identifier
{
public string Name { get; }
public AbstractType Type { get; }
public Identifier(string name, AbstractType type) => (Name, Type) = ($"'{name}'", type);
}
public class Variable : IAssignable
{
public Identifier Identifier { get; }
public PrimType EvalType { get; }
public Variable(Identifier ident)
{
Identifier = ident;
if (ident.Type is PrimType prim)
EvalType = prim;
else
Compiler.Error($"Attempting to use an object of complex type {ident.Type} as a primitive");
}
void INode.Accept(INodeVisitor visitor) => visitor.VisitVariable(this);
void IAssignable.PreStore(IAssignableVisitor visitor) => visitor.PreStoreInVariable(this);
void IAssignable.PostStore(IAssignableVisitor visitor) => visitor.PostStoreInVariable(this);
}
public class Indexing : IAssignable
{
public Identifier Identifier { get; }
public List<IEvaluable> Indices { get; }
public PrimType EvalType { get; }
public Indexing(Identifier identifier, List<IEvaluable> indices)
{
Identifier = identifier;
Indices = indices;
if (Identifier.Type is ArrayType arr)
{
EvalType = arr.ElemType;
if (arr.Dimensions != Indices.Count)
Compiler.Error($"Invalid {Indices.Count}D index for {arr.Dimensions}-dimensional array");
Indices.ForEach(size =>
{
if (size.EvalType != PrimType.Integer)
Compiler.Error($"Invalid array index type {size.EvalType} – expected an {PrimType.Integer}");
});
}
else
Compiler.Error($"Invalid indexing expression - {Identifier.Name} is not of array type");
}
void INode.Accept(INodeVisitor visitor) => visitor.VisitIndexing(this);
void IAssignable.PreStore(IAssignableVisitor visitor) => visitor.PreStoreInArray(this);
void IAssignable.PostStore(IAssignableVisitor visitor) => visitor.PostStoreInArray(this);
}
#region Operators
public class UnaryOp : IEvaluable
{
public enum OpType
{
[Token("~")] BitwiseNot,
[Token("!")] LogicalNot,
[Token("-")] IntNegate,
[Token("(type)")] Conversion,
}
public PrimType EvalType { get; }
public OpType Op { get; }
public IEvaluable Rhs { get; }
/// <summary>
/// Use this constructor for unary operators other than explicit conversions.
/// </summary>
/// <param name="op">Operator type - one of <see cref="OpType"/>s</param>
/// <param name="rhs">Operand</param>
public UnaryOp(OpType op, IEvaluable rhs)
{
Op = op;
Rhs = rhs;
switch (Op)
{
case OpType.IntNegate:
EvalType = Rhs.EvalType;
if (EvalType == PrimType.Bool)
InvalidType();
break;
case OpType.BitwiseNot:
EvalType = PrimType.Integer;
if (Rhs.EvalType != EvalType)
InvalidType();
break;
case OpType.LogicalNot:
EvalType = PrimType.Bool;
if (Rhs.EvalType != EvalType)
InvalidType();
break;
case OpType.Conversion:
Compiler.Error("Invalid conversion - no type specified", true);
break;
}
}
public UnaryOp(PrimType type, IEvaluable rhs)
{
Op = OpType.Conversion;
Rhs = rhs;
EvalType = type;
if (EvalType == PrimType.Bool)
Compiler.Error($"Illegal explicit conversion to {PrimType.Bool}");
}
private void InvalidType() => Compiler.Error($"Invalid operand type: {Op.GetToken()}{Rhs.EvalType}");
void INode.Accept(INodeVisitor visitor) => visitor.VisitUnaryOp(this);
}
/// <inheritdoc />
/// <summary>
/// An abstract base class for all binary operators.
/// </summary>
public abstract class BinOp : IEvaluable
{
public PrimType EvalType { get; protected set; }
public IEvaluable Lhs { get; }
public IEvaluable Rhs { get; }
protected BinOp(IEvaluable lhs, IEvaluable rhs) => (Lhs, Rhs) = (lhs, rhs);
protected void InvalidType(Enum op) =>
Compiler.Error($"Invalid operand types: {Lhs.EvalType} {op.GetToken() ?? "??"} {Rhs.EvalType}");
public abstract void Accept(INodeVisitor visitor);
}
public class MathOp : BinOp
{
public enum OpType
{
[Token("+")] Add,
[Token("-")] Sub,
[Token("*")] Mult,
[Token("/")] Div,
[Token("&")] BitAnd,
[Token("|")] BitOr,
}
public OpType Op { get; }
public MathOp(OpType op, IEvaluable lhs, IEvaluable rhs) : base(lhs, rhs)
{
Op = op;
// Bit operators only accept Integers as operands
if (op == OpType.BitOr || op == OpType.BitAnd)
{
EvalType = PrimType.Integer;
if (lhs.EvalType != PrimType.Integer || rhs.EvalType != PrimType.Integer)
InvalidType(Op);
}
else // Only + - * /
{
if (lhs.EvalType == PrimType.Bool || rhs.EvalType == PrimType.Bool)
{
// Setting some type to allow for error recovery
EvalType = PrimType.Bool;
InvalidType(Op);
}
else if (lhs.EvalType != rhs.EvalType) // Integers or Doubles
{
EvalType = PrimType.Double;
}
else
{
EvalType = lhs.EvalType;
}
}
}
public override void Accept(INodeVisitor visitor) => visitor.VisitMathOp(this);
}
public class CompOp : BinOp
{
public enum OpType
{
[Token("==")] Eq,
[Token("!=")] Neq,
[Token(">")] Gt,
[Token(">=")] Gte,
[Token("<")] Lt,
[Token("<=")] Lte,
}
public OpType Op { get; }
public PrimType CastTo { get; }
public CompOp(OpType op, IEvaluable lhs, IEvaluable rhs) : base(lhs, rhs)
{
Op = op;
EvalType = PrimType.Bool;
if (op == OpType.Eq || op == OpType.Neq)
{
if (lhs.EvalType == rhs.EvalType)
return;
if (lhs.EvalType == PrimType.Bool || rhs.EvalType == PrimType.Bool)
InvalidType(Op);
else
CastTo = PrimType.Double;
}
else
{
if (lhs.EvalType == PrimType.Bool || rhs.EvalType == PrimType.Bool)
InvalidType(Op);
else if (lhs.EvalType != rhs.EvalType)
CastTo = PrimType.Double;
}
}
public override void Accept(INodeVisitor visitor) => visitor.VisitCompOp(this);
}
public class LogicOp : BinOp
{
public enum OpType
{
[Token("&&")] And,
[Token("||")] Or
}
public OpType Op { get; }
public LogicOp(OpType op, IEvaluable lhs, IEvaluable rhs) : base(lhs, rhs)
{
Op = op;
EvalType = PrimType.Bool;
if (Lhs.EvalType != PrimType.Bool || Rhs.EvalType != PrimType.Bool)
InvalidType(Op);
}
public override void Accept(INodeVisitor visitor) => visitor.VisitLogicOp(this);
}
public class Assignment : IEvaluable
{
public IAssignable Lhs { get; }
public IEvaluable Rhs { get; }
public PrimType EvalType => Lhs.EvalType;
public Assignment(IAssignable assignable, IEvaluable rhs)
{
Lhs = assignable;
Rhs = rhs;
if (EvalType != Rhs.EvalType && !(EvalType == PrimType.Double && Rhs.EvalType == PrimType.Integer))
Compiler.Error($"Cannot assign a value of type {Rhs.EvalType}, expected {EvalType}");
}
void INode.Accept(INodeVisitor visitor) => visitor.VisitAssignment(this);
}
#endregion
#region Statements
public class ExprStatement : INode
{
public IEvaluable Expression { get; }
public ExprStatement(IEvaluable expression) => Expression = expression;
void INode.Accept(INodeVisitor visitor) => visitor.VisitExprStatement(this);
}
public class Declaration : INode
{
public Identifier Identifier { get; }
public bool Initialize { get; }
public Declaration(Identifier identifier, bool init) => (Identifier, Initialize) = (identifier, init);
void INode.Accept(INodeVisitor visitor) => visitor.VisitDeclaration(this);
}
public class ArrayCreation : INode
{
public Indexing Indexing { get; }
public ArrayCreation(Indexing indexing) => Indexing = indexing;
void INode.Accept(INodeVisitor visitor) => visitor.VisitArrayCreation(this);
}
public class Write : INode
{
public IEvaluable Rhs { get; }
public Write(IEvaluable rhs) => Rhs = rhs;
void INode.Accept(INodeVisitor visitor) => visitor.VisitWrite(this);
}
public class WriteString : INode
{
public string String { get; }
public WriteString(string s) => String = s;
void INode.Accept(INodeVisitor visitor) => visitor.VisitWriteString(this);
}
public class Read : INode
{
public IAssignable Target { get; }
public Read(IAssignable target) => Target = target;
void INode.Accept(INodeVisitor visitor) => visitor.VisitRead(this);
}
public class Return : INode
{
void INode.Accept(INodeVisitor visitor) => visitor.VisitReturn();
}
public class Break : INode
{
public int Levels { get; }
public Break(int levels)
{
Levels = levels;
if (Levels < 1)
Compiler.Error("Break level must be positive");
}
void INode.Accept(INodeVisitor visitor) => visitor.VisitBreak(this);
}
public class Continue : INode
{
void INode.Accept(INodeVisitor visitor) => visitor.VisitContinue();
}
public class While : INode
{
public IEvaluable Condition { get; }
public INode Body { get; }
public While(IEvaluable condition, INode body)
{
Condition = condition;
Body = body;
if (condition.EvalType != PrimType.Bool)
Compiler.Error($"Loop condition evaluates to {condition.EvalType} and not {PrimType.Bool}");
}
void INode.Accept(INodeVisitor visitor) => visitor.VisitWhile(this);
}
public class IfElse : INode
{
public IEvaluable Condition { get; }
public INode ThenBlock { get; }
public INode ElseBlock { get; }
public IfElse(IEvaluable condition, INode thenBlock, INode elseBlock = null)
{
Condition = condition;
ThenBlock = thenBlock;
ElseBlock = elseBlock;
}
void INode.Accept(INodeVisitor visitor) => visitor.VisitIfElse(this);
}
public class Program : INode
{
public Block MainBlock { get; }
public Program(Block mainBlock) => MainBlock = mainBlock;
public void Accept(INodeVisitor visitor) => visitor.VisitProgram(this);
}
#endregion
#endregion
#region Visitors
public interface INodeVisitor
{
// Primitives
void VisitProgram(Program program);
void VisitConstant(Constant constant);
void VisitVariable(Variable variable);
void VisitIndexing(Indexing indexing);
// Statements
void VisitBlock(Block block);
void VisitExprStatement(ExprStatement exprStatement);
void VisitDeclaration(Declaration declaration);
void VisitAssignment(Assignment assignment);
void VisitArrayCreation(ArrayCreation arrayCreation);
void VisitWrite(Write write);
void VisitWriteString(WriteString writeString);
void VisitRead(Read read);
void VisitWhile(While @while);
void VisitIfElse(IfElse ifElse);
void VisitBreak(Break @break);
void VisitContinue();
void VisitReturn();
// Operators
void VisitMathOp(MathOp mathOp);
void VisitCompOp(CompOp compOp);
void VisitLogicOp(LogicOp logicOp);
void VisitUnaryOp(UnaryOp unaryOp);
}
public interface IAssignableVisitor
{
void PreStoreInVariable(Variable variable);
void PostStoreInVariable(Variable variable);
void PreStoreInArray(Indexing indexing);
void PostStoreInArray(Indexing indexing);
}
public class CodeBuilder : INodeVisitor, IAssignableVisitor
{
private int _labelNum;
private readonly StreamWriter _sw;
private readonly Stack<(string, string)> _loopLabels = new Stack<(string, string)>();
// Helper dictionaries
private readonly Dictionary<PrimType, string> _longTypes = new Dictionary<PrimType, string>
{
{PrimType.Integer, "int32"},
{PrimType.Double, "float64"},
{PrimType.Bool, "bool"}
};
private readonly Dictionary<PrimType, string> _shortTypes = new Dictionary<PrimType, string>
{
{PrimType.Integer, "i4"},
{PrimType.Double, "r8"},
{PrimType.Bool, "i1"}
};
private string UniqueLabel(string prefix) => $"{prefix}_{_labelNum++}";
public string OutputFile { get; }
public CodeBuilder(string file, string outFile = null)
{
OutputFile = outFile ?? file + ".il";
_sw = new StreamWriter(OutputFile);
}
private void EmitLine(string code) => _sw.WriteLine(code);
// IAssignableVisitor methods
public void PreStoreInVariable(Variable variable) { }
public void PostStoreInVariable(Variable variable) => EmitLine($"stloc {variable.Identifier.Name}");
public void PreStoreInArray(Indexing indexing)
{
EmitLine($"ldloc {indexing.Identifier.Name}"); // TODO: same as in VisitVariable
indexing.Indices.ForEach(ix => ix.Accept(this));
}
public void PostStoreInArray(Indexing indexing)
{
int dim = indexing.Indices.Count;
if (dim == 1)
{
EmitLine($"stelem.{_shortTypes[indexing.EvalType]}");
}
else
{
var zeros = string.Join(",", Enumerable.Repeat("0...", dim));
var ints = string.Join(", ", Enumerable.Repeat("int32", dim));
EmitLine($"call instance void {_longTypes[indexing.EvalType]}[{zeros}]::Set({ints}, {_longTypes[indexing.EvalType]})");
}
}
// INodeVisitor methods
public void VisitProgram(Program program)
{
EmitPrologue();
program.MainBlock.Accept(this);
EmitEpilogue();
_sw.Flush();
_sw.Close();
}
public void VisitBlock(Block block) => block.Statements.ForEach(x => x.Accept(this));
public void VisitExprStatement(ExprStatement exprStatement)
{
exprStatement.Expression.Accept(this);
EmitLine("pop");
}
public void VisitVariable(Variable variable) => EmitLine($"ldloc {variable.Identifier.Name}");
public void VisitDeclaration(Declaration declaration)
{
Identifier ident = declaration.Identifier;
string initStr = declaration.Initialize ? "init " : "";
switch (ident.Type)
{
case ArrayType arr when arr.Dimensions == 1:
EmitLine($".locals {initStr}( {_longTypes[arr.ElemType]}[] {ident.Name} )");
break;
case ArrayType arr:
{
var zeros = string.Join(",", Enumerable.Repeat("0...", arr.Dimensions));
EmitLine($".locals {initStr}( {_longTypes[arr.ElemType]}[{zeros}] {ident.Name} )");
break;
}
case PrimType prim:
EmitLine($".locals {initStr}( {_longTypes[prim]} {ident.Name} )");
break;
}
}
public void VisitConstant(Constant constant)
{
switch (constant.EvalType)
{
case PrimType.IntegerT _:
EmitLine($"ldc.i4 {constant.Value}");
break;
case PrimType.DoubleT _:
EmitLine($"ldc.r8 {constant.Value}");
break;
case PrimType.BoolT _:
EmitLine(constant.Value == "true" ? "ldc.i4.1" : "ldc.i4.0");
break;
}
}
private void EmitConversion(PrimType targetType)
{
switch (targetType)
{
case PrimType.DoubleT _:
EmitLine("conv.r8");
break;
default:
EmitLine("conv.i4");
break;
}
}
public void VisitAssignment(Assignment assignment)
{
assignment.Lhs.PreStore(this);
assignment.Rhs.Accept(this);
if (assignment.EvalType != assignment.Rhs.EvalType)
EmitConversion(assignment.EvalType);
assignment.Lhs.PostStore(this);
// Create a read so that we leave a value on the stack
assignment.Lhs.Accept(this);
}
public void VisitIndexing(Indexing indexing)
{
EmitLine($"ldloc {indexing.Identifier.Name}"); // TODO: same as in VisitVariable
indexing.Indices.ForEach(x => x.Accept(this));
int dim = indexing.Indices.Count;
if (dim == 1)
{
EmitLine($"ldelem.{_shortTypes[indexing.EvalType]}");
}
else
{
var zeros = string.Join(",", Enumerable.Repeat("0...", dim));
var ints = string.Join(", ", Enumerable.Repeat("int32", dim));
string tc = _longTypes[indexing.EvalType];
EmitLine($"call instance {tc} {tc}[{zeros}]::Get({ints})");
}
}
public void VisitArrayCreation(ArrayCreation arrayCreation)
{
int dim = arrayCreation.Indexing.Indices.Count;
arrayCreation.Indexing.Indices.ForEach(node => node.Accept(this));
if (dim == 1)
{
var boxedTypes = new Dictionary<PrimType, string>
{
{PrimType.Integer, "Int32"},
{PrimType.Double, "Double"},
{PrimType.Bool, "Boolean"}
};
EmitLine($"newarr [mscorlib]System.{boxedTypes[arrayCreation.Indexing.EvalType]}");
}
else
{
var zeros = string.Join(",", Enumerable.Repeat("0...", dim));
var ints = string.Join(", ", Enumerable.Repeat("int32", dim));
EmitLine($"newobj instance void {_longTypes[arrayCreation.Indexing.EvalType]}[{zeros}]::.ctor({ints})");
}
EmitLine($"stloc {arrayCreation.Indexing.Identifier.Name}");
}
public void VisitWrite(Write write)
{
switch (write.Rhs.EvalType)
{
case PrimType.DoubleT _:
EmitLine(
"call class [mscorlib]System.Globalization.CultureInfo class [mscorlib]System.Globalization.CultureInfo::get_InvariantCulture()");
EmitLine(@"ldstr ""{0:0.000000}""");
write.Rhs.Accept(this);
EmitLine("box [mscorlib]System.Double");
EmitLine("call string string::Format(class [mscorlib]System.IFormatProvider, string, object)");
EmitLine("call void [mscorlib]System.Console::Write(string)");
break;
default:
write.Rhs.Accept(this);
EmitLine($"call void [mscorlib]System.Console::Write({_longTypes[write.Rhs.EvalType]})");
break;
}
}
public void VisitWriteString(WriteString writeString)
{
EmitLine($"ldstr {writeString.String}");
EmitLine("call void [mscorlib]System.Console::Write(string)");
}
public void VisitRead(Read read)
{
read.Target.PreStore(this);
EmitLine("call string class [mscorlib]System.Console::ReadLine()");
if (read.Target.EvalType == PrimType.Double)
{
EmitLine(
"call class [mscorlib]System.Globalization.CultureInfo class [mscorlib]System.Globalization.CultureInfo::get_InvariantCulture()");
EmitLine("call float64 float64::Parse(string, class [mscorlib]System.IFormatProvider)");
}
else
{
EmitLine($"call {_longTypes[read.Target.EvalType]} {_longTypes[read.Target.EvalType]}::Parse(string)");
}
read.Target.PostStore(this);
}
public void VisitBreak(Break @break) => EmitLine($"br {_loopLabels.ElementAt(@break.Levels - 1).Item2}");
public void VisitContinue() => EmitLine($"br {_loopLabels.Peek().Item1}");
public void VisitReturn() => EmitLine("leave EndMain");
public void VisitWhile(While @while)
{
string startWhile = UniqueLabel("WHILE"),
endWhile = UniqueLabel("ENDWHILE");
EmitLine($"{startWhile}:");
@while.Condition.Accept(this);
EmitLine($"brfalse {endWhile}");
_loopLabels.Push((startWhile, endWhile));
@while.Body.Accept(this);
_loopLabels.Pop();
EmitLine($"br {startWhile}");
EmitLine($"{endWhile}:");
}
public void VisitIfElse(IfElse ifElse)
{
string elseLabel = UniqueLabel("ELSE");
ifElse.Condition.Accept(this);
EmitLine($"brfalse {elseLabel}");
ifElse.ThenBlock.Accept(this);
if (ifElse.ElseBlock != null)
{
string endLabel = UniqueLabel("ENDIF");
EmitLine($"br {endLabel}");
EmitLine($"{elseLabel}:");
ifElse.ElseBlock.Accept(this);
EmitLine($"{endLabel}:");
}
else
EmitLine($"{elseLabel}:");
}
public void VisitMathOp(MathOp mathOp)
{
mathOp.Lhs.Accept(this);
if (mathOp.Lhs.EvalType != mathOp.EvalType)
EmitConversion(mathOp.EvalType);
mathOp.Rhs.Accept(this);
if (mathOp.Rhs.EvalType != mathOp.EvalType)
EmitConversion(mathOp.EvalType);
var opcodes = new Dictionary<MathOp.OpType, string>
{
{MathOp.OpType.Add, "add"},
{MathOp.OpType.Sub, "sub"},
{MathOp.OpType.Mult, "mul"},
{MathOp.OpType.Div, "div"},
{MathOp.OpType.BitAnd, "and"},
{MathOp.OpType.BitOr, "or"},
};
EmitLine(opcodes[mathOp.Op]);
}
public void VisitCompOp(CompOp compOp)
{
compOp.Lhs.Accept(this);
if (compOp.CastTo is PrimType type && compOp.Lhs.EvalType != type)
EmitConversion(type);
compOp.Rhs.Accept(this);
if (compOp.CastTo is PrimType type2 && compOp.Rhs.EvalType != type2)
EmitConversion(type2);
switch (compOp.Op)
{
case CompOp.OpType.Eq:
EmitLine("ceq");
break;
case CompOp.OpType.Neq:
EmitLine("ceq\nldc.i4.0\nceq");
break;
case CompOp.OpType.Gt:
EmitLine("cgt");
break;
case CompOp.OpType.Gte:
EmitLine("clt\nldc.i4.0\nceq");
break;
case CompOp.OpType.Lt:
EmitLine("clt");
break;
case CompOp.OpType.Lte:
EmitLine("cgt\nldc.i4.0\nceq");
break;
}
}
public void VisitLogicOp(LogicOp logicOp)
{
string label = UniqueLabel("LOGIC");
logicOp.Lhs.Accept(this);
EmitLine("dup");
EmitLine(logicOp.Op == LogicOp.OpType.And ? $"brfalse {label}" : $"brtrue {label}");
EmitLine("pop");
logicOp.Rhs.Accept(this);
EmitLine($"{label}:");
}
public void VisitUnaryOp(UnaryOp unaryOp)
{
unaryOp.Rhs.Accept(this);
switch (unaryOp.Op)
{
case UnaryOp.OpType.BitwiseNot:
EmitLine("not");
break;
case UnaryOp.OpType.LogicalNot:
EmitLine("ldc.i4.0\nceq");
break;
case UnaryOp.OpType.IntNegate:
EmitLine("neg");
break;
case UnaryOp.OpType.Conversion:
EmitConversion(unaryOp.EvalType);
break;
}
}
private void EmitPrologue()
{
EmitLine(".assembly extern mscorlib { }");