Repository navigation
Expand file tree
/
Copy pathuparser.pas
More file actions
1482 lines (1367 loc) · 40.4 KB
/
Copy pathuparser.pas
File metadata and controls
1482 lines (1367 loc) · 40.4 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
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
unit uParser;
{ This unit contains the parser that processes all tokens; input from the Lexer.
The parser also checks the language grammar. The result of the parsing is
an AST.
Copyright (C) 2018 J. de Haan jdehaan2014@gmail.com
This source is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more details.
A copy of the GNU General Public License is available on the World Wide Web at
<http://www.gnu.org/copyleft/gpl.html>. You can also obtain it by writing to the Free
Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA 02110-1335, USA.
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uLexer, uToken, uAST, uError, Variants;
type
TParser = class
private
type
TFuncForm = (ffFunction, ffAnonym, ffInit);
private
Tokens: TTokens;
Current: integer;
LoopDepth: Integer;
function CurrentToken: TToken;
function Peek: TToken;
procedure Error(Token: TToken; Msg: string);
procedure Expect(const TokenTyp: TTokenTyp);
procedure Next;
procedure Synchronize(Types: TTokenTypSet);
function isLastToken: Boolean;
function MakeID(Name: String): TIdent;
function ParseExprList: TExprList;
public
constructor Create(Lexer: TLexer);
function Parse: TProduct;
private
function ParseIdent: TIdent;
// Expressions
function ParseExpr: TExpr;
function isRelOp: Boolean;
function ParseAddExpr: TExpr;
function isAddOp: Boolean;
function ParseMulExpr: TExpr;
function isMulOp: Boolean;
function ParseShiftExpr: TExpr;
function isShiftOp: Boolean;
function ParseRangeExpr: TExpr;
function ParseUnaryExpr: TExpr;
function ParseCallExpr: TExpr;
function ParseCallArgs(Callee: TExpr): TExpr;
function ParseIfExpr: TExpr;
function ParseMatchExpr: TExpr;
function ParseIdentifierExpr: TExpr;
function ParseParenExpr: TExpr;
function ParseSelfExpr: TExpr;
function ParseInheritedExpr: TExpr;
function ParseArrayDeclExpr(FirstExpr: TExpr): TExpr;
function ParseDictDeclExpr(KeyExpr: TExpr): TExpr;
function ParseBracketExpr: TExpr;
function ParseSetBuilderExpr: TExpr;
function ParseInterpolatedExpr: TExpr;
function ParseFactor: TExpr;
// Statements
function ParseStmt: TStmt;
function ParsePrintStmt: TStmt;
function ParseAssignStmt: TStmt;
function ParseIfStmt: TStmt;
function ParseWhileStmt: TStmt;
function ParseRepeatStmt: TStmt;
function ParseForStmt: TStmt;
function ParseForEachStmt: TStmt;
function ParseEnsureStmt: TStmt;
function ParseSwitchStmt: TStmt;
function ParseBreakStmt: TStmt;
function ParseContinueStmt: TStmt;
function ParseReturnStmt: TStmt;
function ParseUseStmt: TStmt;
// Declarations
function ParseDecl: TDecl;
function ParseDeclList(DeclSet: TTokenTypSet; const TypeName: String): TDeclList;
function ParseVarDecl(Mutable: Boolean): TDecl;
function ParseVarDecls(Mutable: Boolean): TDecl;
function ParseFuncDecl(FuncForm: TFuncForm): TDecl;
function ParseClassDecl: TDecl;
function ParseValDecl: TDecl;
function ParseExtensionDecl: TDecl;
function ParseTraitDecl: TDecl;
function ParseArrayDecl: TDecl;
function ParseKeyValueList: TKeyValueList;
function ParseDictDecl: TDecl;
function ParseEnumDecl: TDecl;
// Blocks
function ParseNode: TNode;
function ParseBlock: TBlock;
function ParseProduct: TProduct;
end;
implementation
uses uLanguage, uReader;
const
ErrSyntax = 'Syntax error, "%s" expected.';
ErrUnexpectedToken = 'Unexpected token: %s.';
ErrDuplicateTerminator = 'Duplicate terminator not allowed.';
ErrUnexpectedAttribute = 'Unexpected attribute "%s:".';
ErrInvalidAssignTarget = 'Invalid assignment target.';
ErrExpectedAssignOpFunc = 'Expected assignment operator, or function call.';
ErrUnrecognizedDeclOrStmt = 'Unrecognized declaration or statement.';
ErrBreakInLoop = 'Break can only be used from inside a loop.';
ErrExpectedArrow = 'Expected arrow "=>".';
ErrIncorrectInherit = 'Incorrect inheritance expression.';
ErrUnallowedDeclIn = 'Unallowed declaration in "%s".';
ErrNotExistsUseFile = 'Used file "%s" does not exist.';
ErrIncorrectUseFile = 'Used file "%s" is incorrect or corrupt.';
ErrNotAllowedInRange = 'Token "%s" not allowed in range expression.';
ErrAtLeastOneEnum = 'At least one enum is required in declaration.';
ErrDuplicateEnum = 'Duplicate enum name "%s".';
ErrNotAllowedInEnum = 'Constant value "%s" not allowed in enum declaration.';
ErrDuplicateSetName = 'Duplicate enum set name "%s".';
function TParser.CurrentToken: TToken;
begin
Result := Tokens[Current];
end;
function TParser.Peek: TToken;
begin
if not isLastToken then
Result := Tokens[Current+1];
end;
procedure TParser.Error(Token: TToken; Msg: string);
begin
Errors.Append(Token, Msg);
Raise EParseError.Create(Msg);
end;
procedure TParser.Expect(const TokenTyp: TTokenTyp);
begin
if CurrentToken.Typ = TokenTyp then
Next
else
Error(CurrentToken, Format(ErrSyntax, [TokenTyp.toString]));
end;
procedure TParser.Next;
begin
Current +=1;
end;
procedure TParser.Synchronize(Types: TTokenTypSet);
begin
while not (CurrentToken.Typ in Types) do
Next;
end;
function TParser.isLastToken: Boolean;
begin
Result := Current = Tokens.Count-1;
end;
function TParser.MakeID(Name: String): TIdent;
begin
with CurrentToken do
Result := TIdent.Create(TToken.Create(
ttIdentifier, Name, Null, Line, Col, FileIndex));
end;
constructor TParser.Create(Lexer: TLexer);
begin
Tokens := Lexer.Tokens;
Current := 0;
LoopDepth := 0;
end;
function TParser.Parse: TProduct;
begin
Result := ParseProduct;
end;
function TParser.ParseExprList: TExprList;
begin
Result := TExprList.Create();
Result.Add(ParseExpr);
while CurrentToken.Typ = ttComma do begin
Next; // skip ,
Result.Add(ParseExpr);
end;
end;
function TParser.ParseIdent: TIdent;
var
Token: TToken;
begin
Token := CurrentToken;
Expect(ttIdentifier);
Result := TIdent.Create(Token);
end;
function TParser.ParseExpr: TExpr;
var
RelOp: TToken;
begin
Result := ParseAddExpr;
if isRelOp then begin
RelOp := CurrentToken;
Next;
Result := TBinaryExpr.Create(Result, RelOp, ParseAddExpr);
end;
end;
function TParser.isRelOp: Boolean;
begin
Result := CurrentToken.Typ in [ttEQ, ttNEQ, ttGT, ttGE, ttLT, ttLE, ttIn, ttIs];
// = <> > >= < <= in is
end;
function TParser.ParseAddExpr: TExpr;
var
AddOp: TToken;
begin
Result := ParseMulExpr;
while isAddOp do begin
AddOp := CurrentToken;
Next;
Result := TBinaryExpr.Create(Result, AddOp, ParseMulExpr);
end;
end;
function TParser.isAddOp: Boolean;
begin
Result := CurrentToken.Typ in [ttPlus, ttMin, ttOr, ttXOr, ttConcat];
// + - | ~ ><
end;
function TParser.ParseMulExpr: TExpr;
var
MulOp: TToken;
begin
Result := ParseShiftExpr;
while isMulOp do begin
MulOp := CurrentToken;
Next;
Result := TBinaryExpr.Create(Result, MulOp, ParseShiftExpr);
end;
end;
function TParser.isMulOp: Boolean;
begin
Result := CurrentToken.Typ in [ttMul, ttDiv, ttRem, ttAnd, ttColons];
// * / % & ::
end;
function TParser.ParseShiftExpr: TExpr;
var
ShiftOp: TToken;
begin
Result := ParseRangeExpr;
while isShiftOp do begin
ShiftOp := CurrentToken;
Next;
Result := TBinaryExpr.Create(Result, ShiftOp, ParseUnaryExpr);
end;
end;
function TParser.isShiftOp: Boolean;
begin
Result := CurrentToken.Typ in [ttShl, ttShr, ttPow];
// << >> ^
end;
function TParser.ParseRangeExpr: TExpr;
var
UpperBound: TExpr;
Range: TCallExpr;
Exclude: Boolean=False;
Minus: TToken;
One: TConstExpr;
procedure CheckUnaryOp(Expr: TExpr);
begin
if Expr is TUnaryExpr then
if (Expr as TUnaryExpr).Op.Typ in [ttNot, ttQuestion] then
Error((Expr as TUnaryExpr).Op,
Format(ErrNotAllowedInRange, [(Expr as TUnaryExpr).Op.Typ.toString]));
end;
begin
Result := ParseUnaryExpr;
if CurrentToken.Typ = ttDotDot then begin
CheckUnaryOp(Result);
Next; // skip ..
if CurrentToken.Typ = ttLT then begin // ..<
Exclude := True;
Next; // skip <
end;
UpperBound := ParseUnaryExpr;
CheckUnaryOp(UpperBound);
if Exclude then begin
Minus := TToken.Create(ttMin, '-', Null, 0, 0);
One := TConstExpr.Create(1, TToken.Create(ttNumber, '1', 1, 0, 0));
UpperBound := TBinaryExpr.Create(UpperBound, Minus, One);
end;
// build call to Range(Lower, Upper)
Range := TCallExpr.Create(TVariable.Create(MakeID('Range')), Nil);
Range.AddArgument(Result, Nil);
Range.AddArgument(UpperBound, Nil);
Result := Range;
end;
end;
function TParser.ParseUnaryExpr: TExpr;
var
Op: TToken;
begin
if CurrentToken.Typ in [ttPlus, ttMin, ttNot, ttQuestion] then begin
Op := CurrentToken;
Next;
Result := TUnaryExpr.Create(Op, ParseUnaryExpr());
end
else
Result := ParseCallExpr;
end;
function TParser.ParseCallExpr: TExpr;
var
Token: TToken;
begin
Token := CurrentToken;
Result := ParseFactor;
while CurrentToken.Typ in [ttDot, ttOpenParen, ttOpenBrack] do
case CurrentToken.Typ of
ttDot: begin
Next; // skip .
Result := TGetExpr.Create(Result, ParseFactor, Token);
end;
ttOpenParen: Result := ParseCallArgs(Result);
ttOpenBrack: begin
Next; // skip [
Result := TIndexedExpr.Create(Result, ParseExpr);
Expect(ttCloseBrack);
end;
end;
end;
function TParser.ParseCallArgs(Callee: TExpr): TExpr;
var
CallExpr: TCallExpr;
Token: TToken;
Signature: TExpr;
ParamNames: String = '';
function ParseArgument: String;
var
Expr: TExpr;
Ident: TIdent = Nil;
begin
Result := '';
Expr := ParseExpr;
if CurrentToken.Typ = ttColon then begin
Ident := TVariable(Expr).Ident; // ExtIdent parsed as Expr
Result := '#' + Ident.Text;
Next; // skip :
Expr := ParseExpr;
end;
CallExpr.AddArgument(Expr, Ident);
end;
begin
Token := CurrentToken;
Next; // skip (
CallExpr := TCallExpr.Create(Callee, Token);
if CurrentToken.Typ <> ttCloseParen then begin
ParamNames := ParseArgument;
while CurrentToken.Typ = ttComma do begin
Next; // skip ,
ParamNames += ParseArgument;
end;
end;
if ParamNames <> '' then begin
if Callee is TVariable then with Callee as TVariable do begin
Signature := TVariable.Create(TIdent.Create(Ident.Token.Copy));
TVariable(Signature).Ident.Text := Ident.Text + ParamNames;
end
else if Callee is TGetExpr then with Callee as TGetExpr do begin
Signature := TGetExpr.Create(Instance, TVariable.Create(
TIdent.Create(TVariable(Member).Ident.Token.Copy)), Token.Copy);
TVariable(TGetExpr(Signature).Member).Ident.Text :=
TVariable(Member).Ident.Text + ParamNames;
end
else if Callee is TInheritedExpr then with Callee as TInheritedExpr do begin
Signature := TInheritedExpr.Create(Variable, TVariable.Create(
TIdent.Create(TVariable(Method).Ident.Token.Copy)));
TVariable(TInheritedExpr(Signature).Method).Ident.Text :=
TVariable(Method).Ident.Text + ParamNames;
end
end
else Signature := Callee;
CallExpr.Signature := Signature;
Expect(ttCloseParen);
Result := CallExpr;
end;
function TParser.ParseIfExpr: TExpr;
var
Condition, TrueExpr, FalseExpr: TExpr;
Token: TToken;
begin
Token := CurrentToken;
Next; // skip 'if'
Condition := ParseExpr;
Expect(ttThen);
TrueExpr := ParseExpr;
Expect(ttElse);
FalseExpr := ParseExpr;
Result := TIfExpr.Create(Condition, TrueExpr, FalseExpr, Token);
end;
function TParser.ParseMatchExpr: TExpr;
var
Token: TToken;
Value, Expr: TExpr;
MatchExpr: TMatchExpr;
Values: TExprList;
begin
Token := CurrentToken;
Next; // skip 'match'
MatchExpr := TMatchExpr.Create(ParseExpr, Token);
Expect(ttIf); // one 'if' is mandatory
Values := ParseExprList;
Expect(ttThen);
Expr := ParseExpr;
for Value in Values do
MatchExpr.AddLimb(Value, Expr);
while CurrentToken.Typ = ttIf do begin
Next; // skip if
Values := ParseExprList;
Expect(ttThen);
Expr := ParseExpr;
for Value in Values do
MatchExpr.AddLimb(Value, Expr);
end;
Expect(ttElse); // else is mandatory
MatchExpr.ElseLimb := ParseExpr;
Result := MatchExpr;
end;
function TParser.ParseIdentifierExpr: TExpr;
var
Ident: TIdent;
FuncDecl: TFuncDecl;
begin
Ident := ParseIdent;
if CurrentToken.Typ = ttArrow then begin
FuncDecl := TFuncDecl.Create(Nil, CurrentToken);
FuncDecl.AddParam(Ident, Nil);
FuncDecl.Body := TBlock.Create(TNodeList.Create(), CurrentToken);
FuncDecl.Body.Nodes.Add(ParseReturnStmt);
Result := TFuncDeclExpr.Create(FuncDecl);
end
else Result := TVariable.Create(Ident);
end;
function TParser.ParseParenExpr: TExpr;
var
Expr: TExpr;
ExprList: TExprList;
FuncDecl: TFuncDecl;
begin
Expect(ttOpenParen);
if CurrentToken.Typ <> ttCloseParen then begin
Expr := ParseExpr;
if CurrentToken.Typ = ttComma then begin // check for a list
ExprList := TExprList.Create();
ExprList.Add(Expr);
while CurrentToken.Typ = ttComma do begin
Next; // skip ,
ExprList.Add(ParseExpr);
end;
Expect(ttCloseParen);
if CurrentToken.Typ = ttArrow then begin // func: ExprList contains params
FuncDecl := TFuncDecl.Create(Nil, CurrentToken);
for Expr in ExprList do
FuncDecl.AddParam((Expr as TVariable).Ident, Nil);
FuncDecl.Body := TBlock.Create(TNodeList.Create(), CurrentToken);
FuncDecl.Body.Nodes.Add(ParseReturnStmt);
Result := TFuncDeclExpr.Create(FuncDecl);
end
else // must be a tuple expr
Result := TTupleExpr.Create(ExprList, CurrentToken);
end
else begin
Result := Expr; // it’s a regular parenthesised expression
Expect(ttCloseParen);
end;
end
else begin
Next; // skip )
if CurrentToken.Typ = ttArrow then begin // func: zero params
FuncDecl := TFuncDecl.Create(Nil, CurrentToken);
FuncDecl.Body := TBlock.Create(TNodeList.Create(), CurrentToken);
FuncDecl.Body.Nodes.Add(ParseReturnStmt);
Result := TFuncDeclExpr.Create(FuncDecl);
end
else // empty tuple
Result := TTupleExpr.Create(TExprList.Create(), CurrentToken);
end;
end;
function TParser.ParseSelfExpr: TExpr;
var
Variable: TVariable;
begin
Variable := TVariable.Create(TIdent.Create(CurrentToken));
Next; // skip self
Result := TSelfExpr.Create(Variable);
end;
function TParser.ParseInheritedExpr: TExpr;
var
Variable, Method: TVariable;
begin
Variable := TVariable.Create(TIdent.Create(CurrentToken));
Next; // skip inherited
if CurrentToken.Typ in [ttIdentifier, ttInit] then begin
Method := TVariable.Create(TIdent.Create(CurrentToken));
Next; // skip method name
end
else if CurrentToken.Typ = ttOpenParen then with CurrentToken do
Method := TVariable.Create(TIdent.Create(TToken.Create(
ttIdentifier, 'init', Null, Line, Col, FileIndex)))
else
Error(CurrentToken, ErrIncorrectInherit);
Result := TInheritedExpr.Create(Variable, Method);
end;
function TParser.ParseArrayDeclExpr(FirstExpr: TExpr): TExpr;
var
ArrayDecl: TArrayDecl;
begin
ArrayDecl := TArrayDecl.Create(Nil, TDeclList.Create(false), CurrentToken);
ArrayDecl.AddElement(FirstExpr);
while CurrentToken.Typ = ttComma do begin
Next; // skip ,
ArrayDecl.AddElement(ParseExpr);
end;
Result := TArrayDeclExpr.Create(ArrayDecl);
end;
function TParser.ParseDictDeclExpr(KeyExpr: TExpr): TExpr;
var
DictDecl: TDictDecl;
Key: TExpr;
begin
DictDecl := TDictDecl.Create(Nil, TKeyValueList.Create,
TDeclList.Create(false), CurrentToken);
Expect(ttColon);
DictDecl.AddElement(KeyExpr, ParseExpr);
while CurrentToken.Typ = ttComma do begin
Next; // skip ,
Key := ParseExpr;
Expect(ttColon);
DictDecl.AddElement(Key, ParseExpr);
end;
Result := TDictDeclExpr.Create(DictDecl);
end;
function TParser.ParseBracketExpr: TExpr;
var
Expr: TExpr;
ArrayDecl: TArrayDecl;
DictDecl: TDictDecl;
begin
Next; // skip [
case CurrentToken.Typ of
ttCloseBrack: begin // an empty array
ArrayDecl := TArrayDecl.Create(Nil, TDeclList.Create(false), CurrentToken);
Result := TArrayDeclExpr.Create(ArrayDecl);
end;
ttColon: begin // an empty dictionary
DictDecl := TDictDecl.Create(Nil, TKeyValueList.Create,
TDeclList.Create(false), CurrentToken);
Result := TDictDeclExpr.Create(DictDecl);
Next; // skip :
end
else // a filled array or dictionary
begin
Expr := ParseExpr; // parse the first expr
if CurrentToken.Typ = ttColon then // then check for ‘:’
Result := ParseDictDeclExpr(Expr) // a dictionary; pass the first expr
else
Result := ParseArrayDeclExpr(Expr); // an array; pass the first expr
end;
end;
Expect(ttCloseBrack); // final closing bracket
end;
function TParser.ParseSetBuilderExpr: TExpr;
var
OutputExpr, InputSet: TExpr;
PredicateExpr: TExpr = Nil;
Ident: TIdent;
OutputFuncExpr, PredicateFuncExpr: TFuncDeclExpr;
ListBuilder: TCallExpr;
begin
// first step: parse all elements of set builder expression
Next; // skip '{'
OutputExpr := ParseExpr;
Expect(ttFor);
Ident := ParseIdent;
Expect(ttIn);
InputSet := ParseExpr;
if CurrentToken.Typ = ttWhere then begin
Next; // skip where
PredicateExpr := ParseExpr;
end;
Expect(ttCloseBrace);
// second step: create the functions
OutputFuncExpr := TFuncDeclExpr.Create(TFuncDecl.Create(Nil, Nil));
with OutputFuncExpr do begin
FuncDecl.AddParam(Ident, Nil);
FuncDecl.Body := TBlock.Create(TNodeList.Create(), Nil);
FuncDecl.Body.Nodes.Add(TReturnStmt.Create(OutputExpr, Nil));
end;
if Assigned(PredicateExpr) then begin
PredicateFuncExpr := TFuncDeclExpr.Create(TFuncDecl.Create(Nil, Nil));
with PredicateFuncExpr do begin
FuncDecl.AddParam(Ident, Nil);
FuncDecl.Body := TBlock.Create(TNodeList.Create(), Nil);
FuncDecl.Body.Nodes.Add(TReturnStmt.Create(PredicateExpr, Nil));
end;
end;
// third step: create call to func listBuilder(transform, input, include)
ListBuilder := TCallExpr.Create(TVariable.Create(MakeID('listBuilder')), Nil);
ListBuilder.AddArgument(OutputFuncExpr, Nil);
ListBuilder.AddArgument(InputSet, Nil);
if Assigned(PredicateExpr) then
ListBuilder.AddArgument(PredicateFuncExpr, Nil)
else
ListBuilder.AddArgument(TConstExpr.Create(Null, Nil), Nil);
Result := ListBuilder;
end;
function TParser.ParseInterpolatedExpr: TExpr;
var
ExprList: TExprList;
Token: TToken;
begin
Token := CurrentToken;
ExprList := TExprList.Create();
while CurrentToken.Typ = ttInterpolated do begin
ExprList.Add(TConstExpr.Create(CurrentToken.Value, CurrentToken)); // Opening string
Next;
ExprList.Add(ParseExpr); // Interpolated expression
end;
if CurrentToken.Typ = ttString then
ExprList.Add(ParseFactor)
else
Error(CurrentToken, 'Expected end of string interpolation.');
Result := TInterpolatedExpr.Create(ExprList, Token);
end;
function TParser.ParseFactor: TExpr;
begin
case CurrentToken.Typ of
ttFunc: Result := TFuncDeclExpr.Create(ParseFuncDecl(ffAnonym) as TFuncDecl);
ttIf: Result := ParseIfExpr;
ttMatch: Result := ParseMatchExpr;
ttInherited: Result := ParseInheritedExpr;
ttSelf: Result := ParseSelfExpr;
ttIdentifier: Result := ParseIdentifierExpr;
ttFalse, ttTrue: begin
Result := TConstExpr.Create(CurrentToken.Typ = ttTrue, CurrentToken);
Next;
end;
ttNull: begin
Result := TConstExpr.Create(Null, CurrentToken); // Null is variant enum
Next;
end;
ttNumber, ttString, ttChar: begin
Result := TConstExpr.Create(CurrentToken.Value, CurrentToken);
Next;
end;
ttInterpolated: Result := ParseInterpolatedExpr;
ttOpenParen: Result := ParseParenExpr;
ttOpenBrace: Result := ParseSetBuilderExpr;
ttOpenBrack: Result := ParseBracketExpr; // [ array or dictionary
else begin
Result := TExpr.Create(CurrentToken);
Error(CurrentToken,Format(ErrUnexpectedToken, [CurrentToken.toString]));
end;
end;
end;
const
StmtStartSet: TTokenTypSet = [ttIf, ttWhile, ttRepeat, ttFor, ttSwitch,
ttReturn, ttEnsure, ttPrint, ttInherited , ttSelf, ttUse, ttBreak,
ttContinue, ttIdentifier];
function TParser.ParseStmt: TStmt;
begin
case CurrentToken.Typ of
ttIf: Result := ParseIfStmt;
ttWhile: Result := ParseWhileStmt;
ttRepeat: Result := ParseRepeatStmt;
ttFor: Result := ParseForStmt;
ttReturn: Result := ParseReturnStmt;
ttSwitch: Result := ParseSwitchStmt;
ttEnsure: Result := ParseEnsureStmt;
ttPrint: Result := ParsePrintStmt;
ttUse: Result := ParseUseStmt;
ttBreak: Result := ParseBreakStmt;
ttContinue: Result := ParseContinueStmt;
else
Result := ParseAssignStmt;
end;
end;
function TParser.ParsePrintStmt: TStmt;
var
ExprList: TExprList;
Token: TToken;
Terminator: TExpr;
SawTerminator: Boolean = False;
procedure ParseItem;
var
PrintPretty: TIdent;
begin
if (CurrentToken.Typ = ttIdentifier) and (Peek.Typ = ttColon) then begin
PrintPretty := ParseIdent;
if PrintPretty.Text = 'terminator' then begin
if SawTerminator then
Error(PrintPretty.Token, ErrDuplicateTerminator);
SawTerminator := True;
Next; // skip :
Terminator := ParseExpr;
end
else
Error(PrintPretty.Token,
Format(ErrUnexpectedAttribute, [PrintPretty.Text]));
end
else ExprList.Add(ParseExpr);
end;
begin
Terminator := TConstExpr.Create(LineEnding, CurrentToken);
Token := CurrentToken;
Next; // skip print
Expect(ttOpenParen);
ExprList := TExprList.Create(false);
if CurrentToken.Typ <> ttCloseParen then begin
ParseItem;
while CurrentToken.Typ = ttComma do begin
Next; // skip ,
ParseItem;
end;
end;
Expect(ttCloseParen);
Result := TPrintStmt.Create(ExprList, Terminator, Token);
end;
const
AssignSet: TTokenTypSet =
[ttPlusIs, ttMinIs, ttMulIs, ttDivIs, ttRemIs, ttConcatIs, ttAssign];
function TParser.ParseAssignStmt: TStmt;
var
Token, Op: TToken;
Left, Right: TExpr;
begin
Token := CurrentToken;
Left := ParseExpr;
if CurrentToken.Typ in AssignSet then begin
Op := CurrentToken;
Next; // skip assign token
Right := ParseExpr;
if Left is TVariable then
Result := TAssignStmt.Create(Left as TVariable, Op, Right)
else if Left is TGetExpr then
Result := TSetStmt.Create(Left as TGetExpr, Op, Right)
else if Left is TIndexedExpr then
Result := TIndexedExprStmt.Create(Left as TIndexedExpr, Op, Right)
else
Error(Token, ErrInvalidAssignTarget);
end
else if Left is TCallExpr then
Result := TCallExprStmt.Create(Left as TCallExpr, Token)
else
Error(CurrentToken, ErrExpectedAssignOpFunc);
end;
function TParser.ParseIfStmt: TStmt;
var
Token, VarToken: TToken;
VarDecl: TVarDecl = Nil;
Condition: TExpr;
ThenPart: TBlock;
ElsePart: TBlock = Nil;
ElseIfExprs: TExprList = Nil;
ElseIfParts: TBlocks = Nil;
begin
Token := CurrentToken;
Next; // skip if
if CurrentToken.Typ in [ttVar, ttLet] then begin
VarToken := CurrentToken;
Next; // skip var or let
VarDecl := ParseVarDecl(VarToken.Typ = ttVar) as TVarDecl;
Expect(ttWhere);
end;
Condition := ParseExpr;
Expect(ttThen);
ThenPart := ParseBlock;
if CurrentToken.Typ = ttElseif then begin
ElseIfExprs := TExprList.Create();
ElseIfParts := TBlocks.Create();
repeat
Next; // skip elseif
ElseIfExprs.Add(ParseExpr);
Expect(ttThen);
ElseIfParts.Add(ParseBlock);
until CurrentToken.Typ <> ttElseIf;
end;
if CurrentToken.Typ = ttElse then begin
Next; // skip else
ElsePart := ParseBlock;
end;
Expect(ttEnd);
Result := TIfStmt.Create(VarDecl, Condition, ElseIfExprs,
ThenPart, ElsePart, ElseIfParts, Token);
end;
function TParser.ParseWhileStmt: TStmt;
var
Token: TToken;
VarDecl: TVarDecl = Nil;
Condition: TExpr;
Block: TBlock;
begin
try
Inc(LoopDepth);
Token := CurrentToken;
Next; // skip while
if CurrentToken.Typ = ttVar then begin
Next;
VarDecl := ParseVarDecl(True) as TVarDecl;
Expect(ttWhere);
end;
Condition := ParseExpr;
Expect(ttDo);
Block := ParseBlock;
Expect(ttEnd);
Result := TWhileStmt.Create(VarDecl, Condition, Block, Token);
finally
Dec(LoopDepth);
end;
end;
function TParser.ParseRepeatStmt: TStmt;
var
Token: TToken;
Condition: TExpr;
Block: TBlock;
begin
Token := CurrentToken;
Next; // skip repeat
Block := ParseBlock;
Expect(ttUntil);
Condition := ParseExpr;
Result := TRepeatStmt.Create(Condition, Block, Token);
end;
function TParser.ParseForStmt: TStmt;
var
Token: TToken;
VarDecl: TVarDecl;
Condition: TExpr;
Iterator: TStmt;
Block: TBlock;
begin
try
Inc(LoopDepth);
Token := CurrentToken;
Next; // skip for
if CurrentToken.Typ = ttEach then
Result := ParseForEachStmt
else begin
Expect(ttVar);
VarDecl := ParseVarDecl(True) as TVarDecl;
Expect(ttWhere);
Condition := ParseExpr;
Expect(ttComma);
Iterator := ParseAssignStmt;
Expect(ttDo);
Block := ParseBlock;
Block.Nodes.Add(Iterator);
Result := TWhileStmt.Create(VarDecl, Condition, Block, Token);
end;
Expect(ttEnd);
finally
Dec(LoopDepth);
end;
end;
function TParser.ParseForEachStmt: TStmt;
var
Condition: TGetExpr;
IterDecl, VarDecl: TVarDecl;
Block: TBlock;
LoopIdent: TIdent;
ListExpr: TExpr;
WhereExpr: TExpr = Nil;
IfStmt: TIfStmt = Nil;
begin
Next; // skip each
// parse the for-loop variable
LoopIdent := ParseIdent;
Expect(ttIn);
// parse list type expression
ListExpr := ParseExpr;
if CurrentToken.Typ = ttWhere then begin
Next;
WhereExpr := ParseExpr;
end;
Expect(ttDo);
// create initial iterator vardecl: var iterator := ListExpr.iterator
IterDecl := TVarDecl.Create(MakeID('iterator'),
TGetExpr.Create(ListExpr, TVariable.Create(MakeID('iterator')), Nil), Nil);
// build condition: iterator.hasNext
Condition := TGetExpr.Create(
TVariable.Create(MakeID('iterator')), TVariable.Create(MakeID('hasNext')), Nil);
// build var LoopIdent := iterator.next
VarDecl := TVarDecl.Create(LoopIdent,
TGetExpr.Create(TVariable.Create(MakeID('iterator')), TVariable.Create(MakeID('next')), Nil), Nil);
// build where-expression into if-statement
if Assigned(WhereExpr) then begin
IfStmt := TIfStmt.Create(Nil, WhereExpr, Nil,
TBlock.Create(TNodeList.Create(), Nil), Nil, Nil, Nil);
IfStmt.ThenPart := ParseBlock;
Block := TBlock.Create(TNodeList.Create(), Nil);
Block.Nodes.Add(VarDecl);
Block.Nodes.Add(IfStmt);
end else begin
// parse the block
Block := ParseBlock;
Block.Nodes.Insert(0, VarDecl); // insert VarDecl at start of block
end;
Result := TWhileStmt.Create(IterDecl, Condition, Block, Nil);
end;
function TParser.ParseEnsureStmt: TStmt;
var
Token, VarToken: TToken;
VarDecl: TVarDecl = Nil;
Condition: TExpr;
ElsePart: TBlock;
begin
Token := CurrentToken;
Next; // skip ensure
if CurrentToken.Typ in [ttVar, ttLet] then begin
VarToken := CurrentToken;
Next;
VarDecl := ParseVarDecl(VarToken.Typ = ttVar) as TVarDecl;
Expect(ttWhere);
end;
Condition := ParseExpr;
Expect(ttElse);
ElsePart := ParseBlock;
Expect(ttEnd);
Result := TEnsureStmt.Create(VarDecl, Condition, ElsePart, Token);
end;
function TParser.ParseSwitchStmt: TStmt;