Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParser.java
More file actions
572 lines (539 loc) · 15.2 KB
/
Copy pathParser.java
File metadata and controls
572 lines (539 loc) · 15.2 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
package parser;
import java.util.*;
import lexer.*;
import ast.*;
/**
* The Parser class performs recursive-descent parsing; as a
* by-product it will build the Abstract Syntax Tree representation
* for the source program<br>
* Following is the Grammar we are using:<br>
* <pre>
* PROGRAM -> ‘program’ BLOCK ==> program
*
* BLOCK -> ‘{‘ D* S* ‘}’ ==> block
*
* D -> TYPE NAME ==> decl
* -> TYPE NAME FUNHEAD BLOCK ==> functionDecl
*
* TYPE -> ‘int’
* -> ‘boolean’
* -> ‘float’
* -> ‘char’
*
* FUNHEAD -> '(' (D list ',')? ')' ==> formals<br>
*
* S -> ‘if’ E ‘then’ BLOCK ‘else’ BLOCK ==> if
* -> ‘if’ E ‘then’ BLOCK ==> if
* -> ‘while’ E BLOCK ==> while
* -> ‘return’ E ==> return
* -> BLOCK
* -> NAME ‘=’ E ==> assign
* -> ‘do’ BLOCK ‘while’ E ==> repeat
*
* E -> SE
* -> SE ‘==’ SE ==> =
* -> SE ‘!=’ SE ==> !=
* -> SE ‘<’ SE ==> <
* -> SE ‘>’ SE ==> >
* -> SE ‘<=’ SE ==> <=
* -> SE ‘>=’ SE ==> >=
*
* SE -> T
* -> SE ‘+’ T ==> +
* -> SE ‘-‘ T ==> -
* -> SE ‘|’ T ==> or
*
* SE -> T
* -> T ‘+’ SE ==> +
* -> T ‘-‘ SE ==> -
* -> T ‘|’ SE ==> or
*
* T -> F
* -> T ‘*’ F ==> *
* -> T ‘/’ F ==> /
* -> T ‘&’ F ==> and
*
* F -> ‘(‘ E ‘)’
* -> NAME
* -> <int>
* -> NAME '(' (E list ',')? ')' ==> call
* -> <float>
* -> <char>
* -> <ScientificN>
* -> ‘!’ E
* -> ‘-’ E
*
* NAME -> <id>
* </pre>
*/
public class Parser {
private Token currentToken;
private Lexer lex;
private EnumSet<Tokens> relationalOps =
EnumSet.of(Tokens.Equal,Tokens.NotEqual,Tokens.Less,Tokens.LessEqual,Tokens.Greater,Tokens.GreaterEqual);
private EnumSet<Tokens> addingOps =
EnumSet.of(Tokens.Plus,Tokens.Minus,Tokens.Or);
private EnumSet<Tokens> multiplyingOps =
EnumSet.of(Tokens.Multiply,Tokens.Divide,Tokens.And);
/**
* Construct a new Parser;
* @param sourceProgram - source file name
* @exception Exception - thrown for any problems at startup (e.g. I/O)
*/
public Parser(String sourceProgram) throws Exception {
try {
lex = new Lexer(sourceProgram);
scan();
}
catch (Exception e) {
System.out.println("********exception*******"+e.toString());
throw e;
};
}
public Lexer getLex() { return lex; }
/**
* Execute the parse command
* @return the AST for the source program
* @exception Exception - pass on any type of exception raised
*/
public AST execute() throws Exception {
try {
return rProgram();
}catch (SyntaxError e) {
e.print();
throw e;
}
}
/** <pre>
* Program -> 'program' block ==> program
* </pre>
* @return the program tree
* @exception SyntaxError - thrown for any syntax error
*/
public AST rProgram() throws SyntaxError {
// note that rProgram actually returns a ProgramTree; we use the
// principle of substitutability to indicate it returns an AST
AST t = new ProgramTree();
expect(Tokens.Program);
t.addKid(rBlock());
return t;
}
/** <pre>
* block -> '{' d* s* '}' ==> block
* </pre>
* @return block tree
* @exception SyntaxError - thrown for any syntax error
* e.g. an expected left brace isn't found
*/
public AST rBlock() throws SyntaxError {
expect(Tokens.LeftBrace);
AST t = new BlockTree();
while (true) { // get decls
try {
t.addKid(rDecl());
} catch (SyntaxError e) { break; }
}
while (true) { // get statements
try {
t.addKid(rStatement());
} catch (SyntaxError e) { break; }
}
expect(Tokens.RightBrace);
return t;
}
/** <pre>
* d -> type name ==> decl
* -> type name funcHead block ==> functionDecl
* </pre>
* @return either the decl tree or the functionDecl tree
* @exception SyntaxError - thrown for any syntax error
*/
public AST rDecl() throws SyntaxError {
AST t,t1;
t = rType();
t1 = rName();
if (isNextTok(Tokens.LeftParen)) { // function
t = (new FunctionDeclTree()).addKid(t).addKid(t1);
t.addKid(rFunHead());
t.addKid(rBlock());
return t;
}
t = (new DeclTree()).addKid(t).addKid(t1);
return t;
}
/** <pre>
* type -> 'int'
* type -> 'boolean'
* type -> 'float'
* type -> 'char'
* </pre>
* @return the intType or boolType tree or floatType tree or charType tree
* @exception SyntaxError - thrown for any syntax error
*/
public AST rType() throws SyntaxError {
AST t;
if (isNextTok(Tokens.Int)) {
t = new IntTypeTree();
scan();
} else if(isNextTok(Tokens.BOOLean)){
t = new BoolTypeTree();
scan();
}else if(isNextTok(Tokens.FLOAT)){
t = new FloatTypeTree();
scan();
}else{
expect(Tokens.CHAR);
t = new CharTypeTree();
}
return t;
}
/** <pre>
* funHead -> '(' (decl list ',')? ')' ==> formals
* note a funhead is a list of zero or more decl's
* separated by commas, all in parens
* </pre>
* @return the formals tree describing this list of formals
* @exception SyntaxError - thrown for any syntax error
*/
public AST rFunHead() throws SyntaxError {
AST t = new FormalsTree();
expect(Tokens.LeftParen);
if (!isNextTok(Tokens.RightParen)) {
do {
t.addKid(rDecl());
if (isNextTok(Tokens.Comma)) {
scan();
} else {
break;
}
} while (true);
}
expect(Tokens.RightParen);
return t;
}
/** <pre>
* S -> 'if' e 'then' block 'else' block ==> if
* -> 'if' E 'then' block ==> if
* -> 'while' e block ==> while
* -> 'return' e ==> return
* -> block
* -> 'do' block 'while' E ==> repeat
* -> name '=' e ==> assign
* </pre>
* @return the tree corresponding to the statement found
* @exception SyntaxError - thrown for any syntax error
*/
public AST rStatement() throws SyntaxError {
AST t;
// 'if' e 'then' block 'else' block ==> if
// 'if' e 'then' block ==> if
if (isNextTok(Tokens.If)) {
scan();
t = new IfTree();
t.addKid(rExpr());
expect(Tokens.Then);
t.addKid(rBlock());
if(isNextTok(Tokens.Else)){
scan();
t.addKid(rBlock());
return t;
}else
return t;
}
// 'while' e block ==> while
if (isNextTok(Tokens.While)) {
scan();
t = new WhileTree();
t.addKid(rExpr());
t.addKid(rBlock());
return t;
}
// 'return' e ==> return
if (isNextTok(Tokens.Return)) {
scan();
t = new ReturnTree();
t.addKid(rExpr());
return t;
}
// block
if (isNextTok(Tokens.LeftBrace)) {
return rBlock();
}
// 'do' block 'while' E ==> repeat
if (isNextTok(Tokens.Do)) {
scan();
t = new DoTree();
t.addKid(rBlock());
expect(Tokens.While);
t.addKid(rExpr());
return t;
}
// name '=' e ==> assign
t = rName();
t = (new AssignTree()).addKid(t);
expect(Tokens.Assign);
t.addKid(rExpr());
return t;
}
/** <pre>
* e -> se
* -> se '==' se ==> =
* -> se '!=' se ==> !=
* -> se '<' se ==> <
* -> se '>' se ==> >
* -> se '<=' se ==> <=
* -> se '>=' se ==> >=
* </pre>
* @return the tree corresponding to the expression
* @exception SyntaxError - thrown for any syntax error
*/
public AST rExpr() throws SyntaxError {
AST t, kid = rSimpleExpr();
t = getRelationTree();
if (t == null) {
return kid;
}
t.addKid(kid);
t.addKid(rSimpleExpr());
return t;
}
/** <pre>
* se -> t
* -> se '+' t ==> +
* -> se '-' t ==> -
* -> se '|' t ==> or
* This rule indicates we should pick up as many <i>t</i>'s as
* possible; the <i>t</i>'s will be left associative
* </pre>
* @return the tree corresponding to the adding expression
* @exception SyntaxError - thrown for any syntax error
*/
public AST rSimpleExpr() throws SyntaxError {
AST t, kid = rTerm();
while ( (t = getAddOperTree()) != null) {
t.addKid(kid);
t.addKid(rTerm());
kid = t;
}
return kid;
}
// Make a little change on the grammer to understand the process of building the tree
/*
* se -> t
* -> t '+' se ==> +
* -> t '-' se ==> -
* -> t '|' se ==> or
public AST rSimpleExpr() throws SyntaxError {
AST t, kid = rTerm();
while ( (t = getAddOperTree()) != null) {
t.addKid(kid);
t.addKid(rSimpleExpr()); //use the recursive function call of rSimpleExpr()
kid = t;
}
return kid;
}
// Or in this way
public AST rSimpleExpr() throws SyntaxError {
AST t,left,right,kid,seT;
seT=left=rTerm();
if((t=getAddOperTree())!= null){
seT=t;
t.addKid(left);
right=rTerm();
while((kid=getAddOperTree())!=null){
kid.addKid(right);
t.addKid(kid);
t=kid;
right=rTerm();
}
t.addKid(right);
}
return seT;
}
*/
/** <pre>
* t -> f
* -> t '*' f ==> *
* -> t '/' f ==> /
* -> t '&' f ==> and
* This rule indicates we should pick up as many <i>f</i>'s as
* possible; the <i>f</i>'s will be left associative
* </pre>
* @return the tree corresponding to the multiplying expression
* @exception SyntaxError - thrown for any syntax error
*/
public AST rTerm() throws SyntaxError {
AST t, kid = rFactor();
while ( (t = getMultOperTree()) != null) {
t.addKid(kid);
t.addKid(rFactor());
kid = t;
}
return kid;
}
/** <pre>
* f -> '(' e ')'
* -> name
* -> <int>
* -> name '(' (e list ',')? ')' ==> call
* -> <float>
* -> <char>
* -> <ScientificN>
* -> ‘!’ E
* -> ‘-’ E
* </pre>
* @return the tree corresponding to the factor expression
* @exception SyntaxError - thrown for any syntax error
*/
public AST rFactor() throws SyntaxError {
AST t;
if (isNextTok(Tokens.LeftParen)) { // -> (e)
scan();
t = rExpr();
expect(Tokens.RightParen);
return t;
}
if (isNextTok(Tokens.INTeger)) { // -> <int>
t = new IntTree(currentToken);
scan();
return t;
}
if (isNextTok(Tokens.Float)) { // -> <float>
t = new FloatTree(currentToken);
scan();
return t;
}
if (isNextTok(Tokens.Char)) { // -> <char>
t = new CharTree(currentToken);
scan();
return t;
}
if (isNextTok(Tokens.ScientificN)) { // -> <ScientificN>
t = new ScientificNTree(currentToken);
scan();
return t;
}
if (isNextTok(Tokens.Negation)) { // -> <Negation>
t = new NegationTree(currentToken);
scan();
t.addKid(rExpr());
return t;
}
if (isNextTok(Tokens.Minus)) { // -> <UnaryOp>
t = new UnaryOpTree(currentToken);
scan();
t.addKid(rExpr());
return t;
}
t = rName();
if (!isNextTok(Tokens.LeftParen)) { // -> name
return t;
}
scan(); // -> name '(' (e list ',')? ) ==> call
t = (new CallTree()).addKid(t);
if (!isNextTok(Tokens.RightParen)) {
do {
t.addKid(rExpr());
if (isNextTok(Tokens.Comma)) {
scan();
} else {
break;
}
} while (true);
}
expect(Tokens.RightParen);
return t;
}
/** <pre>
* name -> <id>
* </pre>
* @return the id tree
* @exception SyntaxError - thrown for any syntax error
*/
public AST rName() throws SyntaxError {
AST t;
if (isNextTok(Tokens.Identifier)) {
t = new IdTree(currentToken);
scan();
return t;
}
throw new SyntaxError(currentToken,Tokens.Identifier);
}
AST getRelationTree() { // build tree with current token's relation
Tokens kind = currentToken.getKind();
if (relationalOps.contains(kind)) {
AST t = new RelOpTree(currentToken);
scan();
return t;
} else {
return null;
}
}
private AST getAddOperTree() {
Tokens kind = currentToken.getKind();
if (addingOps.contains(kind)) {
AST t = new AddOpTree(currentToken);
scan();
return t;
} else {
return null;
}
}
private AST getMultOperTree() {
Tokens kind = currentToken.getKind();
if (multiplyingOps.contains(kind)) {
AST t = new MultOpTree(currentToken);
scan();
return t;
} else {
return null;
}
}
private boolean isNextTok(Tokens kind) {
if ((currentToken == null) || (currentToken.getKind() != kind)) {
return false;
}
return true;
}
private void expect(Tokens kind) throws SyntaxError {
if (isNextTok(kind)) {
scan();
return;
}
throw new SyntaxError(currentToken,kind);
}
private void scan() {
currentToken = lex.nextToken();
if (currentToken != null) {
currentToken.print(); // debug printout
}
return;
}
}
class SyntaxError extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
private Token tokenFound;
private Tokens kindExpected;
/**
* record the syntax error just encountered
* @param tokenFound is the token just found by the parser
* @param kindExpected is the token we expected to find based on
* the current context
*/
public SyntaxError(Token tokenFound, Tokens kindExpected) {
this.tokenFound = tokenFound;
this.kindExpected = kindExpected;
}
void print() {
System.out.println("Expected: " +
kindExpected+" Found: " +
tokenFound);
return;
}
}
You can’t perform that action at this time.
