-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parser.cs
711 lines (618 loc) · 21.3 KB
/
Parser.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JFICompiler
{
/// <summary>
/// Generates an AST from the tokens provided by the tokenizer.
/// </summary>
public class Parser
{
private Token[] Tokens;
public Parser(Token[] _Tokens)
{
Tokens = _Tokens;
Labels = new Dictionary<string, int>();
}
public Block Run()
{
Block MainBlock = new Block(Tokens, this, null);
MainBlock.SetOffsets();
return MainBlock;
}
Dictionary<string, int> Labels;
public string NewLabel()
{
return NewLabel("l");
}
public string NewLabel(string Prefix)
{
if (!Labels.ContainsKey(Prefix))
{
Labels.Add(Prefix, 0);
}
string Label = Prefix + Labels[Prefix];
Labels[Prefix]++;
return Label;
}
}
public class Block
{
private List<Block> ChildBlocks;
public Block ParentBlock;
public Parser Parser;
public int BlockOffset;
private int CurrentOffset;
public string EndLabel;
private Queue<Statement> Statements;
private Token[] BlockTokens;
private int Index;
Dictionary<string, int> IntegerVariables;
public Block(Token[] _Tokens, Parser _Parser, Block _ParentBlock)
{
if(_ParentBlock != null)
{
_ParentBlock.ChildBlocks.Add(this);
}
Parser = _Parser;
Statements = new Queue<Statement>();
ChildBlocks = new List<Block>();
BlockTokens = _Tokens;
ParentBlock = _ParentBlock;
Index = 0;
BlockOffset = 0;
CurrentOffset = 0;
IntegerVariables = new Dictionary<string, int>();
EndLabel = Parser.NewLabel("BLOCK");
while (Index < BlockTokens.Length)
{
Token T = BlockTokens[Index];
HandleStatement(T);
}
}
public int SetOffsets()
{
int Capacity = 4 * IntegerVariables.Count;
int OffsetSum = -Capacity;
foreach(Block C in ChildBlocks)
{
C.BlockOffset = OffsetSum;
OffsetSum -= C.SetOffsets();
}
return OffsetSum;
}
public void DeclareVariable(string Identifier)
{
if (IntegerVariables.ContainsKey(Identifier))
{
throw new Exception("Variable already declared.");
}
IntegerVariables.Add(Identifier, CurrentOffset);
CurrentOffset -= 4;
}
private void HandleStatement(Token T)
{
switch (T.Type)
{
case TokenType.KEYWORD:
{
switch (T.Body.ToUpper())
{
case "IF":
{
Token Value1 = BlockTokens[Index + 2];
string Operator = BlockTokens[Index + 3].Body;
Token Value2 = BlockTokens[Index + 4];
Index += 6;
Block SuccessBlock = GetBlock();
Statements.Enqueue(new IfStatement(this, Value1, Value2, Operator, SuccessBlock, null));
break;
}
case "WHILE":
{
Token Value1 = BlockTokens[Index + 2];
string Operator = BlockTokens[Index + 3].Body;
Token Value2 = BlockTokens[Index + 4];
Index += 6;
Block LoopBlock = GetBlock();
Statements.Enqueue(new WhileStatement(this, Value1, Value2, Operator, LoopBlock));
break;
}
case "PRINT":
{
Token Value = BlockTokens[Index + 2];
Index += 5;
Statements.Enqueue(new PrintStatement(this, Value));
break;
}
case "RETURN":
{
Index += 2;
Statements.Enqueue(new ReturnStatement(this));
break;
}
default: { throw new Exception("Invalid Keyword!"); }
}
break;
}
case TokenType.IDENTIFIER:
{
string Identifier = BlockTokens[Index].Body;
if(BlockTokens[Index + 1].Type == TokenType.OPERATOR && BlockTokens[Index + 1].Body == "=")
{
Token Value = BlockTokens[Index + 2];
Statements.Enqueue(new AssignStatement(this, Identifier, Value));
Index += 4;
}
else if (BlockTokens[Index + 1].Type == TokenType.OPERATOR && BlockTokens[Index + 1].Body == "+=")
{
Token Value = BlockTokens[Index + 2];
Statements.Enqueue(new IncrementStatement(this, Identifier, Value));
Index += 4;
}
else if (BlockTokens[Index + 1].Type == TokenType.OPERATOR && BlockTokens[Index + 1].Body == "-=")
{
Token Value = BlockTokens[Index + 2];
Statements.Enqueue(new DecrementStatement(this, Identifier, Value));
Index += 4;
}
break;
}
case TokenType.TYPE:
{
switch (T.Body.ToUpper())
{
case "INT":
{
string Identifier = BlockTokens[Index + 1].Body;
Token Value = BlockTokens[Index + 3];
DeclareVariable(Identifier);
Statements.Enqueue(new AssignStatement(this, Identifier, Value));
Index += 5;
break;
}
default: { throw new Exception("Invalid Keyword!"); }
}
break;
}
default: { throw new Exception("Invalid Statement!"); }
}
}
private Block GetBlock()
{
Token CurrentToken = BlockTokens[Index];
if (CurrentToken.Type != TokenType.SYMBOL || CurrentToken.Body != "{")
{
throw new Exception("Expected '{'");
}
Index++;
CurrentToken = BlockTokens[Index];
int LayerCounter = 0;
List<Token> Tokens = new List<Token>();
while (Index < BlockTokens.Length)
{
Tokens.Add(BlockTokens[Index]);
if (CurrentToken.Type == TokenType.SYMBOL && CurrentToken.Body == "{")
{
LayerCounter++;
}
if (CurrentToken.Type == TokenType.SYMBOL && CurrentToken.Body == "}")
{
LayerCounter--;
if (LayerCounter < 0)
{
break;
}
}
Index++;
if (Index >= BlockTokens.Length)
{
throw new Exception("Expected '}'");
}
CurrentToken = BlockTokens[Index];
}
Tokens.RemoveAt(Tokens.Count - 1);
Index++;
return new Block(Tokens.ToArray(), Parser, this);
}
private Expression GetExpression()
{
return null;
}
private Expression GetExpressionParanthesis()
{
Token CurrentToken = BlockTokens[Index];
if(CurrentToken.Type != TokenType.SYMBOL || CurrentToken.Body != "(")
{
throw new Exception("Expected '('");
}
Index++;
CurrentToken = BlockTokens[Index];
int LayerCounter = 0;
List<Token> ExpressionTokens = new List<Token>();
while (CurrentToken.Type == TokenType.CONSTANT || CurrentToken.Type == TokenType.IDENTIFIER || CurrentToken.Type == TokenType.OPERATOR || CurrentToken.Type == TokenType.SYMBOL)
{
ExpressionTokens.Add(BlockTokens[Index]);
if (CurrentToken.Type == TokenType.SYMBOL && CurrentToken.Body == "(")
{
LayerCounter++;
}
if (CurrentToken.Type == TokenType.SYMBOL && CurrentToken.Body == ")")
{
LayerCounter--;
if(LayerCounter < 0)
{
break;
}
}
Index++;
if (Index >= BlockTokens.Length)
{
throw new Exception("Expected ')'");
}
CurrentToken = BlockTokens[Index];
}
Index = 0;
while(Index < ExpressionTokens.Count)
{
Token T = ExpressionTokens[Index];
if(T.Type == TokenType.CONSTANT)
{
}
}
return null;
}
public string GenerateCode()
{
string Output = String.Empty;
Output += "ADDI $sp, $sp, " + BlockOffset;
Output += "\n";
foreach (Statement S in Statements)
{
if(S == null) { continue; }
Output += S.GenerateCode();
Output += "\n";
}
Output += EndLabel + ":";
Output += "\n";
Output += "ADDI $sp, $sp, " + -BlockOffset;
Output += "\n";
return Output;
}
internal int GetVariableOffset(string Identifier)
{
if (IntegerVariables.ContainsKey(Identifier))
{
return IntegerVariables[Identifier];
}
else if (ParentBlock != null && ParentBlock.IntegerVariables.ContainsKey(Identifier))
{
return ParentBlock.IntegerVariables[Identifier] - BlockOffset;
}
else
{
throw new Exception("Variable out of scope.");
}
}
}
public abstract class Statement
{
protected Block CurrentBlock;
public Statement(Block _CurrentBlock)
{
CurrentBlock = _CurrentBlock;
}
public virtual string GenerateCode()
{
return String.Empty;
}
protected string GetBranchCommand(string Operator)
{
switch (Operator)
{
case "==": { return "BEQ"; }
case "!=": { return "BNQ"; }
case ">": { return "BGT"; }
case ">=": { return "BGE"; }
case "<": { return "BLT"; }
case "<=": { return "BLE"; }
default: { throw new Exception("Invalid Operator"); }
}
}
protected string GetVariableOrConstant(Token T, string Register)
{
string Output = String.Empty;
if (T.Type == TokenType.CONSTANT)
{
Output += "LI " + Register + ", " + T.Body;
}
else if (T.Type == TokenType.IDENTIFIER)
{
int Offset = CurrentBlock.GetVariableOffset(T.Body);
Output += "LW " + Register + ", " + Offset + "($sp)";
}
else if(T.Type == TokenType.KEYWORD && T.Body.ToUpper() == "READ")
{
Output += "LI $v0, 5";
Output += "\n";
Output += "SYSCALL";
Output += "\n";
Output += "MOVE " + Register + ", $v0";
}
else
{
throw new Exception("Invalid Argument");
}
return Output;
}
}
public class IncrementStatement : Statement
{
string Identifier;
Token Value;
public IncrementStatement(Block _CurrentBlock, string _Identifier, Token _Value) : base(_CurrentBlock)
{
Identifier = _Identifier;
Value = _Value;
}
public override string GenerateCode()
{
string Output = String.Empty;
int Offset = CurrentBlock.GetVariableOffset(Identifier);
Output += "LW $t0, " + Offset + "($sp)";
Output += "\n";
Output += GetVariableOrConstant(Value, "$t1");
Output += "\n";
Output += "ADD $t0, $t0, $t1";
Output += "\n";
Output += "SW $t0, " + Offset + "($sp)";
return Output;
}
}
public class DecrementStatement : Statement
{
string Identifier;
Token Value;
public DecrementStatement(Block _CurrentBlock, string _Identifier, Token _Value) : base(_CurrentBlock)
{
Identifier = _Identifier;
Value = _Value;
}
public override string GenerateCode()
{
string Output = String.Empty;
int Offset = CurrentBlock.GetVariableOffset(Identifier);
Output += "LW $t0, " + Offset + "($sp)";
Output += "\n";
Output += GetVariableOrConstant(Value, "$t1");
Output += "\n";
Output += "SUB $t0, $t0, $t1";
Output += "\n";
Output += "SW $t0, " + Offset + "($sp)";
return Output;
}
}
public class ReturnStatement : Statement
{
public ReturnStatement(Block _CurrentBlock) : base(_CurrentBlock)
{
}
public override string GenerateCode()
{
string Output = String.Empty;
Output += "ADDI $sp, $sp, " + -CurrentBlock.BlockOffset;
Output += "\n";
Output += "J " + CurrentBlock.ParentBlock.EndLabel;
Output += "\n";
return Output;
}
}
public class PrintStatement : Statement
{
Token Value;
public PrintStatement(Block _CurrentBlock, Token _Value) : base(_CurrentBlock)
{
Value = _Value;
}
public override string GenerateCode()
{
string Output = String.Empty;
Output += GetVariableOrConstant(Value, "$a0");
Output += "\n";
Output += "LI $v0, 1";
Output += "\n";
Output += "SYSCALL";
return Output;
}
}
public class AssignStatement : Statement
{
string Identifier;
Token Value;
public AssignStatement(Block _CurrentBlock, string _Identifier, Token _Value) : base(_CurrentBlock)
{
Identifier = _Identifier;
Value = _Value;
}
public override string GenerateCode()
{
string Output = String.Empty;
int Offset = CurrentBlock.GetVariableOffset(Identifier);
Output += GetVariableOrConstant(Value, "$t0");
Output += "\n";
Output += "SW $t0, " + Offset + "($sp)";
return Output;
}
}
public class IfStatement : Statement
{
Token Value1;
Token Value2;
Block SuccessBlock;
Block FailBlock;
string Operator;
public IfStatement(Block _CurrentBlock, Token _Value1, Token _Value2, string _Operator, Block _SuccessBlock, Block _FailBlock) : base(_CurrentBlock)
{
Value1 = _Value1;
Value2 = _Value2;
SuccessBlock = _SuccessBlock;
FailBlock = _FailBlock;
Operator = _Operator;
}
public override string GenerateCode()
{
string StartLabel = CurrentBlock.Parser.NewLabel("IF");
string SuccessLabel = CurrentBlock.Parser.NewLabel("IF");
string EndLabel = CurrentBlock.Parser.NewLabel("IF");
string Output = String.Empty;
Output += GetVariableOrConstant(Value1, "$t1");
Output += "\n";
Output += GetVariableOrConstant(Value2, "$t2");
Output += "\n";
Output += GetBranchCommand(Operator) + " $t1, $t2, " + SuccessLabel;
Output += "\n";
if (FailBlock != null)
{
Output += FailBlock.GenerateCode();
Output += "\n";
}
Output += "J " + EndLabel;
Output += "\n";
Output += SuccessLabel + ":";
Output += "\n";
Output += SuccessBlock.GenerateCode();
Output += "\n";
Output += EndLabel + ":";
return Output;
}
}
public class WhileStatement : Statement
{
Token Value1;
Token Value2;
Block LoopBlock;
string Operator;
public WhileStatement(Block _CurrentBlock, Token _Value1, Token _Value2, string _Operator, Block _LoopBlock) : base(_CurrentBlock)
{
Value1 = _Value1;
Value2 = _Value2;
Operator = _Operator;
LoopBlock = _LoopBlock;
}
public override string GenerateCode()
{
string StartLabel = CurrentBlock.Parser.NewLabel("WHILE");
string BodyLabel = CurrentBlock.Parser.NewLabel("WHILE");
string EndLabel = CurrentBlock.Parser.NewLabel("WHILE");
string Output = String.Empty;
Output += StartLabel + ":";
Output += "\n";
Output += GetVariableOrConstant(Value1, "$t1");
Output += "\n";
Output += GetVariableOrConstant(Value2, "$t2");
Output += "\n";
Output += GetBranchCommand(Operator) + " $t1, $t2, " + BodyLabel;
Output += "\n";
Output += "J " + EndLabel;
Output += "\n";
Output += BodyLabel + ":";
Output += "\n";
Output += LoopBlock.GenerateCode();
Output += "\n";
Output += "J " + StartLabel;
Output += "\n";
Output += EndLabel + ":";
return Output;
}
}
abstract class Expression
{
public virtual string GenerateCode()
{
return String.Empty;
}
}
abstract class ExpressionLayer
{
protected Expression Value1;
protected Expression Value2;
public ExpressionLayer(Token _Value, Token _Operator)
{
if (_Operator.Body == "+")
{
if (_Value.Type == TokenType.CONSTANT)
{
Value1 = new ExpressionConstant(int.Parse(_Value.Body));
}
else if (_Value.Type == TokenType.IDENTIFIER)
{
Value1 = new ExpressionVariable(_Value.Body);
}
else
{
throw new Exception("Invalid Expression");
}
}
}
protected virtual string GetOperator()
{
return null;
}
}
class E1 : ExpressionLayer
{
public E1(Token _Value, Token _Operator) : base(_Value, _Operator) { }
protected override string GetOperator()
{
return "+";
}
}
class E2 : ExpressionLayer
{
public E2(Token _Value, Token _Operator) : base(_Value, _Operator) { }
protected override string GetOperator()
{
return "*";
}
}
class E3 : ExpressionLayer
{
public E3(Token _Value, Token _Operator) : base(_Value, _Operator) { }
protected override string GetOperator()
{
return null;
}
}
class E4 : ExpressionLayer
{
public E4(Token _Value, Token _Operator) : base(_Value, _Operator)
{
}
}
class ExpressionConstant : Expression
{
int Value;
public ExpressionConstant(int _Value)
{
Value = _Value;
}
public override string GenerateCode()
{
return Value.ToString();
}
}
class ExpressionVariable : Expression
{
string Identifier;
public ExpressionVariable(string _Identifier)
{
Identifier = _Identifier;
}
public override string GenerateCode()
{
return "LOAD " + Identifier;
}
}
}