forked from lkesteloot/turbopascal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParser.js
1380 lines (1176 loc) · 54.3 KB
/
Parser.js
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
// Parses a lexer's output into a tree of Node objects.
'use strict';
if (typeof define !== 'function') { var define = require('amdefine')(module) };
define(["./Token", "./Node", "./PascalError", "./inst", "./SymbolTable", "./Symbol", "./modules", "./RawData"],
function (Token, Node, PascalError, inst, SymbolTable, Symbol, modules, RawData) {
var Parser = function (lexer) {
this.lexer = lexer;
};
// Parse an entire Pascal program.
Parser.prototype.parse = function (symbolTable) {
var node = this._parseSubprogramDeclaration(symbolTable, Node.PROGRAM);
return node;
};
// Returns whether there are more entities to come. The function is given
// two symbols, one that's a separator and one's that a terminator. Returns
// true and eats the symbol if it sees the separator; returns false and
// leaves the symbol if it sees the terminator. Throws if it sees anything else.
Parser.prototype._moreToCome = function (separator, terminator) {
var token = this.lexer.peek();
if (token.isSymbol(separator)) {
// More to come. Eat the separator.
this.lexer.next();
return true;
} else if (token.isSymbol(terminator)) {
// We're done. Leave the terminator.
return false;
} else {
throw new PascalError(token, "expected \"" + separator +
"\" or \"" + terminator + "\"");
}
};
// Eats the next symbol. If it's not this reserved word, raises an error with this
// message. Returns the token.
Parser.prototype._expectReservedWord = function (reservedWord, message) {
var token = this.lexer.next();
message = message || ("expected reserved word \"" + reservedWord + "\"");
if (!token.isReservedWord(reservedWord)) {
throw new PascalError(token, message);
}
return token;
};
// Eats the next symbol (such as ":="). If it's not this symbol, raises an
// error with this message. Returns the token.
Parser.prototype._expectSymbol = function (symbol, message) {
var token = this.lexer.next();
if (token.tokenType !== Token.SYMBOL || token.value !== symbol) {
message = message || ("expected symbol \"" + symbol + "\"");
throw new PascalError(token, message);
}
return token;
};
// Eats the next symbol. If it's not an identifier, raises an error with this
// message. Returns the identifier token.
Parser.prototype._expectIdentifier = function (message) {
var token = this.lexer.next();
if (token.tokenType !== Token.IDENTIFIER) {
throw new PascalError(token, message);
}
return token;
};
// Returns a list of declarations (var, etc.).
Parser.prototype._parseDeclarations = function (symbolTable) {
var declarations = [];
// Parse each declaration or block.
while (!this.lexer.peek().isReservedWord("begin")) {
// This parser also eats the semicolon after the declaration.
var nodes = this._parseDeclaration(symbolTable);
// Extend the declarations array with the nodes array.
declarations.push.apply(declarations, nodes);
}
return declarations;
}
// Parse any declaration (uses, var, procedure, function). Returns a list
// of them, in case a declaration expands to be multiple nodes.
Parser.prototype._parseDeclaration = function (symbolTable) {
var token = this.lexer.peek();
if (token.isReservedWord("uses")) {
return this._parseUsesDeclaration(symbolTable);
} else if (token.isReservedWord("var")) {
this._expectReservedWord("var");
return this._parseVarDeclaration(symbolTable);
} else if (token.isReservedWord("const")) {
this._expectReservedWord("const");
return this._parseConstDeclaration(symbolTable);
} else if (token.isReservedWord("type")) {
this._expectReservedWord("type");
return this._parseTypeDeclaration(symbolTable);
} else if (token.isReservedWord("procedure")) {
return [this._parseSubprogramDeclaration(symbolTable, Node.PROCEDURE)];
} else if (token.isReservedWord("function")) {
return [this._parseSubprogramDeclaration(symbolTable, Node.FUNCTION)];
} else if (token.tokenType === Token.EOF) {
throw new PascalError(token, "unexpected end of file");
} else {
throw new PascalError(token, "unexpected token");
}
};
// Parse "uses" declaration, which is a list of identifiers. Returns a list of nodes.
Parser.prototype._parseUsesDeclaration = function (symbolTable) {
var usesToken = this._expectReservedWord("uses");
var nodes = [];
do {
var token = this._expectIdentifier("expected module name");
var node = new Node(Node.USES, usesToken, {
name: new Node(Node.IDENTIFIER, token)
});
// Import the module's symbols into this symbol table.
modules.importModule(token.value, symbolTable);
nodes.push(node);
} while (this._moreToCome(",", ";"));
this._expectSymbol(";");
return nodes;
};
// Parse "var" declaration, which is a variable and its type. Returns a list of nodes.
Parser.prototype._parseVarDeclaration = function (symbolTable) {
var nodes = [];
do {
var startNode = nodes.length;
do {
var nameToken = this._expectIdentifier("expected variable name");
var node = new Node(Node.VAR, null, {
name: new Node(Node.IDENTIFIER, nameToken)
});
nodes.push(node);
} while (this._moreToCome(",", ":"));
// Skip colon.
this._expectSymbol(":");
// Parse the variable's type.
var type = this._parseType(symbolTable);
// Set the type of all nodes for this line.
for (var i = startNode; i < nodes.length; i++) {
nodes[i].type = type;
// Add the variable to our own symbol table.
nodes[i].symbol = symbolTable.addSymbol(
nodes[i].name.token.value, Node.VAR, type);
}
// We always finish the line with a semicolon.
this._expectSymbol(";");
// If the next token is an identifier, then we keep going.
} while (this.lexer.peek().tokenType === Token.IDENTIFIER);
return nodes;
};
// Parse "const" declaration, which is an identifier, optional type, and
// required value. Returns an array of nodes.
Parser.prototype._parseConstDeclaration = function (symbolTable) {
var nodes = [];
do {
// Parse the constant name.
var token = this._expectIdentifier("expected constant name");
var identifierNode = new Node(Node.IDENTIFIER, token);
// Parse optional type.
var type = null;
token = this.lexer.peek();
if (token.isSymbol(":")) {
this.lexer.next();
type = this._parseType(symbolTable);
}
// Parse value. How we do this depends on whether it's a typed constant,
// and if it is, what kind.
this._expectSymbol("=");
// Create the node.
var node;
if (type === null) {
// Constant.
var expression = this._parseExpression(symbolTable);
node = new Node(Node.CONST, null, {
name: identifierNode,
type: expression.expressionType,
value: expression
});
} else {
// Typed constant.
var rawData;
// TODO We need to verify type compatibility throughout here.
if (type.nodeType === Node.ARRAY_TYPE) {
rawData = this._parseArrayConstant(symbolTable, type);
} else if (type.nodeType === Node.RECORD_TYPE) {
throw new PascalError(token, "constant records not supported");
} else if (type.nodeType === Node.SIMPLE_TYPE) {
rawData = new RawData();
rawData.addNode(this._parseExpression(symbolTable));
} else {
throw new PascalError(token, "unhandled typed constant type " + type.nodeType);
}
node = new Node(Node.TYPED_CONST, null, {
name: identifierNode,
type: type,
rawData: rawData
});
}
// Add the constant to our own symbol table.
node.symbol = symbolTable.addSymbol(identifierNode.token.value,
node.nodeType, node.type);
if (type === null) {
node.symbol.value = node.value;
}
nodes.push(node);
// Semicolon terminator.
this._expectSymbol(";");
} while (this.lexer.peek().tokenType === Token.IDENTIFIER);
return nodes;
};
// Parse an array constant, which is a parenthesized list of constants. These
// can be nested for multi-dimensional arrays. Returns a RawData object.
Parser.prototype._parseArrayConstant = function (symbolTable, type) {
// The raw linear (in-memory) version of the data.
var rawData = new RawData();
// Recursive function to parse a dimension of the array. The first
// dimension (ranges[0]) is the "major" one, and we recurse until
// the last dimension, where we actually parse the constant
// expressions.
var self = this;
var parseDimension = function (d) {
self._expectSymbol("(");
var low = type.ranges[d].getRangeLowBound();
var high = type.ranges[d].getRangeHighBound();
for (var i = low; i <= high; i++) {
if (d === type.ranges.length - 1) {
// Parse the next constant.
rawData.addNode(self._parseExpression(symbolTable));
} else {
parseDimension(d + 1);
}
if (i < high) {
self._expectSymbol(",");
}
}
self._expectSymbol(")");
};
// Start the recursion.
parseDimension(0);
return rawData;
};
// Parse "type" declaration, which is an identifier and a type. Returns an
// array of nodes.
Parser.prototype._parseTypeDeclaration = function (symbolTable) {
var nodes = [];
// Pointer types are permitted to point to an undefined type name, as long as
// that name is defined by the end of the "type" section. We keep track of these
// here and resolve them at the end.
var incompleteTypes = [];
do {
// Parse identifier.
var token = this._expectIdentifier("expected type name");
var identifierNode = new Node(Node.IDENTIFIER, token);
// Required equal sign.
var equalToken = this._expectSymbol("=");
// Parse type.
var type = this._parseType(symbolTable, incompleteTypes, token.value);
// Create the node.
var node = new Node(Node.TYPE, equalToken, {
name: identifierNode,
type: type,
});
// Add the type to our own symbol table.
node.symbol = symbolTable.addType(identifierNode.token.value, type);
nodes.push(node);
// Semicolon terminator.
this._expectSymbol(";");
} while (this.lexer.peek().tokenType === Token.IDENTIFIER);
// Fill in incomplete types. They're required to be defined by the end of
// the "type" block.
for (var i = 0; i < incompleteTypes.length; i++) {
var node = incompleteTypes[i];
node.type = symbolTable.getType(node.typeName.token).symbol.type;
}
return nodes;
};
// Parse procedure, function, or program declaration.
Parser.prototype._parseSubprogramDeclaration = function (symbolTable, nodeType) {
// Get the string like "procedure", etc.
var declType = Node.nodeLabel[nodeType];
// Parse the opening token.
var procedureToken = this._expectReservedWord(declType);
// Parse the name.
var nameToken = this._expectIdentifier("expected " + declType + " name");
// From now on we're in our own table.
var symbolTable = new SymbolTable(symbolTable);
// Parse the parameters.
var token = this.lexer.peek();
var parameters = [];
if (token.isSymbol("(")) {
this._expectSymbol("(");
var start = 0;
do {
var byReference = false;
// See if we're passing this batch by reference.
if (this.lexer.peek().isReservedWord("var")) {
this._expectReservedWord("var");
byReference = true;
}
// Parameters can be batched by type.
do {
token = this._expectIdentifier("expected parameter name");
parameters.push(new Node(Node.PARAMETER, colon, {
name: new Node(Node.IDENTIFIER, token),
byReference: byReference
}));
} while (this._moreToCome(",", ":"));
var colon = this._expectSymbol(":");
// Add the type to each parameter.
var type = this._parseType(symbolTable);
for (var i = start; i < parameters.length; i++) {
parameters[i].type = type;
}
start = parameters.length;
} while (this._moreToCome(";", ")"));
this._expectSymbol(")");
}
// Add parameters to our own symbol table.
for (var i = 0; i < parameters.length; i++) {
var parameter = parameters[i];
var symbol = symbolTable.addSymbol(parameter.name.token.value, Node.PARAMETER,
parameter.type, parameter.byReference);
}
// Parse the return type if it's a function.
var returnType;
if (nodeType === Node.FUNCTION) {
this._expectSymbol(":");
returnType = this._parseType(symbolTable);
} else {
returnType = Node.voidType;
}
this._expectSymbol(";");
// Functions have an additional fake symbol: their own name, which maps
// to the mark pointer location (return value).
if (nodeType === Node.FUNCTION) {
var name = nameToken.value;
symbolTable.symbols[name.toLowerCase()] = new Symbol(name, returnType, 0, false);
}
// Create the type of the subprogram itself.
var type = new Node(Node.SUBPROGRAM_TYPE, procedureToken, {
parameters: parameters,
returnType: returnType,
});
// Add the procedure to our parent symbol table.
var symbol = symbolTable.parentSymbolTable.addSymbol(nameToken.value,
Node.SUBPROGRAM_TYPE, type);
// Parse declarations.
var declarations = this._parseDeclarations(symbolTable);
// Parse begin/end block.
var block = this._parseBlock(symbolTable, "begin", "end");
// Make node.
var node = new Node(nodeType, procedureToken, {
name: new Node(Node.IDENTIFIER, nameToken),
declarations: declarations,
block: block
});
node.symbol = symbol;
node.symbolTable = symbolTable;
node.expressionType = type;
// Semicolon terminator.
this._expectSymbol(nodeType === Node.PROGRAM ? "." : ";");
return node;
};
// Parse a begin/end block. The startWord must be the next token. The endWord
// will end the block and is eaten.
Parser.prototype._parseBlock = function (symbolTable, startWord, endWord) {
var token = this._expectReservedWord(startWord);
var statements = [];
var foundEnd = false;
while (!foundEnd) {
token = this.lexer.peek();
if (token.isReservedWord(endWord)) {
// End of block.
this.lexer.next();
foundEnd = true;
} else if (token.isSymbol(";")) {
// Empty statement.
this.lexer.next();
} else {
// Parse statement.
statements.push(this._parseStatement(symbolTable));
// After an actual statement, we require a semicolon or end of block.
token = this.lexer.peek();
if (!token.isReservedWord(endWord) && !token.isSymbol(";")) {
throw new PascalError(token, "expected \";\" or \"" + endWord + "\"");
}
}
}
return new Node(Node.BLOCK, token, {
statements: statements
});
};
// Parse a statement, such as a for loop, while loop, assignment, or procedure call.
Parser.prototype._parseStatement = function (symbolTable) {
var token = this.lexer.peek();
var node;
// Handle simple constructs.
if (token.isReservedWord("if")) {
node = this._parseIfStatement(symbolTable);
} else if (token.isReservedWord("while")) {
node = this._parseWhileStatement(symbolTable);
} else if (token.isReservedWord("repeat")) {
node = this._parseRepeatStatement(symbolTable);
} else if (token.isReservedWord("for")) {
node = this._parseForStatement(symbolTable);
} else if (token.isReservedWord("begin")) {
node = this._parseBlock(symbolTable, "begin", "end");
} else if (token.isReservedWord("exit")) {
node = this._parseExitStatement(symbolTable);
} else if (token.tokenType === Token.IDENTIFIER) {
// This could be an assignment or procedure call. Both start with an identifier.
node = this._parseVariable(symbolTable);
// See if this is an assignment or procedure call.
token = this.lexer.peek();
if (token.isSymbol(":=")) {
// It's an assignment.
node = this._parseAssignment(symbolTable, node);
} else if (node.nodeType === Node.IDENTIFIER) {
// Must be a procedure call.
node = this._parseProcedureCall(symbolTable, node);
} else {
throw new PascalError(token, "invalid statement");
}
} else {
throw new PascalError(token, "invalid statement");
}
return node;
};
// Parse a variable. A variable isn't just an identifier, like "foo", it can also
// be an array dereference, like "variable[index]", a field designator, like
// "variable.fieldName", or a pointer dereference, like "variable^". In all
// three cases the "variable" part is itself a variable. This function always
// returns a node of type IDENTIFIER, ARRAY, FIELD_DESIGNATOR, or DEREFERENCE.
Parser.prototype._parseVariable = function (symbolTable) {
// Variables always start with an identifier.
var identifierToken = this._expectIdentifier("expected identifier");
// Create an identifier node for this token.
var node = new Node(Node.IDENTIFIER, identifierToken);
// Look up the symbol so we can set its type.
var symbolLookup = symbolTable.getSymbol(identifierToken);
node.symbolLookup = symbolLookup;
node.expressionType = symbolLookup.symbol.type;
// The next token determines whether the variable continues or ends here.
while (true) {
var nextToken = this.lexer.peek();
if (nextToken.isSymbol("[")) {
// Replace the node with an array node.
node = this._parseArrayDereference(symbolTable, node);
} else if (nextToken.isSymbol(".")) {
// Replace the node with a record designator node.
node = this._parseRecordDesignator(symbolTable, node);
} else if (nextToken.isSymbol("^")) {
// Replace the node with a pointer dereference.
this._expectSymbol("^");
var variable = node;
if (!variable.expressionType.isSimpleType(inst.A)) {
throw new PascalError(nextToken, "can only dereference pointers");
}
node = new Node(Node.DEREFERENCE, nextToken, {
variable: node
});
node.expressionType = variable.expressionType.type;
} else {
// We're done with the variable.
break;
}
}
return node;
};
// Parse an assignment. We already have the left-hand-side variable.
Parser.prototype._parseAssignment = function (symbolTable, variable) {
var assignToken = this._expectSymbol(":=");
var expression = this._parseExpression(symbolTable);
return new Node(Node.ASSIGNMENT, assignToken, {
lhs: variable,
rhs: expression.castToType(variable.expressionType)
});
};
// Parse a procedure call. We already have the identifier, so we only need to
// parse the optional arguments.
Parser.prototype._parseProcedureCall = function (symbolTable, identifier) {
// Look up the symbol to make sure it's a procedure.
var symbolLookup = symbolTable.getSymbol(identifier.token);
var symbol = symbolLookup.symbol;
identifier.symbolLookup = symbolLookup;
// Verify that it's a procedure.
if (symbol.type.nodeType === Node.SUBPROGRAM_TYPE && symbol.type.returnType.isVoidType()) {
// Parse optional arguments.
var argumentList = this._parseArguments(symbolTable, symbol.type);
// If the call is to the native function "New", then we pass a hidden second
// parameter, the size of the object to allocate. The procedure needs that
// to know how much to allocate.
if (symbol.name.toLowerCase() === "new" && symbol.isNative) {
if (argumentList.length === 1) {
argumentList.push(Node.makeNumberNode(
argumentList[0].expressionType.type.getTypeSize()));
} else {
throw new PascalError(identifier.token, "new() takes one argument");
}
}
return new Node(Node.PROCEDURE_CALL, identifier.token, {
name: identifier,
argumentList: argumentList
});
} else {
throw new PascalError(identifier.token, "expected procedure");
}
};
// Parse an optional argument list. Returns a list of nodes. type is the
// type of the subprogram being called.
Parser.prototype._parseArguments = function (symbolTable, type) {
var argumentList = [];
if (this.lexer.peek().isSymbol("(")) {
this._expectSymbol("(");
var token = this.lexer.peek();
if (token.isSymbol(")")) {
// Empty arguments.
this.lexer.next();
} else {
do {
// Find the formal parameter. Some functions (like WriteLn)
// are variadic, so allow them to have more arguments than
// were defined.
var argumentIndex = argumentList.length;
var parameter;
if (argumentIndex < type.parameters.length) {
parameter = type.parameters[argumentIndex];
} else {
// Accept anything (by value).
parameter = null;
}
var argument;
if (parameter && parameter.byReference) {
// This has to be a variable, not any expression, since
// we need its address.
argument = this._parseVariable(symbolTable);
// Hack this "byReference" field that'll be used by
// the compiler to pass the argument's address.
argument.byReference = true;
} else {
argument = this._parseExpression(symbolTable);
}
// Cast to type of parameter.
if (parameter) {
argument = argument.castToType(parameter.type);
}
argumentList.push(argument);
} while (this._moreToCome(",", ")"));
this._expectSymbol(")");
}
}
return argumentList;
}
// Parse an if statement.
Parser.prototype._parseIfStatement = function (symbolTable) {
var token = this._expectReservedWord("if");
var expression = this._parseExpression(symbolTable);
if (!expression.expressionType.isBooleanType()) {
throw new PascalError(expression.token, "if condition must be a boolean");
}
this._expectReservedWord("then");
var thenStatement = this._parseStatement(symbolTable);
var elseStatement = null;
var elseToken = this.lexer.peek();
if (elseToken.isReservedWord("else")) {
this._expectReservedWord("else");
var elseStatement = this._parseStatement(symbolTable);
}
return new Node(Node.IF, token, {
expression: expression,
thenStatement: thenStatement,
elseStatement: elseStatement
});
};
// Parse a while statement.
Parser.prototype._parseWhileStatement = function (symbolTable) {
var whileToken = this._expectReservedWord("while");
// Parse the expression that keeps the loop going.
var expression = this._parseExpression(symbolTable);
if (!expression.expressionType.isBooleanType()) {
throw new PascalError(whileToken, "while condition must be a boolean");
}
// The "do" keyword is required.
this._expectReservedWord("do", "expected \"do\" for \"while\" loop");
// Parse the statement. This can be a begin/end pair.
var statement = this._parseStatement(symbolTable);
// Create the node.
return new Node(Node.WHILE, whileToken, {
expression: expression,
statement: statement
});
};
// Parse a repeat/until statement.
Parser.prototype._parseRepeatStatement = function (symbolTable) {
var block = this._parseBlock(symbolTable, "repeat", "until");
var expression = this._parseExpression(symbolTable);
if (!expression.expressionType.isBooleanType()) {
throw new PascalError(node.token, "repeat condition must be a boolean");
}
return new Node(Node.REPEAT, block.token, {
block: block,
expression: expression
});
};
// Parse a for statement.
Parser.prototype._parseForStatement = function (symbolTable) {
var token = this._expectReservedWord("for");
var loopVariableToken = this._expectIdentifier("expected identifier for \"for\" loop");
this._expectSymbol(":=");
var fromExpr = this._parseExpression(symbolTable);
var downto = this.lexer.peek().isReservedWord("downto");
if (downto) {
this._expectReservedWord("downto");
} else {
// Default error message if it's neither.
this._expectReservedWord("to");
}
var toExpr = this._parseExpression(symbolTable);
this._expectReservedWord("do");
var body = this._parseStatement(symbolTable);
// Get the symbol for the loop variable.
var symbolLookup = symbolTable.getSymbol(loopVariableToken);
var loopVariableType = symbolLookup.symbol.type;
var variable = new Node(Node.IDENTIFIER, loopVariableToken);
variable.symbolLookup = symbolLookup;
// Cast "from" and "to" to type of variable.
fromExpr = fromExpr.castToType(loopVariableType);
toExpr = toExpr.castToType(loopVariableType);
return new Node(Node.FOR, token, {
variable: variable,
fromExpr: fromExpr,
toExpr: toExpr,
body: body,
downto: downto
});
};
// Parse an exit statement.
Parser.prototype._parseExitStatement = function (symbolTable) {
var token = this._expectReservedWord("exit");
return new Node(Node.EXIT, token);
};
// Parse a type declaration, such as "Integer" or "Array[1..70] of Real".
// The "incompleteTypes" array is optional. If specified, and if a pointer
// to an unknown type is found, it is added to the array. If such a pointer
// is found and the array was not passed in, we throw.
Parser.prototype._parseType = function (symbolTable, incompleteTypes, parentName) {
var token = this.lexer.next();
var node;
if (token.isReservedWord("array")) {
// Array type.
this._expectSymbol("[");
var ranges = [];
// Parse multiple ranges.
do {
var range = this._parseRange(symbolTable);
ranges.push(range);
} while (this._moreToCome(",", "]"));
this._expectSymbol("]");
this._expectReservedWord("of");
var elementType = this._parseType(symbolTable, incompleteTypes);
node = new Node(Node.ARRAY_TYPE, token, {
elementType: elementType,
ranges: ranges
});
} else if (token.isReservedWord("record")) {
node = this._parseRecordType(symbolTable, token, incompleteTypes);
} else if (token.isSymbol("^")) {
var typeNameToken = this._expectIdentifier("expected type identifier");
var type;
try {
type = symbolTable.getType(typeNameToken).symbol.type;
} catch (e) {
if (e instanceof PascalError) {
// The type symbol is not defined. Pascal requires that it be defined
// by the time the "type" section ends.
type = null;
} else {
throw new PascalError(typeNameToken, "exception looking up type symbol");
}
}
node = new Node(Node.SIMPLE_TYPE, token, {
typeCode: inst.A,
typeName: new Node(Node.IDENTIFIER, typeNameToken),
type: type
});
// See if this is a forward type reference.
if (type === null) {
// We'll fill these in later.
if (incompleteTypes) {
incompleteTypes.push(node);
} else {
throw new PascalError(typeNameToken, "unknown type");
}
}
} else if (token.tokenType === Token.IDENTIFIER) {
// Type name.
var symbolLookup = symbolTable.getType(token);
// Substitute the type right away. This will mess up the display of
// the program, since you'll see the full type everywhere, but will
// simplify the compilation step.
node = symbolLookup.symbol.type;
// Strings with defined lengths
var nToken = this.lexer.peek();
if (nToken.isSymbol("[")) {
var ob = this.lexer.next();
var len = this.lexer.next();
this._expectSymbol("]");
}
} else if (token.isSymbol('(')) {
var entries = [];
do {
var entry = this._expectIdentifier("expected enumeration entry");
//console.warn('Defining enum value',entry.value,entries.length);
var eNode = new Node(Node.CONST, entry, {
name: entry.value,
type: inst.I,
value: entries.length,
symbolTable: symbolTable // mike
});
symbolTable.addNativeConstant(entry.value, entries.length, Node.integerType);
entries.push(entry);
} while (this._moreToCome(",", ")"));
this._expectSymbol(")");
node = new Node(Node.ENUM_TYPE, token, {
typeCode: inst.I,
typeName: new Node(Node.IDENTIFIER, typeNameToken),
type: type,
entries: entries
});
//console.warn('Defining enum length',parentName,entries.length);
symbolTable.addNativeConstant(parentName, entries.length, Node.integerType);
} else {
throw new PascalError(token, "can't parse type");
}
// A type node is its own type.
node.expressionType = node;
return node;
};
// Parse a record type definition. See _parseType() for an explanation of "incompleteTypes".
Parser.prototype._parseRecordType = function (symbolTable, token, incompleteTypes) {
// A record is a list of fields.
var fields = [];
while (true) {
var token = this.lexer.peek();
if (token.isSymbol(";")) {
// Empty field, no problem.
this.lexer.next();
} else if (token.isReservedWord("end")) {
// End of record.
this._expectReservedWord("end");
break;
} else {
fields.push.apply(fields,
this._parseRecordSection(symbolTable, token, incompleteTypes));
// Must have ";" or "end" after field.
var token = this.lexer.peek();
if (!token.isSymbol(";") && !token.isReservedWord("end")) {
throw new PascalError(token, "expected \";\" or \"end\" after field");
}
}
}
// Calculate the offset of each field.
var offset = 0;
for (var i = 0; i < fields.length; i++) {
var field = fields[i];
field.offset = offset;
offset += field.type.getTypeSize();
}
return new Node(Node.RECORD_TYPE, token, {
fields: fields
});
};
// Parse a section of a record type, which is a list of identifiers and
// their type. Returns an array of FIELD nodes. See _parseType() for an
// explanation of "incompleteTypes".
Parser.prototype._parseRecordSection = function (symbolTable, fieldToken, incompleteTypes) {
var fields = [];
do {
var nameToken = this._expectIdentifier("expected field name");
var field = new Node(Node.FIELD, fieldToken, {
name: new Node(Node.IDENTIFIER, nameToken),
offset: 0
});
fields.push(field);
} while (this._moreToCome(",", ":"));
// Skip colon.
this._expectSymbol(":");
// Parse the fields's type.
var type = this._parseType(symbolTable, incompleteTypes);
// Set the type of all fields.
for (var i = 0; i < fields.length; i++) {
fields[i].type = type;
}
return fields;
};
// Parses a range, such as "5..10". Either can be a constant expression.
Parser.prototype._parseRange = function (symbolTable) {
var low = this._parseExpression(symbolTable);
var next = this.lexer.peek();
if (next.value === "..") {
var token = this.lexer.next();
var high = this._parseExpression(symbolTable);
}
else {
var high = low;
var lToken = new Token(0, Token.NUMBER);
low = new Node(Node.NUMBER, lToken);
}
return new Node(Node.RANGE, token, {low: low, high: high});
};
// Parses an expression.
Parser.prototype._parseExpression = function (symbolTable) {
return this._parseRelationalExpression(symbolTable);
};
// Parses a relational expression.
Parser.prototype._parseRelationalExpression = function (symbolTable) {
var node = this._parseAdditiveExpression(symbolTable);
while (true) {
var token = this.lexer.peek();
if (token.isSymbol("=")) {
node = this._createBinaryNode(symbolTable, token, node, Node.EQUALITY,
this._parseAdditiveExpression).withExpressionType(Node.booleanType);
} else if (token.isSymbol("<>")) {
node = this._createBinaryNode(symbolTable, token, node, Node.INEQUALITY,
this._parseAdditiveExpression).withExpressionType(Node.booleanType);
} else if (token.isSymbol(">")) {
node = this._createBinaryNode(symbolTable, token, node, Node.GREATER_THAN,
this._parseAdditiveExpression).withExpressionType(Node.booleanType);
} else if (token.isSymbol("<")) {
node = this._createBinaryNode(symbolTable, token, node, Node.LESS_THAN,
this._parseAdditiveExpression).withExpressionType(Node.booleanType);
} else if (token.isSymbol(">=")) {
node = this._createBinaryNode(symbolTable, token, node,
Node.GREATER_THAN_OR_EQUAL_TO,
this._parseAdditiveExpression).withExpressionType(Node.booleanType);
} else if (token.isSymbol("<=")) {
node = this._createBinaryNode(symbolTable, token, node, Node.LESS_THAN_OR_EQUAL_TO,
this._parseAdditiveExpression).withExpressionType(Node.booleanType);
} else {
break;
}
}
return node;
};
// Parses an additive expression.
Parser.prototype._parseAdditiveExpression = function (symbolTable) {
var node = this._parseMultiplicativeExpression(symbolTable);
while (true) {
var token = this.lexer.peek();
if (token.isSymbol("+")) {
node = this._createBinaryNode(symbolTable, token, node, Node.ADDITION,
this._parseMultiplicativeExpression);
} else if (token.isSymbol("-")) {
node = this._createBinaryNode(symbolTable, token, node, Node.SUBTRACTION,
this._parseMultiplicativeExpression);
} else if (token.isReservedWord("or")) {
node = this._createBinaryNode(symbolTable, token, node, Node.OR,
this._parseMultiplicativeExpression,