-
Notifications
You must be signed in to change notification settings - Fork 194
/
Copy pathParser.java
1931 lines (1835 loc) · 99.4 KB
/
Parser.java
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
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import static java.lang.System.exit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
/**
*
* @author wangjs
*/
//This class is used to make the grammar checking, semantic analysis and code generation.
//The symbol tables will also be created in this class
public class Parser {
//symbolTables[0] = classStaticVariableSymbolTable
//symbolTables[1] = classFieldVariableSymbolTable
//symbolTables[2] = functionVarSymbolTable
//symbolTables[3] = functionArgumentSymbolTable
//symbolTables[4] = otherClassFunctionsSymbolTable
private Lexer lexer = null;
private SymbolTable[] symbolTables = new SymbolTable[5];
private String textContent = null;
private JackClasses jackClasses = null;
private String Type = "int|char|boolean|ID|void|String|Array";
private String otherClassType = "";
private File vmFile = null;
private String className = "";
private String expressionReturnType = "";
private String functionName = "";
private String subroutineKind = "";
private String returnType = "";
private String oldToken = "";
private String lastFunctionName = "";
private boolean arrayInitOrNot = false;
private boolean constructorOrNot = false;
private boolean methodOrNot = false;
private int ifCounter = 0;
private int whileCounter = 0;
private int pushCounter = 0;
private int eleNumberCounter = 0;
private Map classFieldVar = new HashMap();
private Map classArrayNumOfEle = new HashMap();
private Map functionArrayNumOfEle = new HashMap();
//Initialize the lexer and each symboltable
public Parser(Lexer lexer) {
this.lexer = lexer;
lexer.initLocalFile();
symbolTables[0] = new SymbolTable();
symbolTables[1] = new SymbolTable();
symbolTables[2] = new SymbolTable();
symbolTables[3] = new SymbolTable();
symbolTables[4] = new SymbolTable();
textContent = this.lexer.getTextContent();
jackClasses = new JackClasses();
parserAnalysis();
}
//Create the VM file if it not exists currently
private void vmFileCreate() {
try {
vmFile = new File(lexer.getFolderPath() + File.separator + className + ".vm");
if (!vmFile.exists()) {
vmFile.createNewFile();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//Insert the VM codes into the VM file
private void vmCodeInput(String vmCodes) {
try {
File log = new File(lexer.getFolderPath() + File.separator + className + ".vm");
FileWriter fileWriter = new FileWriter(log.getAbsoluteFile(), true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(vmCodes);
bufferedWriter.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//Output the error information and terminate the execution of the parser
private void error(String errorInfor) {
System.out.printf("%s\n", errorInfor);
exit(0);
}
//Check if the class used in current Jack source codes exists in the local folder
private boolean localFileCheck(String className) {
try {
className += ".jack";
File files = new File(lexer.getFolderPath());
File[] allFile = files.listFiles();
for (File f : allFile) {
if (f.isFile()) {
if (className.equals(f.getName())) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
//Clear the values of the temporary variables in the symbol tables
private void symbolTableVarClear() {
for (SymbolTable symbolTable : symbolTables) {
symbolTable.memorySegment = "";
symbolTable.dataType = "";
symbolTable.returnType = "";
symbolTable.functionType = "";
symbolTable.numOfArgs = 0;
symbolTable.numOfVar = 0;
symbolTable.offset = 0;
symbolTable.initOrNot = false;
}
}
//Exact tokens from the lexical analyser and call the corresponding proecessing methods
private void parserAnalysis() {
try {
while (lexer.getReadIndex() < textContent.length() - 2) {
//Identify the token to call corresponding methods
Token newToken = lexer.GetNextToken();
if (newToken.Token.equals("class")) {
classCheck();
vmFileCreate();
ClassesFunctionsReference();
} else if (newToken.Token.equals("constructor")
|| newToken.Token.equals("function")
|| newToken.Token.equals("method")) {
if (!functionName.equals(lastFunctionName)) {
error("Error: in class: " + className + ", function \""
+ functionName + "\" doesn't have return statement");
}
if (newToken.Token.equals("method")) {
methodOrNot = true;
} else if (newToken.Token.equals("constructor")) {
constructorOrNot = true;
}
subroutineKind = newToken.Token;
functionCheck();
} else if (newToken.Token.equals("field")) {
classVarDeclarCheck();
} else if (newToken.Token.equals("var")) {
functionVarDeclarCheck();
} else if (newToken.Token.equals("let")) {
letStatementCheck();
} else if (newToken.Token.equals("if")) {
ifStatementCheck();
} else if (newToken.Token.equals("while")) {
whileStatementCheck();
} else if (newToken.Token.equals("do")) {
doStatementCheck();
} else if (newToken.Token.equals("return")) {
lastFunctionName = functionName;
returnStatementCheck();
}
}
if (!functionName.equals(lastFunctionName)) {
error("Error: function \"" + functionName
+ "\" doesn't have return statement");
}
} catch (Exception e) {
e.printStackTrace();
}
}
//Check if the format of the class is correct
private void classCheck() {
Token lastToken = null;
if (!lexer.PeekNextToken().Type.toString().equals("ID")) {
error("Error: in class: " + className + ", identifier is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
className = lexer.PeekNextToken().Token;
Type += ("|" + className);
otherClassType += className;
lexer.GetNextToken();
}
//Check the grammar of the source codes between the braces
if (!lexer.PeekNextToken().Token.equals("{")) {
error("Error: in class: " + className + ", \"{\" is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
lexer.GetNextToken();
}
//Record the current index for recovering
int oldIndex = lexer.getReadIndex();
Lexer.newLineCheck = false;
//Get the last token
while (lexer.getReadIndex() < textContent.length() - 2) {
if (!lexer.PeekNextToken().Token.equals("")) {
lastToken = lexer.PeekNextToken();
}
lexer.GetNextToken();
}
//Recover the index to the original value
lexer.setReadIndex(oldIndex);
Lexer.newLineCheck = true;
//Check if the last token is right brace
if (!lastToken.Token.equals("}")) {
error("Error: in class: " + className + ", \"}\" is expected, line: "
+ lastToken.LineNumber);
}
}
/*Declare a new lexer and exact each token from source codes to find all
other classes used in current source codes. Then call the methods to search
their variables and methods.*/
private void ClassesFunctionsReference() {
Lexer classCheckLexer = new Lexer(className + ".jack");
classCheckLexer.initLocalFile();
//Read all tokens from source codes to find all kinds of variables
while (classCheckLexer.getReadIndex() < classCheckLexer.getTextContent().length() - 2) {
if (classCheckLexer.PeekNextToken().Token.equals("var")
|| classCheckLexer.PeekNextToken().Token.equals("field")
|| classCheckLexer.PeekNextToken().Token.equals("static")) {
classCheckLexer.GetNextToken();
boolean jackLibrariesOrNot = false;
for (String library : jackClasses.jackLibraries) {
if (classCheckLexer.PeekNextToken().Token.equals(library)) {
jackLibrariesOrNot = true;
break;
}
}
//If the data type is not pre-defined or Jack libraries
if (!jackLibrariesOrNot) {
Type += ("|" + classCheckLexer.PeekNextToken().Token);
otherClassType += ("|" + classCheckLexer.PeekNextToken().Token);
if (!classCheckLexer.PeekNextToken().Token.equals(className)) {
classFunctionsCheck(classCheckLexer.PeekNextToken().Token);
classStaticDeclarCheck(classCheckLexer.PeekNextToken().Token);
}
}
}
classCheckLexer.GetNextToken();
}
classFunctionsCheck(className);
classStaticDeclarCheck(className);
}
//This method is used to search and record all subroutines in the current class
private void classFunctionsCheck(String name) {
Pattern pattern = Pattern.compile(Type);
ArrayList<String> fieldVars = new ArrayList<String>();
Token lastToken = null;
String functionType = "";
String dataType = "";
//Declare a new lexer to get the tokens
Lexer temLexer = new Lexer(name + ".jack");
temLexer.initLocalFile();
/*Construct a loop to supervise the value of index for terminating the loop
when end of source codes have been reached.*/
while (temLexer.getReadIndex() < temLexer.getTextContent().length() - 2) {
//Store all fields belonging to the current class
if (temLexer.PeekNextToken().Token.equals("field")) {
temLexer.GetNextToken();
if (!(pattern.matcher(temLexer.PeekNextToken().Token).matches()
|| localFileCheck(temLexer.PeekNextToken().Token))) {
error("Error: in class: " + name + ", keyword is expected, line: "
+ temLexer.GetNextToken().LineNumber);
} else {
dataType = temLexer.PeekNextToken().Token;
temLexer.GetNextToken();
}
while (true) {
if (!temLexer.PeekNextToken().Type.toString().equals("ID")) {
error("Error: in class: " + name + ", identifier is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
} else {
fieldVars.add(dataType);
temLexer.GetNextToken();
}
if (!temLexer.PeekNextToken().Token.equals(",")) {
break;
} else {
temLexer.GetNextToken();
}
}
if (!temLexer.PeekNextToken().Token.equals(";")) {
error("Error: in class: " + name + ", \";\" is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
}
/*Store the information of all subroutines into the symbol table and
check if the grammar of these subroutines are correct*/
} else if (temLexer.PeekNextToken().Token.equals("function")
|| temLexer.PeekNextToken().Token.equals("method")
|| temLexer.PeekNextToken().Token.equals("constructor")) {
functionType = temLexer.PeekNextToken().Token;
temLexer.GetNextToken();
int numOfVar = 0;
String localFunctionName = "";
String localReturnType = "";
ArrayList<String> argumentsDataType = new ArrayList<String>();
if (!pattern.matcher(temLexer.PeekNextToken().Token).matches()
&& !pattern.matcher(temLexer.PeekNextToken().Type.toString()).matches()) {
error("Error: in class: " + name + ", keyword is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
} else {
localReturnType = temLexer.PeekNextToken().Token;
temLexer.GetNextToken();
}
if (!temLexer.PeekNextToken().Type.toString().equals("ID")) {
error("Error: in class: " + name + ", identifier is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
} else {
localFunctionName = temLexer.PeekNextToken().Token;
temLexer.GetNextToken();
}
//Check if the grammar in the argument list is correct
if (!temLexer.PeekNextToken().Token.equals("(")) {
error("Error: in class: " + name + ", \"(\" is expected, line: "
+ temLexer.GetNextToken().LineNumber);
} else {
temLexer.GetNextToken();
while (!temLexer.PeekNextToken().Token.equals(")")) {
if (!pattern.matcher(temLexer.PeekNextToken().Token).matches()
&& !pattern.matcher(temLexer.PeekNextToken().Type.toString()).matches()) {
error("Error: in class: " + name + ", keyword is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
} else {
//Store the data type can be accepted for type conversion
if (temLexer.PeekNextToken().Token.equals("Array")) {
argumentsDataType.add("(int|Array|class|null|all)");
} else if (temLexer.PeekNextToken().Token.equals("String")) {
argumentsDataType.add("(String|null|all)");
} else if (temLexer.PeekNextToken().Token.equals("char")) {
argumentsDataType.add("(int|char|all)");
} else if (temLexer.PeekNextToken().Token.equals("boolean")) {
argumentsDataType.add("(int|boolean|all)");
} else if (temLexer.PeekNextToken().Token.equals("int")) {
argumentsDataType.add("(int|all)");
} else {
argumentsDataType.add("(" + temLexer.PeekNextToken().Token + "|null|Array)");
}
temLexer.GetNextToken();
}
if (!temLexer.PeekNextToken().Type.toString().equals("ID")) {
error("Error: in class: " + name + ", identifier is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
} else {
temLexer.GetNextToken();
}
if (!temLexer.PeekNextToken().Token.equals(",")) {
break;
} else {
temLexer.GetNextToken();
}
}
if (!temLexer.PeekNextToken().Token.equals(")")) {
error("Error: in class: " + name + ", \")\" is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
} else {
temLexer.GetNextToken();
}
}
/*Check if the grammar of braces are correct and count the number
of the local variables in the braces used in the code generation*/
if (!temLexer.PeekNextToken().Token.equals("{")) {
error("Error: in class: " + name + ", \"{\" is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
} else {
int counterLB = 0;
int counterRB = 0;
int oldIndex = 0;
int result = 0;
counterLB++;
temLexer.GetNextToken();
oldIndex = temLexer.getReadIndex();
temLexer.newLineCheck = false;
//Count the number of local variables
while (temLexer.getReadIndex() < temLexer.getTextContent().length() - 2) {
if (temLexer.PeekNextToken().Token.equals("var")) {
temLexer.GetNextToken();
if (!pattern.matcher(temLexer.PeekNextToken().Token).matches()) {
error("Error: in class: " + name + ", keyword is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
} else {
temLexer.GetNextToken();
}
while (true) {
if (!temLexer.PeekNextToken().Type.toString().equals("ID")) {
error("Error: in class: " + name + ", identifier is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
} else {
numOfVar++;
temLexer.GetNextToken();
}
if (!temLexer.PeekNextToken().Token.equals(",")) {
break;
} else {
temLexer.GetNextToken();
}
}
if (!temLexer.PeekNextToken().Token.equals(";")) {
error("Error: in class: " + name + ", \";\" is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
}
}
if (temLexer.PeekNextToken().Token.equals("{")) {
counterLB++;
} else if (temLexer.PeekNextToken().Token.equals("}")) {
counterRB++;
}
lastToken = temLexer.GetNextToken();
if (counterLB == counterRB) {
result = 1;
break;
}
}
if (result == 0) {
error("Error: in class: " + name + ", \"}\" is expected, line: "
+ temLexer.PeekNextToken().LineNumber);
}
temLexer.setReadIndex(oldIndex);
temLexer.newLineCheck = true;
}
//Store the information of subroutines into the symbol table
if (symbolTables[4].findFunctionSymbol(name + "." + localFunctionName)) {
error("Error: in class: " + name + ", function redeclaration, line:"
+ temLexer.PeekNextToken().LineNumber);
} else {
if (functionType.equals("function")) {
symbolTables[4].addFunctionSymbolTable(name + "."
+ localFunctionName, Symbol.SymbolType.function,
argumentsDataType, localReturnType, numOfVar);
} else if (functionType.equals("method")) {
symbolTables[4].addFunctionSymbolTable(name + "."
+ localFunctionName, Symbol.SymbolType.method,
argumentsDataType, localReturnType, numOfVar);
} else {
symbolTables[4].addFunctionSymbolTable(name + "."
+ localFunctionName, Symbol.SymbolType.constructor,
argumentsDataType, localReturnType, numOfVar);
}
}
}
temLexer.GetNextToken();
}
//Store the arraylist used to store the field variables into a dictionary
classFieldVar.put(name, fieldVars);
}
//This method is used to check if the grammar of subroutine in current class is correct
private void functionCheck() throws Exception {
symbolTables[2].setCounter(0);
symbolTables[3].setCounter(0);
symbolTables[2].symbols.clear();
symbolTables[3].symbols.clear();
functionArrayNumOfEle.clear();
ifCounter = 0;
whileCounter = 0;
//If current subroutine is a method, the first argument should be 'this'
if (methodOrNot) {
symbolTables[3].addIdentifierSymbolTable("this",
Symbol.SymbolType.argument, className, className, "this");
}
//Check the grammar of the definition of subroutine
Pattern pattern = Pattern.compile(Type);
if (!pattern.matcher(lexer.PeekNextToken().Token).matches()
&& !pattern.matcher(lexer.PeekNextToken().Type.toString()).matches()) {
error("Error: in class: " + className + ", keyword is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
returnType = lexer.PeekNextToken().Token;
lexer.GetNextToken();
}
if (!lexer.PeekNextToken().Type.toString().equals("ID")) {
error("Error: in class: " + className + ", identifier is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
functionName = lexer.PeekNextToken().Token;
lexer.GetNextToken();
}
//Check the grammar of the argument list
if (!lexer.PeekNextToken().Token.equals("(")) {
error("Error: in class: " + className + ", \"(\" is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
lexer.GetNextToken();
while (!lexer.PeekNextToken().Token.equals(")")) {
String assignArgumentType = "";
String beAssignedArgumentType = "";
if (!pattern.matcher(lexer.PeekNextToken().Token).matches()
&& !pattern.matcher(lexer.PeekNextToken().Type.toString()).matches()) {
error("Error: in class: " + className + ", keyword is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
//Store all the data types can be accepted for type conversion
assignArgumentType = lexer.PeekNextToken().Token;
if (assignArgumentType.equals("Array")) {
beAssignedArgumentType = "(int|Array)";
} else if (assignArgumentType.equals("String")) {
beAssignedArgumentType = "(String|null)";
} else if (assignArgumentType.equals("char")) {
beAssignedArgumentType = "(int|char)";
} else if (assignArgumentType.equals("boolean")) {
beAssignedArgumentType = "(int|boolean)";
} else if (assignArgumentType.equals("int")) {
beAssignedArgumentType = assignArgumentType;
} else {
beAssignedArgumentType = "(" + assignArgumentType + "|null|Array)";
}
lexer.GetNextToken();
}
if (!lexer.PeekNextToken().Type.toString().equals("ID")) {
error("Error: in class: " + className + ", identifier is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
if (symbolTables[3].findIdentifierSymbol(lexer.PeekNextToken().Token)) {
error("Error: in class: " + className + ", argument redeclaration, line:"
+ lexer.PeekNextToken().LineNumber);
} else {
symbolTables[3].addIdentifierSymbolTable(lexer.PeekNextToken().Token,
Symbol.SymbolType.argument, assignArgumentType, beAssignedArgumentType, "argument");
}
lexer.GetNextToken();
}
if (!lexer.PeekNextToken().Token.equals(",")) {
break;
} else {
lexer.GetNextToken();
}
}
if (!lexer.PeekNextToken().Token.equals(")")) {
error("Error: in class: " + className + ", \")\" is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
lexer.GetNextToken();
}
}
oldToken = lexer.PeekNextToken().Token;
symbolTables[4].findFunctionSymbol(className + "." + functionName);
//Insert the VM codes of subroutine into the VM file
vmCodeInput("function " + className + "." + functionName
+ " " + symbolTables[4].numOfVar + "\n");
if (constructorOrNot) {
ArrayList<String> fieldVarArray = (ArrayList<String>) classFieldVar.get(className);
vmCodeInput("push constant " + fieldVarArray.size() + "\n");
vmCodeInput("call Memory.alloc 1\n");
vmCodeInput("pop pointer 0\n");
constructorOrNot = false;
} else if (methodOrNot) {
vmCodeInput("push argument 0\n");
vmCodeInput("pop pointer 0\n");
methodOrNot = false;
}
//Reset the values of temporary variables in the symbol tables
symbolTableVarClear();
}
//This method is used to find all static belonging to current classes
private void classStaticDeclarCheck(String name) {
try {
Pattern pattern = Pattern.compile(Type);
//Declare the new lexical analyser
Lexer temLexer = new Lexer(name + ".jack");
temLexer.initLocalFile();
/*Construct a loop to supervise the value of index for terminating the loop
when end of source codes have been reached.*/
while (temLexer.getReadIndex() < temLexer.getTextContent().length() - 2) {
if (temLexer.PeekNextToken().Token.equals("static")) {
temLexer.GetNextToken();
String assignArgumentType = "";
String beAssignedArgumentType = "";
if (!pattern.matcher(temLexer.PeekNextToken().Token).matches()
&& !pattern.matcher(temLexer.PeekNextToken().Type.toString()).matches()) {
error("Error: in class: " + name + ", keyword is expected, line: " + temLexer.PeekNextToken().LineNumber);
} else {
//Store all data types can be accepted for type conversion
assignArgumentType = temLexer.PeekNextToken().Token;
if (assignArgumentType.equals("Array")) {
beAssignedArgumentType = "(int|Array|null|class|all)";
} else if (assignArgumentType.equals("String")) {
beAssignedArgumentType = "(String|null|all)";
} else if (assignArgumentType.equals("char")) {
beAssignedArgumentType = "(int|char|all)";
} else if (assignArgumentType.equals("boolean")) {
beAssignedArgumentType = "(int|boolean|all)";
} else if (assignArgumentType.equals("int")) {
beAssignedArgumentType = "(int|all)";
} else {
beAssignedArgumentType = "(" + assignArgumentType + "|null|Array)";
}
temLexer.GetNextToken();
}
//Store the information of static variables into the symbol table
while (true) {
if (!temLexer.PeekNextToken().Type.toString().equals("ID")) {
error("Error: in class: " + name + ", identifier is expected, line: " + temLexer.PeekNextToken().LineNumber);
} else {
if (symbolTables[0].findIdentifierSymbol(name + "." + temLexer.PeekNextToken().Token)
&& symbolTables[1].findIdentifierSymbol(temLexer.PeekNextToken().Token)) {
error("Error: in class: " + className + ", Variable redeclaration, line: " + temLexer.PeekNextToken().LineNumber);
} else {
symbolTables[0].addIdentifierSymbolTable(name + "." + temLexer.PeekNextToken().Token, Symbol.SymbolType.Static, assignArgumentType, beAssignedArgumentType, "static");
if (assignArgumentType.equals("Array")) {
classArrayNumOfEle.put(temLexer.PeekNextToken().Token, null);
}
}
temLexer.GetNextToken();
}
if (!temLexer.PeekNextToken().Token.equals(",")) {
break;
} else {
temLexer.GetNextToken();
}
}
if (!temLexer.PeekNextToken().Token.equals(";")) {
error("Error: in class: " + name + ", \";\" is expected, line: " + temLexer.PeekNextToken().LineNumber);
}
}
temLexer.GetNextToken();
}
} catch (Exception e) {
e.printStackTrace();
}
//Clear the values of temporary variables
symbolTableVarClear();
}
/*This method is used to check the grammar of the fields in current source
codes and store the information of them into the corresponding symbol table
*/
private void classVarDeclarCheck() {
Pattern pattern = Pattern.compile(Type);
String assignArgumentType = "";
String beAssignedArgumentType = "";
if (!pattern.matcher(lexer.PeekNextToken().Token).matches()
&& !pattern.matcher(lexer.PeekNextToken().Type.toString()).matches()) {
error("Error: in class: " + className + ", keyword is expected, line: " + lexer.PeekNextToken().LineNumber);
} else {
//Store all data types can be accepted for type conversion
assignArgumentType = lexer.PeekNextToken().Token;
if (assignArgumentType.equals("Array")) {
beAssignedArgumentType = "(int|Array|all)";
} else if (assignArgumentType.equals("String")) {
beAssignedArgumentType = "(String|null|all)";
} else if (assignArgumentType.equals("char")) {
beAssignedArgumentType = "(int|char|all)";
} else if (assignArgumentType.equals("boolean")) {
beAssignedArgumentType = "(int|boolean|all)";
} else if (assignArgumentType.equals("int")) {
beAssignedArgumentType = "(int|all)";
} else {
beAssignedArgumentType = "(" + assignArgumentType + "|null|Array)";
}
lexer.GetNextToken();
}
//Store the information of field variables into the symbol table
while (true) {
if (!lexer.PeekNextToken().Type.toString().equals("ID")) {
error("Error: in class: " + className + ", identifier is expected, line: " + lexer.PeekNextToken().LineNumber);
} else {
if (symbolTables[1].findIdentifierSymbol(lexer.PeekNextToken().Token)
&& symbolTables[0].findIdentifierSymbol(className + "." + lexer.PeekNextToken().Token)) {
error("Error: in class: " + className + ", variable redeclaration, line: " + lexer.PeekNextToken().LineNumber);
} else {
symbolTables[1].addIdentifierSymbolTable(lexer.PeekNextToken().Token, Symbol.SymbolType.field, assignArgumentType, beAssignedArgumentType, "this");
if (assignArgumentType.equals("Array")) {
classArrayNumOfEle.put(lexer.PeekNextToken().Token, null);
}
}
lexer.GetNextToken();
}
if (!lexer.PeekNextToken().Token.equals(",")) {
break;
} else {
lexer.GetNextToken();
}
}
if (!lexer.PeekNextToken().Token.equals(";")) {
error("Error: in class: " + className + ", \";\" is expected, line: " + lexer.PeekNextToken().LineNumber);
} else {
lexer.GetNextToken();
}
//Clear the values of temporary variables in the symbol table
symbolTableVarClear();
}
/*This method is used to check the grammar of the local variables in the subroutine
and insert the information of these variables into the symbol table
*/
private void functionVarDeclarCheck() {
Pattern pattern = Pattern.compile(Type);
String assignArgumentType = "";
String beAssignedArgumentType = "";
if (!pattern.matcher(lexer.PeekNextToken().Token).matches()) {
error("Error: in class: " + className + ", keyword is expected, line: " + lexer.PeekNextToken().LineNumber);
} else {
//Store all data types can be accepted for type conversion
assignArgumentType = lexer.PeekNextToken().Token;
if (assignArgumentType.equals("Array")) {
beAssignedArgumentType = "(int|Array|null|all)";
} else if (assignArgumentType.equals("String")) {
beAssignedArgumentType = "(String|null|all)";
} else if (assignArgumentType.equals("char")) {
beAssignedArgumentType = "(int|char|all)";
} else if (assignArgumentType.equals("boolean")) {
beAssignedArgumentType = "(int|boolean|all)";
} else if (assignArgumentType.equals("int")) {
beAssignedArgumentType = "(int|all)";
} else {
beAssignedArgumentType = "(" + assignArgumentType + "|null|Array)";
}
lexer.GetNextToken();
}
//Store the information of local variables into the symbol table
while (true) {
if (!lexer.PeekNextToken().Type.toString().equals("ID")) {
error("Error: in class: " + className + ", identifier is expected, line: " + lexer.PeekNextToken().LineNumber);
} else {
if (symbolTables[3].findIdentifierSymbol(lexer.PeekNextToken().Token)
|| symbolTables[2].findIdentifierSymbol(lexer.PeekNextToken().Token)) {
error("Error: in class: " + className + ", variable redeclaration, line: " + lexer.PeekNextToken().LineNumber);
} else {
symbolTables[2].addIdentifierSymbolTable(lexer.PeekNextToken().Token, Symbol.SymbolType.var, assignArgumentType, beAssignedArgumentType, "local");
if (assignArgumentType.equals("Array")) {
functionArrayNumOfEle.put(lexer.PeekNextToken().Token, null);
}
}
lexer.GetNextToken();
}
if (!lexer.PeekNextToken().Token.equals(",")) {
break;
} else {
lexer.GetNextToken();
}
}
if (!lexer.PeekNextToken().Token.equals(";")) {
error("Error: in class: " + className + ", \";\" is expected, line: " + lexer.PeekNextToken().LineNumber);
} else {
oldToken = lexer.PeekNextToken().Token;
lexer.GetNextToken();
}
//Clear the values of the temporary variables in the symbol table
symbolTableVarClear();
}
/*This method is used to check the grammar of the let statement, store
variable has been initialized and make the data type checking for the
two sides around the equal sign.
*/
private void letStatementCheck() throws Exception {
String lastToken = "";
String varName = "";
String memorySegment = "";
String dataType = "";
int offset = 0;
boolean arrayOrNot = false;
Pattern pattern = Pattern.compile(otherClassType);
if (!lexer.PeekNextToken().Type.toString().equals("ID")) {
error("Error: in class: " + className
+ ", identifier is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
//Check if the variable is defined before using
if (!(symbolTables[2].findIdentifierSymbol(lexer.PeekNextToken().Token)
|| symbolTables[3].findIdentifierSymbol(lexer.PeekNextToken().Token)
|| symbolTables[1].findIdentifierSymbol(lexer.PeekNextToken().Token)
|| symbolTables[0].findIdentifierSymbol(className + "." + lexer.PeekNextToken().Token))) {
error("Error: in class: " + className + ", variable \""
+ lexer.PeekNextToken().Token + "\" is not declared before, line: "
+ lexer.PeekNextToken().LineNumber);
}
for (SymbolTable symbolTable : symbolTables) {
if (!symbolTable.dataType.equals("")
&& !symbolTable.memorySegment.equals("")) {
varName = symbolTable.varName;
offset = symbolTable.offset;
dataType = symbolTable.dataType;
memorySegment = symbolTable.memorySegment;
break;
}
symbolTable.memorySegment = "";
symbolTable.dataType = "";
symbolTable.offset = 0;
}
lastToken = lexer.PeekNextToken().Token;
lexer.GetNextToken();
}
//Check if the variable on the left-hand side is an array
if (lexer.PeekNextToken().Token.equals("[")) {
lexer.GetNextToken();
expression();
vmCodeInput("push " + memorySegment + " " + offset + "\n");
if (!(expressionReturnType.equals("int")
|| expressionReturnType.equals("all"))) {
error("Error: in class: " + className
+ ", \"int value\" is expected, line: "
+ lexer.PeekNextToken().LineNumber);
}
if (!lexer.PeekNextToken().Token.equals("]")) {
error("Error: in class: " + className
+ ", \"]\" is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
if (!dataType.equals("Array")) {
error("Error: in class: " + className
+ ", variable \"" + lastToken + "\" is not an array variable, line: "
+ lexer.PeekNextToken().LineNumber);
}
vmCodeInput("add\n");
arrayOrNot = true;
lexer.GetNextToken();
}
}
if (!lexer.PeekNextToken().Token.equals("=")) {
error("Error: in class: " + className
+ ", \"=\" is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
lexer.GetNextToken();
String arrayVarName = lexer.PeekNextToken().Token;
expression();
//Check if it is the initialization for array and record the number of elements defined,
if (dataType.equals("Array") && arrayInitOrNot) {
if (functionArrayNumOfEle.containsKey(varName)) {
functionArrayNumOfEle.replace(varName, eleNumberCounter);
} else {
classArrayNumOfEle.replace(varName, eleNumberCounter);
}
arrayInitOrNot = false;
}
//Insert the VM codes if the expression on the right-hand side is an array
if (arrayOrNot) {
vmCodeInput("pop temp 0\n");
vmCodeInput("pop pointer 1\n");
vmCodeInput("push temp 0\n");
vmCodeInput("pop that 0\n");
} else {
//Check if the data type of two sides match with each other
vmCodeInput("pop " + memorySegment + " " + offset + "\n");
if (Pattern.compile(symbolTables[2].
getIdentifierBeAssignedDataType(lastToken)).
matcher(expressionReturnType).matches()
|| Pattern.compile(symbolTables[3].
getIdentifierBeAssignedDataType(lastToken)).
matcher(expressionReturnType).matches()
|| Pattern.compile(symbolTables[1].
getIdentifierBeAssignedDataType(lastToken)).
matcher(expressionReturnType).matches()
|| Pattern.compile(symbolTables[0].
getIdentifierBeAssignedDataType(className + "." + lastToken)).
matcher(expressionReturnType).matches()) {
if (((pattern.matcher(symbolTables[2].
getIdentifierAssignDataType(lastToken)).matches()
|| pattern.matcher(symbolTables[3].
getIdentifierAssignDataType(lastToken)).matches()
|| pattern.matcher(symbolTables[1].
getIdentifierAssignDataType(lastToken)).matches()
|| pattern.matcher(symbolTables[0].
getIdentifierAssignDataType(className + "." + lastToken)).matches())
&& expressionReturnType.equals("Array"))) {
if (!(functionArrayNumOfEle.containsKey(arrayVarName)
&& (((ArrayList<String>) classFieldVar.get(dataType)).size()
== (int) functionArrayNumOfEle.get(arrayVarName)))) {
if (!(classArrayNumOfEle.containsKey(arrayVarName)
&& (((ArrayList<String>) classFieldVar.get(dataType)).size()
== (int) classArrayNumOfEle.get(arrayVarName)))) {
error("Error: in class: " + className
+ ", the numer of fields not matches with the number of elements in the array, line: "
+ lexer.PeekNextToken().Token);
}
}
}
} else {
error("Error: in class: " + className + ", data type of return acvalue is wrong, line "
+ lexer.PeekNextToken().LineNumber);
}
}
if (!lexer.PeekNextToken().Token.equals(";")) {
error("Error: in class: " + className + ", \";\" is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
//Mark if the variable on the left-hand side is initialized
if (memorySegment.equals("local")) {
symbolTables[2].setInitOrNot(lastToken);
} else if (memorySegment.equals("argument")) {
symbolTables[3].setInitOrNot(lastToken);
} else if (memorySegment.equals("this")) {
symbolTables[1].setInitOrNot(lastToken);
} else {
symbolTables[0].setInitOrNot(className + "." + lastToken);
}
oldToken = lexer.PeekNextToken().Token;
lexer.GetNextToken();
}
}
symbolTableVarClear();
}
//This method is used to check the grammar of the if statement and insert VM codes for if statement
private void ifStatementCheck() throws Exception {
boolean ifReturnOrNot = false;
boolean elseReturnOrNot = false;
if (!lexer.PeekNextToken().Token.equals("(")) {
error("Error: in class: " + className + ", \"(\" is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
lexer.GetNextToken();
}
expression();
if (!lexer.PeekNextToken().Token.equals(")")) {
error("Error: in class: " + className + ", \")\" is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
lexer.GetNextToken();
}
int currentIfCounter = ifCounter;
vmCodeInput("if-goto IF_TRUE" + currentIfCounter + "\n");
vmCodeInput("goto IF_FALSE" + currentIfCounter + "\n");
if (!lexer.PeekNextToken().Token.equals("{")) {
error("Error: in class: " + className + ", \"{\" is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
vmCodeInput("label IF_TRUE" + currentIfCounter + "\n");
lexer.GetNextToken();
ifCounter++;
}
//Check the grammar of the source codes in the braces behind the if keyword
Token newToken = lexer.PeekNextToken();
try {
while (lexer.getReadIndex() < textContent.length() - 2) {
if (newToken.Token.equals("let")) {
lexer.GetNextToken();
letStatementCheck();
} else if (newToken.Token.equals("if")) {
lexer.GetNextToken();
ifStatementCheck();
} else if (newToken.Token.equals("while")) {
lexer.GetNextToken();
whileStatementCheck();
} else if (newToken.Token.equals("do")) {
lexer.GetNextToken();
doStatementCheck();
} else if (newToken.Token.equals("return")) {
ifReturnOrNot = true;
lexer.GetNextToken();
returnStatementCheck();
}
newToken = lexer.PeekNextToken();
if (newToken.Token.equals("}")) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (!lexer.PeekNextToken().Token.equals("}")) {
error("Error: in class: " + className + ", \"}\" is expected, line: "
+ lexer.PeekNextToken().LineNumber);
} else {
oldToken = lexer.PeekNextToken().Token;
lexer.GetNextToken();
}
//Check the grammar of the source codes in the braces behind the else keyword
if (lexer.PeekNextToken().Token.equals("else")) {
vmCodeInput("goto IF_END" + currentIfCounter + "\n");