-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.java
More file actions
787 lines (670 loc) · 27.1 KB
/
Parser.java
File metadata and controls
787 lines (670 loc) · 27.1 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
package plc.project;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* The parser takes the sequence of tokens emitted by the lexer and turns that
* into a structured representation of the program, called the Abstract Syntax
* Tree (AST).
*
* The parser has a similar architecture to the lexer, just with {@link Token}s
* instead of characters. As before, {@link #peek(Object...)} and {@link
* #match(Object...)} are helpers to make the implementation easier.
*
* This type of parser is called <em>recursive descent</em>. Each rule in our
* grammar will have it's own function, and reference to other rules correspond
* to calling that functions.
*/
public final class Parser {
private final TokenStream tokens;
public Parser(List<Token> tokens) {
this.tokens = new TokenStream(tokens);
}
/**
* Parses the {@code source} rule.
*/
public Ast.Source parseSource() throws ParseException {
List<Ast.Field> fields = new ArrayList<Ast.Field>();
List<Ast.Method> methods = new ArrayList<Ast.Method>();
// while there are still tokens...
while (tokens.has(0)) {
if (peek("LET")) {
Ast.Field field = parseField();
fields.add(field);
} else if (peek("DEF")) {
Ast.Method method = parseMethod();
methods.add(method);
}
}
return new Ast.Source(fields, methods);
}
/**
* Parses the {@code field} rule. This method should only be called if the
* next tokens start a field, aka {@code LET}.
*/
public Ast.Field parseField() throws ParseException {
match("LET");
if (match(Token.Type.IDENTIFIER)) {
String name = tokens.get(-1).getLiteral();
if (match(":")) {
if (match(Token.Type.IDENTIFIER)) {
String typeName = tokens.get(-1).getLiteral();
if (match("=")) {
Ast.Expr expr = parseExpression();
if (match(";")) {
return new Ast.Field(name, typeName, Optional.of(expr));
} else {
throw new ParseException("Error! No semicolon.", tokens.get(-1).getIndex());
}
} else {
if (match(";")) {
return new Ast.Field(name, typeName, Optional.empty());
} else {
throw new ParseException("Error! No semicolon.", tokens.get(-1).getIndex());
}
}
}
else {
throw new ParseException("Error! No identifier for type name.", tokens.get(-1).getIndex());
}
}
else {
throw new ParseException("Error! No colon.", tokens.get(-1).getIndex());
}
}
else {
throw new ParseException("Error! No identifier.", tokens.get(-1).getIndex());
}
}
/**
* Parses the {@code method} rule. This method should only be called if the
* next tokens start a method, aka {@code DEF}.
*/
public Ast.Method parseMethod() throws ParseException {
List<String> parameters = new ArrayList<String>();
List<String> parameterTypes = new ArrayList<String>();
List<Ast.Stmt> statements = new ArrayList<Ast.Stmt>();
match("DEF");
if (match(Token.Type.IDENTIFIER)) {
String name = tokens.get(-1).getLiteral();
if (match("(")) {
if (match(Token.Type.IDENTIFIER)) {
String param = tokens.get(-1).getLiteral();
if (match(":")) {
if (match(Token.Type.IDENTIFIER)) {
String paramType = tokens.get(-1).getLiteral();
parameters.add(param);
parameterTypes.add(paramType);
while (match(",") && !peek(")")) {
if (match(Token.Type.IDENTIFIER)) {
String extra_param = tokens.get(-1).getLiteral();
if (match(":")) {
if (match(Token.Type.IDENTIFIER)) {
String extra_paramType = tokens.get(-1).getLiteral();
parameters.add(extra_param);
parameterTypes.add(extra_paramType);
}
else {
throw new ParseException("Error! No type name identifier.", tokens.get(-1).getIndex());
}
}
else {
throw new ParseException("Error! No colon.", tokens.get(-1).getIndex());
}
}
else {
throw new ParseException("Error! Trailing comma.", tokens.get(-1).getIndex());
}
}
}
else {
throw new ParseException("Error! No type name identifier.", tokens.get(-1).getIndex());
}
}
else {
throw new ParseException("Error! No colon.", tokens.get(-1).getIndex());
}
}
if (match(")")) {
if (match(":")){
if (match(Token.Type.IDENTIFIER)) {
String returnType = tokens.get(-1).getLiteral();
if (match("DO")) {
while (!peek("END")) {
Ast.Stmt stmt = parseStatement();
statements.add(stmt);
}
match("END");
return new Ast.Method(name, parameters, parameterTypes, Optional.of(returnType), statements);
}
else {
throw new ParseException("Error! No \"DO\" token.", tokens.get(-1).getIndex());
}
}
else {
throw new ParseException("Error! No return type identifier.", tokens.get(-1).getIndex());
}
}
if (match("DO")) {
while (!peek("END")) {
Ast.Stmt stmt = parseStatement();
statements.add(stmt);
}
match("END");
return new Ast.Method(name, parameters, parameterTypes, Optional.empty(), statements);
}
else {
throw new ParseException("Error! No \"DO\" token.", tokens.get(-1).getIndex());
}
}
else {
throw new ParseException("Error! No closing parenthesis.", tokens.get(-1).getIndex());
}
}
else {
throw new ParseException("Error! No opening parenthesis.", tokens.get(-1).getIndex());
}
}
else {
throw new ParseException("Error! No identifier.", tokens.get(-1).getIndex());
}
}
/**
* Parses the {@code statement} rule and delegates to the necessary method.
* If the next tokens do not start a declaration, if, while, or return
* statement, then it is an expression/assignment statement.
*/
public Ast.Stmt parseStatement() throws ParseException {
if (peek("IF")) {
return parseIfStatement();
}
else if (peek("FOR")) {
return parseForStatement();
}
else if (peek("WHILE")) {
return parseWhileStatement();
}
else if (peek("LET")) {
return parseDeclarationStatement();
}
else if (peek("RETURN")) {
return parseReturnStatement();
}
else {
Ast.Expr expr = parseExpression();
if (match("=")) {
Ast.Expr expr1 = parseExpression();
if (match(";")) {
return new Ast.Stmt.Assignment(expr, expr1);
}
throw new ParseException("Error: No semicolon", tokens.get(-1).getIndex());
}
else if (match(";")) {
return new Ast.Stmt.Expression(expr);
}
throw new ParseException("Error: No semicolon", tokens.get(-1).getIndex());
}
}
/**
* Parses a declaration statement from the {@code statement} rule. This
* method should only be called if the next tokens start a declaration
* statement, aka {@code LET}.
*/
public Ast.Stmt.Declaration parseDeclarationStatement() throws ParseException {
match("LET");
if (match(Token.Type.IDENTIFIER)) {
String name = tokens.get(-1).getLiteral();
if (match(":")) {
if (match(Token.Type.IDENTIFIER)) {
String typeName = tokens.get(-1).getLiteral();
if (match("=")) {
Ast.Expr expr = parseExpression();
if (match(";")) {
return new Ast.Stmt.Declaration(name, Optional.of(typeName), Optional.of(expr));
}
else {
throw new ParseException("Error! No semicolon.", tokens.get(-1).getIndex());
}
}
else {
if (match(";")) {
return new Ast.Stmt.Declaration(name, Optional.of(typeName), Optional.empty());
}
else {
throw new ParseException("Error! No semicolon.", tokens.get(-1).getIndex());
}
}
}
else {
throw new ParseException("Error! No type name identifier.", tokens.get(-1).getIndex());
}
}
if (match("=")) {
Ast.Expr expr = parseExpression();
if (match(";")) {
return new Ast.Stmt.Declaration(name, Optional.of(expr));
}
else {
throw new ParseException("Error! No semicolon.", tokens.get(-1).getIndex());
}
}
else {
if (match(";")) {
return new Ast.Stmt.Declaration(name, Optional.empty());
}
else {
throw new ParseException("Error! No semicolon.", tokens.get(-1).getIndex());
}
}
}
else {
throw new ParseException("Error! No identifier.", tokens.get(-1).getIndex());
}
}
/**
* Parses an if statement from the {@code statement} rule. This method
* should only be called if the next tokens start an if statement, aka
* {@code IF}.
*/
public Ast.Stmt.If parseIfStatement() throws ParseException {
List<Ast.Stmt> thenStatements = new ArrayList<Ast.Stmt>();
List<Ast.Stmt> elseStatements = new ArrayList<Ast.Stmt>();
match("IF");
Ast.Expr condition = parseExpression();
if (match("DO")) {
while (!peek("ELSE") && !peek("END")) {
Ast.Stmt thenStatement = parseStatement();
thenStatements.add(thenStatement);
}
if (peek("ELSE")) {
match("ELSE");
while (!peek("END")) {
Ast.Stmt elseStatement = parseStatement();
elseStatements.add(elseStatement);
}
}
match("END");
return new Ast.Stmt.If(condition, thenStatements, elseStatements);
}
// Adding + 1 to the .getIndex() because the "DO" token should located after the last token in the sequence...
else {
throw new ParseException("Error! No \"DO\" token.", tokens.get(-1).getIndex() + 1);
}
}
/**
* Parses a for statement from the {@code statement} rule. This method
* should only be called if the next tokens start a for statement, aka
* {@code FOR}.
*/
public Ast.Stmt.For parseForStatement() throws ParseException {
List<Ast.Stmt> statements = new ArrayList<Ast.Stmt>();
match("FOR");
if (match(Token.Type.IDENTIFIER)) {
String name = tokens.get(-1).getLiteral();
if (match("IN")) {
Ast.Expr value = parseExpression();
if (match("DO")) {
while (!peek("END")) {
Ast.Stmt stmt = parseStatement();
statements.add(stmt);
}
match("END");
return new Ast.Stmt.For(name, value, statements);
}
else {
throw new ParseException("Error! No \"DO\" token.", tokens.get(-1).getIndex());
}
}
else {
throw new ParseException("Error! No \"IN\" token", tokens.get(-1).getIndex());
}
}
else {
throw new ParseException("Error! No identifier.", tokens.get(-1).getIndex());
}
}
/**
* Parses a while statement from the {@code statement} rule. This method
* should only be called if the next tokens start a while statement, aka
* {@code WHILE}.
*/
public Ast.Stmt.While parseWhileStatement() throws ParseException {
List<Ast.Stmt> statements = new ArrayList<Ast.Stmt>();
match("WHILE");
Ast.Expr condition = parseExpression();
if (match("DO")) {
while (!peek("END")) {
Ast.Stmt stmt = parseStatement();
statements.add(stmt);
}
match("END");
return new Ast.Stmt.While(condition, statements);
}
else {
throw new ParseException("Error! No \"DO\" token.", tokens.get(-1).getIndex());
}
}
/**
* Parses a return statement from the {@code statement} rule. This method
* should only be called if the next tokens start a return statement, aka
* {@code RETURN}.
*/
public Ast.Stmt.Return parseReturnStatement() throws ParseException {
match("RETURN");
Ast.Expr value = parseExpression();
if (match(";")) {
return new Ast.Stmt.Return(value);
}
else {
throw new ParseException("Error! No semicolon.", tokens.get(-1).getIndex());
}
}
/**
* Parses the {@code expression} rule.
*/
public Ast.Expr parseExpression() throws ParseException {
return parseLogicalExpression();
}
/**
* Parses the {@code logical-expression} rule.
*/
public Ast.Expr parseLogicalExpression() throws ParseException {
Ast.Expr expr = parseEqualityExpression();
while (peek("AND") || peek("OR")) {
if (match("AND")) {
Ast.Expr right = parseEqualityExpression();
expr = new Ast.Expr.Binary("AND", expr, right);
}
else {
match("OR");
Ast.Expr right = parseEqualityExpression();
expr = new Ast.Expr.Binary("OR", expr, right);
}
}
return expr;
}
/**
* Parses the {@code equality-expression} rule.
*/
public Ast.Expr parseEqualityExpression() throws ParseException {
Ast.Expr expr = parseAdditiveExpression();
//Not sure if this method of peeking first is better, but the other method of using one match statement
//may have some issues if the input is something like "<<=>"
while (peek("<") || peek("<=") || peek(">") || peek(">=") || peek("==") || peek("!=")) {
if (match("<")) {
Ast.Expr right = parseAdditiveExpression();
expr = new Ast.Expr.Binary("<", expr, right);
}
else if (match("<=")){
Ast.Expr right = parseAdditiveExpression();
expr = new Ast.Expr.Binary("<=", expr, right);
}
else if (match(">")){
Ast.Expr right = parseAdditiveExpression();
expr = new Ast.Expr.Binary(">", expr, right);
}
else if (match(">=")){
Ast.Expr right = parseAdditiveExpression();
expr = new Ast.Expr.Binary(">=", expr, right);
}
else if (match("==")){
Ast.Expr right = parseAdditiveExpression();
expr = new Ast.Expr.Binary("==", expr, right);
}
else {
match("!=");
Ast.Expr right = parseEqualityExpression();
expr = new Ast.Expr.Binary("!=", expr, right);
}
}
return expr;
}
/**
* Parses the {@code additive-expression} rule.
*/
public Ast.Expr parseAdditiveExpression() throws ParseException {
Ast.Expr expr = parseMultiplicativeExpression();
while (peek("+") || peek("-")) {
if (match("+")) {
Ast.Expr right = parseMultiplicativeExpression();
expr = new Ast.Expr.Binary("+", expr, right);
}
else {
match("-");
Ast.Expr right = parseMultiplicativeExpression();
expr = new Ast.Expr.Binary("-", expr, right);
}
}
return expr;
}
/**
* Parses the {@code multiplicative-expression} rule.
*/
public Ast.Expr parseMultiplicativeExpression() throws ParseException {
Ast.Expr expr = parseSecondaryExpression();
while (peek("*") || peek("/")) {
if (match("*")) {
Ast.Expr right = parseSecondaryExpression();
expr = new Ast.Expr.Binary("*", expr, right);
}
else {
match("/");
Ast.Expr right = parseSecondaryExpression();
expr = new Ast.Expr.Binary("/", expr, right);
}
}
return expr;
}
/**
* Parses the {@code secondary-expression} rule.
*/
//Changed a lot here, let me know if you have any questions and feel free to change anything
public Ast.Expr parseSecondaryExpression() throws ParseException {
Ast.Expr expr = parsePrimaryExpression();
List<Ast.Expr> parameters = new ArrayList<Ast.Expr>();
while (match(".")) {
if (match(Token.Type.IDENTIFIER)) {
String name = tokens.get(-1).getLiteral();
if (match("(")) {
if (match(")")) {
return new Ast.Expr.Function(Optional.of(expr), name, parameters);
}
Ast.Expr param = parseExpression();
parameters.add(param);
while (match(",")) {
Ast.Expr extra_param = parseExpression();
parameters.add(extra_param);
}
if (match(")")) {
return new Ast.Expr.Function(Optional.of(expr), name, parameters);
}
else {
throw new ParseException("Error: No closing right parenthesis. \")\"", tokens.get(-1).getIndex());
}
}
else {
return new Ast.Expr.Access(Optional.of(expr), name);
}
}
else {
throw new ParseException("Error: No identifier", tokens.get(-1).getIndex());
}
}
return expr;
}
/**
* Parses the {@code primary-expression} rule. This is the top-level rule
* for expressions and includes literal values, grouping, variables, and
* functions. It may be helpful to break these up into other methods but is
* not strictly necessary.
* @return
*/
public Ast.Expr parsePrimaryExpression() throws ParseException {
// Booleans
if (match("NIL")) { return new Ast.Expr.Literal(null); }
if (match("TRUE")) { return new Ast.Expr.Literal(true); }
if (match("FALSE")) { return new Ast.Expr.Literal(false); }
// Characters
if (match(Token.Type.CHARACTER)) {
// Remove 's & Replace Escape Characters.
String val = tokens.get(-1).getLiteral();
Character newVal;
// Strings can't be changed so we have to replace val each time
if (!val.contains("\\'")) {
val = val.replace("'", "");
} else if (val.equals("'\\''")){
newVal = '\'';
}
if (val.equals("\\b")) {
newVal = '\b';
} else if (val.equals("\\n")) {
newVal = '\n';
} else if (val.equals("\\r")) {
newVal = '\r';
} else if (val.equals("\\t")) {
newVal = '\t';
} else if (val.equals("\\\\")) {
newVal = '\\';
} else {
newVal = val.charAt(0);
}
return new Ast.Expr.Literal(newVal);
}
// Strings
if (match(Token.Type.STRING)) {
// Remove "s & Replace Escape Characters.
String val = tokens.get(-1).getLiteral();
val = val.replace("\"", "");
val = val.replace("\\b", "\b");
val = val.replace("\\n", "\n");
val = val.replace("\\r", "\r");
val = val.replace("\\t", "\t");
val = val.replace("\\'", "\'");
val = val.replace("\\\\", "\\");
return new Ast.Expr.Literal(val);
}
//Don't think the && statement is necessary
//Also remember to use getLiteral() instead of toString()
if (match(Token.Type.INTEGER) && !match(Token.Type.DECIMAL)) {
return new Ast.Expr.Literal(new BigInteger(tokens.get(-1).getLiteral()));
}
// Decimals
if (match(Token.Type.DECIMAL)) {
return new Ast.Expr.Literal(new BigDecimal(tokens.get(-1).getLiteral()));
}
// Group Expression
// Have tokens.get(-1).getIndex() + 1 since error should occur where the parenthesis should be...
if (match("(")) {
Ast.Expr expr = parseExpression();
if (match(")")) {
return new Ast.Expr.Group(expr);
}
else {
throw new ParseException("Error: No closing right parenthesis. \")\"", tokens.get(-1).getIndex() + 1);
}
}
//Redid this section
if (match(Token.Type.IDENTIFIER)) {
// String of Identifier Token.
String name = tokens.get(-1).getLiteral();
if (match("(")) {
// Flag variable to check for ")"
List<Ast.Expr> parameters = new ArrayList<Ast.Expr>();
//Empty function
if (match(")")) {
return new Ast.Expr.Function(Optional.empty(), name, parameters);
}
Ast.Expr param = parseExpression();
parameters.add(param);
while (match(",")) {
Ast.Expr extra_param = parseExpression();
parameters.add(extra_param);
}
if (match(")")) {
return new Ast.Expr.Function(Optional.empty(), name, parameters);
}
else {
throw new ParseException("Error: No closing right parenthesis. \")\"", tokens.get(-1).getIndex());
}
}
// Returning Variable without any ()
return new Ast.Expr.Access(Optional.empty(), name);
}
// Changed new Ast.Expr.Access(Optional.empty(), ""); to error for entering incorrect syntax
// Protecting against index out of bounds errors...
if (tokens.index == 0) {
throw new ParseException("Error: Unable to create expression.", tokens.get(0).getIndex());
}
// Throws error pointing towards highest index if nothing matches.
throw new ParseException("Error: Unable to create expression.", tokens.get(-1).getIndex());
}
/**
* As in the lexer, returns {@code true} if the current sequence of tokens
* matches the given patterns. Unlike the lexer, the pattern is not a regex;
* instead it is either a {@link Token.Type}, which matches if the token's
* type is the same, or a {@link String}, which matches if the token's
* literal is the same.
*
* In other words, {@code Token(IDENTIFIER, "literal")} is matched by both
* {@code peek(Token.Type.IDENTIFIER)} and {@code peek("literal")}.
*/
private boolean peek(Object... patterns) {
for (int i = 0; i < patterns.length; i++) {
if (!tokens.has(i)) {
return false;
} else if (patterns[i] instanceof Token.Type) {
if (patterns[i] != tokens.get(i).getType()) {
return false;
}
} else if (patterns[i] instanceof String) {
if (!patterns[i].equals(tokens.get(i).getLiteral())) {
return false;
}
} else {
throw new AssertionError("Invalid pattern object: " + patterns[i].getClass());
}
}
return true;
}
/**
* As in the lexer, returns {@code true} if {@link #peek(Object...)} is true
* and advances the token stream.
*/
private boolean match(Object... patterns) {
boolean peek = peek(patterns);
if (peek) {
for (int i = 0; i < patterns.length; i++) {
tokens.advance();
}
}
return peek;
}
private static final class TokenStream {
private final List<Token> tokens;
private int index = 0;
private TokenStream(List<Token> tokens) {
this.tokens = tokens;
}
/**
* Returns true if there is a token at index + offset.
*/
public boolean has(int offset) {
return index + offset < tokens.size();
}
/**
* Gets the token at index + offset.
*/
public Token get(int offset) {
return tokens.get(index + offset);
}
/**
* Advances to the next token, incrementing the index.
*/
public void advance() {
index++;
}
}
}