-
Notifications
You must be signed in to change notification settings - Fork 0
/
RdParser.cs
682 lines (534 loc) · 19.9 KB
/
RdParser.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
/*
File: RdParser.cs
Purpose: Recursive descent parser base class.
Author: Allan C. Milne.
Version: 2.2
Date: 9th March 2011.
namespace: AllanMilne.Ardkit
Uses: IScanner, IParser, IToken, ICompilerError, SyntaxError.
Exposes: RdParser, RecoveringRdParser.
Description:
A practical recursive-descent (Rd) parser encapsulation.
The RdParser abstract class provides the base functionality with a one-shot parser that terminates on a syntax error.
The RecoveringRdParser abstract class extends this to use Turner's error recovery method to allow parsing of the entire source stream.
A collection of CompilerError objects is used to contain all errors detected;
this is exposed as an Errors property with the error objects sorted in line/column order..
If the Errors property is called before the Parse() method then it will return null.
Use for a specific language/compiler:
A subclass must be defined that encapsulates the RD recogniser methods for the language rules.
1. Define a class inheriting from either RdParser or RecoveringRdParser.
2. The constructor must call the base constructor, passing the language-specific scanner object.
3. Define the recStarter() recogniser method for the starter symbol of the language.
4. Define the private RD recogniser methods for each rule in the language specification.
5. If semantic analysis is to be included then see the semantic analyser class for information.
*/
using System;
using System.IO;
using System.Collections.Generic;
namespace AllanMilne.PALCompiler
{
//=== the base parser abstract class.
public abstract class RdParser : IParser {
private static ComponentInfo info = new ComponentInfo (
"RdParser", "2.2", "March 2011", "Allan C. Milne", "Recursive-descent parsing abstract classes");
public static ComponentInfo Info
{ get { return info; } }
//--- attributes defining the state of the parse.
protected IScanner scanner; // the scannner.
protected List<ICompilerError> errs; // collection of error instances.
//--- The constructor method.
public RdParser (IScanner scan) {
this.scanner = scan;
this.errs = null;
} // end Parser constructor method
//=== The public API.
//--- always returns false for this one-shot compiler.
public bool IsRecovering
{ get { return false; } }
//--- returns the collection of error objects.
public List<ICompilerError> Errors
{ get { return errs; } }
//--- Initiate the parse and return whether or not the parse was successful.
public virtual bool Parse (TextReader source) {
errs = new List<ICompilerError> ();
scanner.Init (source, errs);
scanner.NextToken(); // seed the scanner with the first token.
try { // mechanism to allow parse to be aborted.
recStarter (); // initiate parse by calling the recogniser for the starter symbol.
mustBe (Token.EndOfFile); // check there is no other text.
} catch (CompilerErrorException) {}
errs.Sort (); // put the errors in line/column order.
return errs.Count == 0;
} // end Parse method.
//=== end of the public API.
//=== Recursive-descent primitives.
//--- Check if a supplied token is present.
protected bool have (String mightBe)
{ return scanner.CurrentToken.Is (mightBe); }
//--- ensure that the next token is the token required;
//--- if present then consume it, if not then abort parse.
protected virtual void mustBe (String shouldBe) {
if (have (shouldBe)) {
scanner.NextToken();
} else {
syntaxError (shouldBe);
}
} // end mustBe method.
//--- handle syntax error;
//--- add error to list and abort parse.
protected virtual void syntaxError (String shouldBe) {
errs.Add (new SyntaxError (scanner.CurrentToken, shouldBe));
throw new CompilerErrorException (); // abort the parse.
} // end syntaxError method.
protected virtual void syntaxError2(String shouldBe)
{
errs.Add(new SyntaxError2(scanner.CurrentToken, shouldBe));
throw new CompilerErrorException(); // abort the parse.
} // end syntaxError method.
//=== recogniser method for the starter symbol.
protected abstract void recStarter ();
} // end RdParser class
//=== Abstract Rd parser class including Turner's error recovery method.
public abstract class RecoveringRdParser : RdParser {
//--- state of the parse.
private bool recovering; // indicates whether or not in recovering mode.
//--- constructor method.
public RecoveringRdParser (IScanner scan)
: base (scan)
{
recovering = false;
} // end constructor method.
//=== the public API.
//--- is the parser recovering from a previous error?
public new bool IsRecovering
{ get { return recovering; } }
//=== Overriden RD primitive methods.
//--- Ensure that a specified token is present; an error if not present.
//--- If ok then consumes the token and reads in the next one; if not ok then controls error handling.
//--- Uses Turner's error recovery approach.
protected override void mustBe (String shouldBe) {
if (recovering) {
// in recovering mode so Synchronize input with expected token.
while (!have (shouldBe) && !scanner.EndOfFile) {
scanner.NextToken();
}
if (scanner.EndOfFile) return; // unable to synchronise before EOF.
scanner.NextToken();
recovering = false;
}
else {
// Not recovering so check if we have what we expect.
if (have (shouldBe)) {
scanner.NextToken(); // everything ok so get the next token.
} else {
syntaxError (shouldBe);
}
}
} // end mustBe method.
//--- Process syntax errors.
protected override void syntaxError (String shouldBe) {
if (recovering) return; // don't report errors when recovering.
errs.Add (new SyntaxError (scanner.CurrentToken, shouldBe));
recovering = true; // go into recovering mode.
} // end syntaxError method.
protected override void syntaxError2(String shouldBe)
{
if (recovering) return; // don't report errors when recovering.
errs.Add(new SyntaxError2(scanner.CurrentToken, shouldBe));
recovering = true; // go into recovering mode.
} // end syntaxError method.
//=== recogniser method for the starter symbol.
protected override abstract void recStarter ();
} // end RecoveringRdParser class.
//=== Exception used to indicate a compiler error was found to allow premature termination of parse.
class CompilerErrorException : ApplicationException {
} // end CompilerErrorException class.
// at this time no implementation of this class is required, only its existance.
public class customParser : RecoveringRdParser
{
private customSemantics semantics;
private List<IToken> tokens;
private List<IToken> wrongTokens;
public customParser() :
base(new PALScanner())
{
semantics = new customSemantics(this);
tokens = new List<IToken>();
wrongTokens = new List<IToken>();
}
//<Program> ::= PROGRAM Identifier WITH <VarDecls> IN(<Statement>)+ END
protected override void recStarter()
{
if (have("PROGRAM"))
{
Scope.OpenScope();
mustBe("PROGRAM");
if (have(Token.IdentifierToken))
{
mustBe(Token.IdentifierToken);
}
else
{
syntaxError("Program name");
}
mustBe("WITH");
recVarDeclaration();
mustBe("IN");
do
{
recStatement();
} while (have(Token.IdentifierToken) || have("UNTIL") || have("IF") || have("INPUT") || have("OUTPUT"));
mustBe("END");
}
else
{
syntaxError("PROGRAM");
}
Scope.CloseScope();
}
// <VarDecls> ::= (<IdentList> AS <Type>)* ;
private void recVarDeclaration()
{
var type = -1;
while (have(Token.IdentifierToken))
{
tokens.Add(scanner.CurrentToken);
mustBe(Token.IdentifierToken);
recIdentList();
if (have("AS"))
{
mustBe("AS");
}
else if (have(Token.IdentifierToken))
{
syntaxError(",");
}
else
{
syntaxError("AS");
}
type = recType();
if (type != -1)
{
foreach (IToken tkn in tokens)
{
semantics.DeclareID(tkn, type); // declare ID
}
tokens.Clear();
}
}
}
//<IdentList> ::= Identifier ( , Identifier)* ;
private void recIdentList()
{
if (have(","))
{
mustBe(",");
if (have(Token.IdentifierToken))
{
tokens.Add(scanner.CurrentToken);
mustBe(Token.IdentifierToken);
recIdentList();
}
else if (have("AS"))
{
syntaxError2("Misplaced comma");
}
else
{
syntaxError("Identifier");
}
}
}
// <Type> ::= REAL | INTEGER ;
private int recType()
{
int varType;
if (have("REAL"))
{
mustBe("REAL");
varType = LanguageType.Real;
}
else if (have("INTEGER"))
{
mustBe("INTEGER");
varType = LanguageType.Integer;
}
else
{
varType = LanguageType.Undefined;
syntaxError("Type"); //?
}
return varType;
// return semantic information
}
//<Statement> ::= <Assignment> | <Loop> | <Conditional> | <I-o> ;
private void recStatement()
{
if (have(Token.IdentifierToken))
{
recAssignment();
}
else if (have("UNTIL"))
{
recLoop();
}
else if (have("IF"))
{
recConditional();
}
else if (have("INPUT") || have("OUTPUT"))
{
recIo();
}
else
{
syntaxError("Statement");
}
}
//<Assignment> ::= Identifier = <Expression> ;
private void recAssignment()
{
if (have(Token.IdentifierToken))
{
int varType = semantics.CheckID(scanner.CurrentToken);
mustBe(Token.IdentifierToken);
mustBe("=");
int expType = recExpression(varType);
if (varType != LanguageType.Undefined)
{
foreach (IToken wrongtkn in wrongTokens)
{
semantics.CheckTypesSame(wrongtkn, varType, expType);
}
wrongTokens.Clear();
}
}
else
{
syntaxError("Identifier");
}
}
//<Expression> ::= <Term> ( (+|-) <Term>)* ;
private int recExpression(int leftValue)
{
int lExpr = recTerm(leftValue);
while (have("+") || have("-"))
{
if (have("+"))
{
mustBe("+");
}
else if (have("-"))
{
mustBe("-");
}
int rExpr = recTerm(leftValue);
}
return lExpr;
}
//<Term> ::= <Factor> ( (*|/) <Factor>)* ;
private int recTerm(int leftValue)
{
int lTerm = recFactor(leftValue);
while (have("*") || have("/"))
{
if (have("*"))
{
mustBe("*");
}
else if (have("/"))
{
mustBe("/");
}
var exp = scanner.CurrentToken;
int rTerm = LanguageType.Undefined;
if (leftValue != LanguageType.Undefined)
{
rTerm = recFactor(leftValue);
}
else
{
rTerm = recFactor(lTerm);
}
//semantics.CheckTypesSame(exp, lTerm, rTerm); // do poprawy
if (lTerm!= LanguageType.Undefined && leftValue == LanguageType.Undefined)
{
foreach (IToken wrongtkn in wrongTokens)
{
//Console.WriteLine("Term: token " + wrongtkn + " type: " + lTerm);
semantics.CheckTypesSame(wrongtkn, lTerm, rTerm);
}
wrongTokens.Clear();
}
}
return lTerm;
}
//<Factor> ::= (+|-)? ( <Value> | "(" <Expression> ")" ) ;
private int recFactor(int leftValue)
{
if (have("+"))
{
mustBe("+");
}
else if (have("-"))
{
mustBe("-");
}
int factorType = LanguageType.Undefined;
if (have(Token.IdentifierToken) || have(Token.IntegerToken) || have(Token.RealToken))
{
factorType = recValue(leftValue);
}
else if (have("("))
{
mustBe("(");
factorType = recExpression(leftValue);
mustBe(")");
}
return factorType;
}
//<Value> ::= Identifier | IntegerValue | RealValue ;
private int recValue(int leftValue)
{
int recValue = LanguageType.Undefined;
if (have(Token.IdentifierToken))
{
recValue = semantics.CheckID(scanner.CurrentToken);
if (recValue != leftValue && leftValue!=LanguageType.Undefined)
{
wrongTokens.Add(scanner.CurrentToken);
}
mustBe(Token.IdentifierToken);
}
else if (have(Token.IntegerToken))
{
recValue = LanguageType.Integer;
if (recValue != leftValue && leftValue != LanguageType.Undefined)
{
wrongTokens.Add(scanner.CurrentToken);
}
mustBe(Token.IntegerToken);
}
else if (have(Token.RealToken))
{
recValue = LanguageType.Real;
if (recValue != leftValue && leftValue != LanguageType.Undefined)
{
wrongTokens.Add(scanner.CurrentToken);
}
mustBe(Token.RealToken);
}
else
{
syntaxError("Integer/Real/Identifier");
}
return recValue;
}
//<Loop> ::= UNTIL <BooleanExpr> REPEAT (<Statement>)* ENDLOOP ;
private void recLoop()
{
if (have("UNTIL"))
{
mustBe("UNTIL");
recBoolean();
mustBe("REPEAT");
while (have(Token.IdentifierToken) || have("UNTIL") || have("IF") || have("INPUT") || have("OUTPUT"))
{
recStatement();
}
mustBe("ENDLOOP");
}
else
{
syntaxError("UNTIL");
}
}
//<Conditional> ::= IF <BooleanExpr> THEN (<Statement>)* (ELSE (<Statement>)* )? ENDIF ;
private void recConditional()
{
if (have("IF"))
{
mustBe("IF");
recBoolean();
mustBe("THEN");
while (have(Token.IdentifierToken) || have("UNTIL") || have("IF") || have("INPUT") || have("OUTPUT"))
{
recStatement();
}
if (have("ELSE"))
{
mustBe("ELSE");
while (have(Token.IdentifierToken) || have("UNTIL") || have("IF") || have("INPUT") || have("OUTPUT"))
{
recStatement();
}
}
mustBe("ENDIF");
}
else
{
syntaxError("IF");
}
}
//<BooleanExpr> ::= <Expression> ("<" | "=" | ">") <Expression> ;
private void recBoolean()
{
int lExpr = recExpression(LanguageType.Undefined);
if (have("<") || have(">") || have("="))
{
if (have("<"))
{
mustBe("<");
}
else if (have("="))
{
mustBe("=");
}
else if (have(">"))
{
mustBe(">");
}
int rExpr = recExpression(lExpr);
foreach (IToken wrongtkn in wrongTokens)
{
//Console.WriteLine("Boolean: token " + wrongtkn + " type: " + lExpr);
semantics.CheckTypesSame(wrongtkn, lExpr, rExpr);
}
wrongTokens.Clear();
}
else
{
syntaxError("<, > or =");
}
}
//<I-o> ::= INPUT <IdentList> | OUTPUT<Expression>( , <Expression>)* ;
private void recIo()
{
if (have("INPUT"))
{
mustBe("INPUT");
if (have(Token.IdentifierToken))
{
semantics.CheckID(scanner.CurrentToken);
mustBe(Token.IdentifierToken);
recIdentList();
}
}
else if (have("OUTPUT"))
{
mustBe("OUTPUT");
int type = recExpression(LanguageType.Undefined);
while (have(","))
{
mustBe(",");
recExpression(LanguageType.Undefined);
}
}
else
{
syntaxError("IO error");
}
}
}
} // end namespace.