-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
2339 lines (2086 loc) · 75.3 KB
/
Copy pathForm1.cs
File metadata and controls
2339 lines (2086 loc) · 75.3 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
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.ComponentModel;
using System.Drawing;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing.Text;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static compiler2024.CompilerBeta;
namespace compiler2024
{
public partial class CompilerBeta : System.Windows.Forms.Form
{
public string sourceProgram;
public int currentPointer;
public token currentToken;
public IdentifierTable Identifiers;
public TemporaryVariableTable tempVars;
public QuadrupleTable midCodes;
private void print(string s)
{
listBox.Items.Add(s);
}
private void printToken(token t)
{
listBox.Items.Add($"[{t.type}, {t.value}]");
}
private void buttonTokenize_Click(object sender, EventArgs e)
{
sourceProgram = textBox1.Text + "#";
listBox.Items.Clear();
listBox1.Items.Clear();
print(sourceProgram);
currentPointer = 0;// Get the first token
currentToken = tokenizer();// Print the first token using printToken method
printToken(currentToken);
// Loop to process all tokens until the end-of-input marker
while (currentToken.type != "#")
{
currentToken = tokenizer(); // Get the next token
printToken(currentToken); // Print each token within square brackets
}
listBox.Items.Add("end..");// Indicate the end of tokenization
}
public CompilerBeta()
{
InitializeComponent();
this.KeyPreview = true; // Enable key preview
listBox.KeyDown += new KeyEventHandler(listBox_KeyDown); // Attach KeyDown event handler for listBox
listBox1.KeyDown += new KeyEventHandler(listBox1_KeyDown); // Attach KeyDown event handler for listBox1
}
private void CopyAllItemsToClipboard(ListBox listBox)
{
StringBuilder sb = new StringBuilder();
foreach (var item in listBox.Items)
{
sb.AppendLine(item.ToString());
}
Clipboard.SetText(sb.ToString());
}
private void listBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
CopyAllItemsToClipboard(listBox);
}
}
private void listBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
CopyAllItemsToClipboard(listBox1);
}
}
public class token
{
public string type { get; set; }
public string value { get; set; }
public token(string t, string v)
{
this.type = t;
this.value = v;
}
public override string ToString()
{
return string.Concat(new string[]
{
"(",
this.type,
",",
this.value,
")"
});
}
}
private token tokenizer()
{
int state = 0;
string word = "";
while (sourceProgram[currentPointer] != '#')
{
// Skip spaces
if (sourceProgram[currentPointer] == ' ')
{
currentPointer++;
continue;
}
if (state == 0)
{
// Handling single character tokens and state transitions
if (sourceProgram[currentPointer] == ';')
{
word += sourceProgram[currentPointer];
currentPointer++;
return new token("semiColon", word);
}
if (sourceProgram[currentPointer] == 'i')
{
state = 200;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == ',')
{
word += sourceProgram[currentPointer];
currentPointer++;
return new token("comma", word);
}
if (sourceProgram[currentPointer] == '$')
{
state = 400;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == '=')
{
state = 500;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == '(')
{
word += sourceProgram[currentPointer];
currentPointer++;
return new token("leftP", word);
}
if (sourceProgram[currentPointer] == ')')
{
word += sourceProgram[currentPointer];
currentPointer++;
return new token("rightP", word);
}
if (sourceProgram[currentPointer] == 't')
{
state = 800;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == 'e')
{
state = 900;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == 'w')
{
state = 1000;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == 'd')
{
state = 1100;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == '+')
{
word += sourceProgram[currentPointer];
currentPointer++;
return new token("opPlus", word);
}
if (sourceProgram[currentPointer] == '*')
{
word += sourceProgram[currentPointer];
currentPointer++;
return new token("opTime", word);
}
if (sourceProgram[currentPointer] == '<')
{
state = 1400;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == '>')
{
state = 1500;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == '!')
{
state = 1600;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == 'b')
{
state = 1700;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] >= '0' && sourceProgram[currentPointer] <= '9')
{
state = 1800;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
}
// Handling keyword 'int'
if (state == 200)
{
if (sourceProgram[currentPointer] == 'n')
{
state = 201;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == 'f')
{
word += sourceProgram[currentPointer];
currentPointer++;
state = 0;
return new token("kw_if", word);
}
}
if (state == 201)
{
if (sourceProgram[currentPointer] == 't')
{
word += sourceProgram[currentPointer];
currentPointer++;
state = 0;
return new token("kw_int", word);
}
}
// Handling identifiers
if (state == 400)
{
if (sourceProgram[currentPointer] >= 'a' && sourceProgram[currentPointer] <= 'z')
{
word += sourceProgram[currentPointer];
state = 401;
currentPointer++;
continue;
}
}
if (state == 401)
{
if ((sourceProgram[currentPointer] >= 'a' && sourceProgram[currentPointer] <= 'z') ||
(sourceProgram[currentPointer] >= '0' && sourceProgram[currentPointer] <= '9'))
{
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
else
{
state = 0;
return new token("identifier", word);
}
}
// Handling assignment and logical operators
if (state == 500)
{
if (sourceProgram[currentPointer] == '=')
{
state = 501;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
state = 0;
return new token("assign", word);
}
if (state == 501)
{
state = 0;
return new token("log_op", word);
}
// Handling keyword 'then'
if (state == 800)
{
if (sourceProgram[currentPointer] == 'h')
{
state = 801;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
}
if (state == 801)
{
if (sourceProgram[currentPointer] == 'e')
{
state = 802;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
}
if (state == 802)
{
if (sourceProgram[currentPointer] == 'n')
{
word += sourceProgram[currentPointer];
currentPointer++;
state = 0;
return new token("kw_then", word);
}
}
// Handling keyword 'else' and 'end'
if (state == 900)
{
if (sourceProgram[currentPointer] == 'l')
{
state = 901;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
if (sourceProgram[currentPointer] == 'n')
{
state = 910;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
}
if (state == 901)
{
if (sourceProgram[currentPointer] == 's')
{
state = 902;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
}
if (state == 902)
{
if (sourceProgram[currentPointer] == 'e')
{
word += sourceProgram[currentPointer];
currentPointer++;
state = 0;
return new token("kw_else", word);
}
}
if (state == 910)
{
if (sourceProgram[currentPointer] == 'd')
{
word += sourceProgram[currentPointer];
currentPointer++;
state = 0;
return new token("kw_end", word);
}
}
// Handling keyword 'while'
if (state == 1000)
{
if (sourceProgram[currentPointer] == 'h')
{
state = 1001;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
}
if (state == 1001)
{
if (sourceProgram[currentPointer] == 'i')
{
state = 1002;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
}
if (state == 1002)
{
if (sourceProgram[currentPointer] == 'l')
{
state = 1003;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
}
if (state == 1003)
{
if (sourceProgram[currentPointer] == 'e')
{
word += sourceProgram[currentPointer];
currentPointer++;
state = 0;
return new token("kw_while", word);
}
}
// Handling keyword 'do'
if (state == 1100)
{
if (sourceProgram[currentPointer] == 'o')
{
word += sourceProgram[currentPointer];
currentPointer++;
state = 0;
return new token("kw_do", word);
}
}
// Handling relational operators
if (state == 1400)
{
if (sourceProgram[currentPointer] == '=')
{
word += sourceProgram[currentPointer];
currentPointer++;
state = 0;
return new token("log_op", word);
}
else
{
state = 0;
return new token("log_op", word);
}
}
if (state == 1500)
{
if (sourceProgram[currentPointer] == '=')
{
word += sourceProgram[currentPointer];
currentPointer++;
state = 0;
return new token("log_op", word);
}
else
{
state = 0;
return new token("log_op", word);
}
}
if (state == 1600)
{
if (sourceProgram[currentPointer] == '=')
{
word += sourceProgram[currentPointer];
currentPointer++;
state = 0;
return new token("log_op", word);
}
else
{
state = 0;
return new token("log_op", word);
}
}
// Handling keyword 'begin'
if (state == 1700)
{
if (sourceProgram[currentPointer] == 'e')
{
state = 1701;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
}
if (state == 1701)
{
if (sourceProgram[currentPointer] == 'g')
{
state = 1702;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
}
if (state == 1702)
{
if (sourceProgram[currentPointer] == 'i')
{
state = 1703;
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
}
if (state == 1703)
{
if (sourceProgram[currentPointer] == 'n')
{
word += sourceProgram[currentPointer];
currentPointer++;
state = 0;
return new token("kw_begin", word);
}
}
// Handling numeric literals starting with digits
if (state == 1800)
{
if (sourceProgram[currentPointer] >= '0' && sourceProgram[currentPointer] <= '9')
{
word += sourceProgram[currentPointer];
currentPointer++;
continue;
}
else
{
state = 0;
return new token("integer", word);
}
}
// Error handling for unexpected characters
print("Error(@position" + currentPointer.ToString() + "): Unexpected character or not defined yet '" + sourceProgram[currentPointer].ToString() + "'");
currentPointer++;
}
return new token("#", "#"); // Return termination token when end of input is reached
}
public class Identifier
{
public string name { get; set; }
public string type { get; set; }
public string value { get; set; }
public Identifier(string n)
{
this.name = n;
this.type = "";
this.value = "";
}
public override string ToString()
{
return $" {this.name} | [{this.type}] | [{this.value}]";
}
}
public class IdentifierTable
{
private List<Identifier> list;
public IdentifierTable()
{
list = new List<Identifier>();
}
public Identifier getIdentifierByName(string name)
{
foreach (Identifier t in list)
{
if (t.name == name) return t;
}
return null;
}
public Boolean add(string name)
{
Identifier t = getIdentifierByName(name);
if (t != null) return false;
list.Add(new Identifier(name));
return true;
}
public Boolean updateTypeByName(string name, string type)
{
Identifier t = getIdentifierByName(name);
if (t == null) return false;
t.type = type;
return true;
}
public Boolean updateValueByName(string name, string value)
{
Identifier t = getIdentifierByName(name);
if (t == null) return false;
t.value = value;
return true;
}
public void dump(ListBox lb)
{
lb.Items.Add("<--------- Identifier Table --------->");
lb.Items.Add(string.Format("{0,-12} | {1,-10} | {2,-10}", "Name", "Type", "Value"));
lb.Items.Add(new string('-', 36));
foreach (Identifier t in list)
{
lb.Items.Add(string.Format("{0,-12} | {1,-10} | {2,-10}", t.name, t.type, t.value));
}
lb.Items.Add(new string('-', 36));
}
}
public class TemporaryVariableTable
{
private List<Identifier> list;
public TemporaryVariableTable()
{
list = new List<Identifier>();
}
public Identifier CreateNewTempVar()
{
int index = list.Count;
Identifier t = new Identifier($"T{index}");
list.Add(t);
return t;
}
public void dump(ListBox lb)
{
lb.Items.Add("<---- Temp Variable Table ---------->");
lb.Items.Add(string.Format("{0,-12} | {1,-10} | {2,-10}", "Name", "Type", "Value"));
lb.Items.Add(new string('-', 36));
foreach (Identifier t in list)
{
lb.Items.Add(string.Format("{0,-12} | {1,-10} | {2,-10}", t.name, t.type, t.value));
}
lb.Items.Add(new string('-', 36));
}
}
public class Quadruple
{
public string Op1 { get; set; }
public string Op2 { get; set; }
public string Op3 { get; set; }
public string Op4 { get; set; }
public Quadruple(string op, string opr1, string opr2, string result)
{
this.Op1 = op;
this.Op2 = opr1;
this.Op3 = opr2;
this.Op4 = result;
}
public override string ToString()
{
return $"({this.Op1}, {this.Op2}, {this.Op3}, {this.Op4})";
}
}
public class QuadrupleTable
{
private List<Quadruple> list;
public int NXQ
{
get { return list.Count; }
}
public QuadrupleTable()
{
list = new List<Quadruple>();
}
public bool Add(string op, string opr1, string opr2, string result)
{
this.list.Add(new Quadruple(op, opr1, opr2, result));
return true; // Assuming add is always successful, adjust as necessary
}
public Boolean BackPatch(int index, string result)
{
if (index >= 0 && index < list.Count) // Ensuring the index is within valid range
{
list[index].Op4 = result; // Update the fourth element (result) of the specified Quadruple
return true;
}
return false;
}
public void dump(ListBox lb)
{
lb.Items.Add("<-------- Mid-Code Table ------------->");
lb.Items.Add(string.Format("{0,-3} | {1,-4} | {2,-6} | {3,-6} | {4,-6}", "Idx", "Op", "Opr1", "Opr2", "Result"));
lb.Items.Add(new string('-', 38));
for (int i = 0; i < list.Count; i++)
{
Quadruple q = list[i];
lb.Items.Add(string.Format("{0,-3} | {1,-4} | {2,-6} | {3,-6} | {4,-6}", i, q.Op1, q.Op2, q.Op3, q.Op4));
}
lb.Items.Add(new string('-', 38));
}
}
private void debug(string s)
{
listBox1.Items.Add(s);
}
private void HandleParseClick(object sender, EventArgs e)
{
sourceProgram = textBox1.Text + "#";
listBox.Items.Clear();
listBox1.Items.Clear();
Identifiers = new IdentifierTable();
tempVars = new TemporaryVariableTable();
midCodes = new QuadrupleTable();
debug(sourceProgram);
currentPointer = 0;
currentToken = tokenizer();
print(currentToken.ToString());
// Directly use the result of parseProgram in the if condition
if (parseProgram())
{
print("end..");
}
else
{
print("error...");
}
midCodes.dump(listBox);
Identifiers.dump(this.listBox1);
tempVars.dump(this.listBox1);
}
public bool match(string expectedType)
{
if (currentToken.type == expectedType)
{
debug(string.Concat(new string[]
{
"expec ",
expectedType,
", currentToken ",
currentToken.type,
", matched."
}));
currentToken = tokenizer();
print(currentToken.ToString());
return true;
}
else
{
print(string.Concat(new string[]
{
"Error: expec ",
expectedType,
", got ",
currentToken.ToString(),
"."
}));
return false;
}
}
public bool parseProgram()
{
print("< program > → <variable declaration section> ; <statements section>");
if (!parseDeclarationSection())
{
print("error: Fail to parse <variable declaration section>");
return false;
}
if (!match("semiColon"))
{
return false;
}
if (!parseStatementsSection())
{
print("error: Fail to parse <statements section>");
return false;
}
debug("[< program > → <variable declaration section> ; <statements section>]end");
return true;
}
public bool parseDeclarationSection()
{
print("< variable declaration section > → int <variable list>");
string type = currentToken.value;
if (!match("kw_int"))
{
return false;
}
if (!parseVariableList(type))
{
print("error: Fail to parse <variable list>");
return false;
}
debug("[< variable declaration section > → int <variable list>]end");
return true;
}
public bool parseVariableList(string type)
{
print("< variable list > → identifier A");
string name = currentToken.value;
if (!match("identifier"))
{
return false;
}
if (!Identifiers.add(name))
{
print("error: Fail to add identifier " + name);
return false;
}
if (!Identifiers.updateTypeByName(name, type))
{
print("error: Fail to update identifier " + name + " with type " + type);
return false;
}
if (!parseA(type))
{
print("error: Fail to parse A");
return false;
}
debug("[< variable list > → identifier A]end");
return true;
}
public bool parseA(string type)
{
if (currentToken.type == "comma")
{
print("A → , identifier A");
if (!match("comma"))
{
return false;
}
string name = currentToken.value;
if (!match("identifier"))
{
return false;
}
if (!Identifiers.add(name))
{
print("error: Fail to add identifier " + name);
return false;
}
if (!Identifiers.updateTypeByName(name, type))
{
print("error: Fail to update identifier " + name + " with type " + type);
return false;
}
if (!parseA(type))
{
print("error: Fail to parse A");
return false;
}
debug("[A → , identifier A]end");
return true;
}
else
{
if (currentToken.type == "semiColon")
{
print("A →ε");
return true;
}
print("can't choose production for parseA with " + currentToken.ToString());
return false;
}
}
public bool parseStatementsSection()
{
print("< statements section > → <statement>; B");
if (!parseStatement())
{
print("error: Fail to parse <statement>");
return false;
}
if (!match("semiColon"))
{
return false;
}
if (!parseB())
{
print("error: Fail to parse B");
return false;
}
debug("[< statements section > → <statement>; B]end");
return true;
}
public bool parseB()
{
if (currentToken.type == "identifier" || currentToken.type == "kw_if" || currentToken.type == "kw_while")
{
print("B → <statement>; B");
if (!parseStatement())
{
print("error: Fail to parse <statement>");
return false;
}
if (!match("semiColon"))
{
return false;
}
if (!parseB())
{
print("error: Fail to parse B");
return false;
}
debug("[B → <statement>; B]end");
return true;
}
else
{
if (currentToken.type == "#" || currentToken.type == "kw_end")
{
print("B →ε");
return true;
}
print("can't choose production for parseB with " + currentToken.ToString());
return false;