-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.ts
More file actions
1277 lines (1087 loc) Β· 30.7 KB
/
Copy pathparser.ts
File metadata and controls
1277 lines (1087 loc) Β· 30.7 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
//#if _MATBAS_BUILD == 'debug'
import { Span } from './debug';
//#else
//#unset _DEBUG_SHOW_TREE
//#endif
//#if _MATBAS_BUILD == 'debug'
import { startSpan } from './debug';
//#endif
//#if _DEBUG_SHOW_TREE
import { showTree } from './debug';
//#endif
import { errorType } from './errors';
import {
SyntaxError,
ParseError,
SyntaxWarning,
ParseWarning,
sortParseError,
} from './exceptions';
import { runtimeMethod } from './faults';
import { Scanner, KEYWORDS } from './scanner';
import { Token, TokenKind } from './tokens';
import { Source } from './ast/source';
import {
Expr,
Binary,
Logical,
Unary,
Call,
Group,
Variable,
Lambda,
IntLiteral,
RealLiteral,
BoolLiteral,
StringLiteral,
ShellLiteral,
PromptLiteral,
NilLiteral,
} from './ast/expr';
import {
Instr,
Assign,
Print,
Expression,
Rem,
New,
Load,
List,
Renum,
Save,
Run,
End,
Exit,
Let,
ShortIf,
If,
Else,
ElseIf,
EndIf,
For,
Onward,
Next,
While,
EndWhile,
Repeat,
Until,
Def,
ShortDef,
Return,
EndDef,
Command,
} from './ast/instr';
import { Cmd, Line, Input, Program } from './ast';
import { sortLines } from './ast/util';
export type ParseResult<T> = [T, ParseWarning | null];
export type Row = Line | Cmd;
export abstract class DefKind<T> {
abstract create(name: Token | null, params: Token[], body: Expr | null): T;
}
export class FunctionKind extends DefKind<Instr> {
create(name: Token | null, params: Token[], body: Expr | null): Instr {
if (body) {
return new ShortDef(name!, params, body);
}
return new Def(name!, params);
}
}
export class LambdaKind extends DefKind<Expr> {
create(name: Token | null, params: Token[], body: Expr | null): Expr {
return new Lambda(name, params, body!);
}
}
const FUNCTION = new FunctionKind();
const LAMBDA = new LambdaKind();
// The alternative to using exceptions is to set a panicMode flag to ignore
// emitted errors until we can synchronize. This might be worth trying out
// later.
@errorType('Synchronize')
class Synchronize extends Error {
constructor() {
super('Synchronize');
Object.setPrototypeOf(this, new.target.prototype);
}
}
export class Parser {
private filename: string = '<unknown>';
private scanner: Scanner;
private previous: Token | null;
private current: Token;
private leadingWs: string = '';
private next: Token;
private trailingWs: string = '';
private lineErrors: Array<SyntaxError | SyntaxWarning> = [];
private errors: Array<SyntaxError | SyntaxWarning> = [];
private isError: boolean = false;
private isWarning: boolean = false;
private isProgram: boolean = false;
private isLine: boolean = false;
private lineNo: number | null = null;
private cmdNo: number = 0;
private line: Source = Source.empty();
private isShortIf: boolean = false;
constructor() {}
init(source: string, filename: string, isProgram: boolean) {
this.filename = filename;
this.scanner = new Scanner(source, filename);
this.previous = null;
const [ws1, current] = this.nextToken();
this.current = current;
const [ws2, next] = this.nextToken();
this.leadingWs = ws1;
this.next = next;
this.trailingWs = ws2;
this.lineErrors = [];
this.errors = [];
this.isError = false;
this.isWarning = false;
this.isProgram = isProgram;
this.isLine = false;
this.lineNo = null;
this.line = new Source(ws1, '', '', this.current.text);
this.isShortIf = false;
}
/**
* Parse the source as input, returning a list of lines and commands.
*
* @param source The source code.
* @returns A list of lines and commands.
*/
@runtimeMethod
public parseInput(source: string): ParseResult<Input> {
//#if _MATBAS_BUILD == 'debug'
return startSpan('Parser#parseInput', (_: Span): ParseResult<Input> => {
//#endif
this.init(source, '<input>', false);
const result = new Input(this.rows());
// NOTE: errors and warnings are *almost* sorted, but there are
// certain cases where an error is only known after its expression is
// parsed - for example, parameter length validation in params
// parsing.
let warning: ParseWarning | null = null;
if (this.isError) {
const err = new ParseError(this.errors);
sortParseError(err, ['row', 'offsetStart']);
throw err;
} else if (this.isWarning) {
const warnings = this.errors as unknown as SyntaxWarning[];
warning = new ParseWarning(warnings);
sortParseError(warning, ['row', 'offsetStart']);
}
//#if _DEBUG_SHOW_TREE
showTree(result);
//#endif
return [result, warning];
//#if _MATBAS_BUILD == 'debug'
});
//#endif
}
/**
* Parse the source as a program, returning a Program.
*
* @param source The source code.
* @param filename The source filename.
* @returns A Program.
*/
@runtimeMethod
public parseProgram(source: string, filename: string): ParseResult<Program> {
//#if _MATBAS_BUILD == 'debug'
return startSpan('Parser#parseProgram', (_: Span): ParseResult<Program> => {
//#endif
this.init(source, filename, true);
const result = this.rows();
sortLines(result as Line[]);
const program = new Program(this.filename, result as Line[]);
let warning: ParseWarning | null = null;
if (this.isError) {
throw new ParseError(this.errors);
} else if (this.isWarning) {
const warnings = this.errors as unknown as SyntaxWarning[];
warning = new ParseWarning(warnings);
}
//#if _DEBUG_SHOW_TREE
showTree(program);
//#endif
return [program, warning];
//#if _MATBAS_BUILD == 'debug'
});
//#endif
}
//
// Core parse methods
//
private match(...kinds: TokenKind[]): boolean {
for (const kind of kinds) {
if (this.check(kind)) {
this.advance();
return true;
}
}
return false;
}
private check(kind: TokenKind): boolean {
if (this.done) {
return kind === TokenKind.Eof;
}
return this.current.kind === kind;
}
private checkNext(kind: TokenKind): boolean {
if (this.done) {
return kind === TokenKind.Eof;
}
return this.next.kind === kind;
}
private nextToken(ws: string = ''): [string, Token] {
const token = this.scanner.nextToken();
if (token.kind === TokenKind.Whitespace) {
return this.nextToken(ws + token.text);
}
return [ws, token];
}
private advance(): Token {
this.previous = this.current;
this.current = this.next;
this.line.source += this.trailingWs + this.current.text;
const [ws, next] = this.nextToken();
this.leadingWs = this.trailingWs;
this.trailingWs = ws;
this.next = next;
if (this.current.kind === TokenKind.Illegal) {
this.syntaxError(this.current, `Illegal token ${this.current.text}`);
}
return this.previous as Token;
}
private get done(): boolean {
return this.current.kind == TokenKind.Eof;
}
private consume(kind: TokenKind, message: string): Token {
if (this.check(kind)) return this.advance() as Token;
this.syntaxError(this.current, message);
}
//
// Errors and Warnings
//
private syntaxError(token: Token, message: string): never {
const exc = new SyntaxError(message, {
filename: this.filename,
row: token.row,
isLine: this.isLine,
lineNo: this.lineNo,
cmdNo: this.isLine ? null : this.cmdNo,
offsetStart: token.offsetStart,
offsetEnd: token.offsetEnd,
source: Source.unknown(),
});
this.isError = true;
this.lineErrors.push(exc);
throw new Synchronize();
}
private syntaxWarning(token: Token, message: string): void {
const exc = new SyntaxWarning(message, {
filename: this.filename,
row: token.row,
isLine: this.isLine,
lineNo: this.lineNo,
cmdNo: this.isLine ? null : this.cmdNo,
offsetStart: token.offsetStart,
offsetEnd: token.offsetEnd,
source: Source.unknown(),
});
this.isWarning = true;
this.lineErrors.push(exc);
}
private rows(): Row[] {
const rows: Row[] = [];
while (!this.done) {
const parsed = this.row();
if (parsed) {
rows.push(parsed);
}
}
return rows;
}
private row(): Row | null {
const rowNo = this.current.row;
let cmds: Instr[];
let source: Source;
try {
this.lineNumber();
cmds = this.instructions();
source = this.rowEnding();
} catch (err) {
if (err instanceof Synchronize) {
this.syncNextRow();
return null;
}
throw err;
}
if (this.lineNo !== null) {
return new Line(this.lineNo, rowNo, source, cmds);
}
this.cmdNo += 10;
return new Cmd(this.cmdNo, rowNo, source, cmds);
}
private lineNumber(): void {
const prevLineNo = this.lineNo;
if (this.match(TokenKind.DecimalLiteral)) {
this.lineNo = this.previous!.value as number;
this.line.lineNo = this.previous!.text;
this.line.separatingWs = this.leadingWs;
this.line.source = this.current.text;
this.isLine = true;
} else if (this.isProgram) {
this.syntaxError(this.current, 'Expected line number');
} else {
this.lineNo = null;
this.isLine = false;
}
if (this.lineNo !== null) {
if (this.lineNo % 10) {
this.syntaxWarning(
this.previous!,
'Line numbers should be in factors of 10',
);
}
if (this.isProgram && prevLineNo !== null) {
if (this.lineNo <= prevLineNo) {
this.syntaxWarning(this.previous!, 'Line numbers should be in order');
}
}
}
}
private rowEnding(): Source {
const line = this.line.clone();
if (line.source.endsWith('\n')) {
line.source = line.source.slice(0, -1);
}
for (const error of this.lineErrors) {
error.source = line;
this.errors.push(error);
}
this.lineErrors = [];
if (!this.match(TokenKind.LineEnding)) {
const token = this.current;
this.consume(
TokenKind.Eof,
`Unexpected token ${token.text.length ? token.text : token.kind}`,
);
}
const nextLine = new Source(this.leadingWs, '', '', this.current.text);
this.line = nextLine;
this.isLine = false;
return line;
}
private syncNextInstr() {
// Remarks can be handled in the next attempt at parsing a command
while (!this.isInstrBoundary) {
// TODO: Illegal, UnterminatedString
this.advance();
}
}
private syncNextRow(): void {
while (
![TokenKind.LineEnding, TokenKind.Eof, TokenKind.Rem].includes(
this.current.kind,
)
) {
// TODO: Illegal, UnterminatedString
this.advance();
}
this.rowEnding();
}
private get isLineEnding(): boolean {
return this.done || this.current.kind === TokenKind.LineEnding;
}
private get isInstrBoundary(): boolean {
return (
this.isLineEnding ||
[TokenKind.Colon, TokenKind.Eof, TokenKind.Rem].reduce(
(check, tok) => check || this.check(tok),
false,
)
);
}
//
// Instruction parsing
//
private instructions(): Instr[] {
if (this.isLineEnding) {
return [];
}
let instr: Instr | null = this.instruction();
const instrs: Instr[] = instr ? [instr] : [];
// Less strict than isInstrBoundary, since that check includes end-of-input
// scenarios
while (this.match(TokenKind.Colon) || this.check(TokenKind.Rem)) {
try {
instr = this.instruction();
if (instr) {
instrs.push(instr);
}
} catch (err) {
if (err instanceof Synchronize) {
this.syncNextInstr();
}
throw err;
}
}
return instrs;
}
private instruction(): Instr | null {
const { offsetStart } = this.current;
let instr: Instr;
// Remarks are treated like commands - the scanner handles the fact
// that they include all text to the end of the line
if (this.match(TokenKind.Rem)) {
instr = new Rem(this.previous!.value as string);
} else if (this.match(TokenKind.Semicolon)) {
instr = new Rem('');
} else if (this.match(TokenKind.Print)) {
instr = this.print();
// TODO: TokenKind.ShellToken (or TokenKind.StringLiteral)
} else if (this.match(TokenKind.New)) {
instr = this.new();
} else if (this.match(TokenKind.Load)) {
instr = this.load();
} else if (this.match(TokenKind.List)) {
instr = this.list();
} else if (this.match(TokenKind.Renum)) {
instr = this.renum();
} else if (this.match(TokenKind.Save)) {
instr = this.save();
} else if (this.match(TokenKind.Run)) {
instr = this.run();
} else if (this.match(TokenKind.End)) {
instr = this.end();
} else if (this.match(TokenKind.Exit)) {
instr = this.exit();
} else if (this.match(TokenKind.Let)) {
instr = this.let();
} else if (this.match(TokenKind.If)) {
instr = this.if_();
} else if (this.match(TokenKind.Else)) {
instr = this.else_();
} else if (this.match(TokenKind.EndIf)) {
instr = this.endIf();
} else if (this.match(TokenKind.For)) {
instr = this.for_();
} else if (this.match(TokenKind.Onward)) {
instr = this.onward();
} else if (this.match(TokenKind.Next)) {
instr = this.endFor();
} else if (this.match(TokenKind.While)) {
instr = this.while_();
} else if (this.match(TokenKind.EndWhile)) {
instr = this.endWhile();
} else if (this.match(TokenKind.Repeat)) {
instr = this.repeat();
} else if (this.match(TokenKind.Until)) {
instr = this.until();
} else if (this.match(TokenKind.Def)) {
instr = this.def(FUNCTION);
} else if (this.match(TokenKind.Return)) {
instr = this.return();
} else if (this.match(TokenKind.EndDef)) {
instr = this.endDef();
} else {
const assign = this.assign();
if (assign) {
instr = assign;
} else if (this.checkExpressionStatementStart()) {
instr = this.expressionStatement();
} else {
instr = this.command();
}
}
const { offsetEnd } = this.previous!;
instr.offsetStart = offsetStart;
instr.offsetEnd = offsetEnd;
return instr;
}
// TODO: What's the syntax of print? lol
private print(): Instr {
return new Print(this.expression());
}
private new(): Instr {
return new New(this.optionalExpression());
}
private load(): Instr {
const params = this.commandParams();
return new Load(params);
}
private list(): Instr {
if (this.match(TokenKind.DecimalLiteral)) {
const lineStart = this.previous!.value as number;
if (this.match(TokenKind.Minus)) {
const lineEnd = this.consume(
TokenKind.DecimalLiteral,
'Expected line end',
).value as number;
return new List(lineStart, lineEnd);
}
return new List(lineStart, null);
}
return new List(null, null);
}
private renum(): Instr {
return new Renum();
}
private save(): Instr {
return new Save(this.optionalExpression());
}
private run(): Instr {
return new Run();
}
private end(): Instr {
// TODO: Should end take an exit code?
return new End();
}
private exit(): Instr {
const expr = this.optionalExpression();
if (expr) {
return new Exit(expr);
}
return new Exit(null);
}
private expressionStatement(): Instr {
return new Expression(this.expression());
}
//
// Check, match or consume identifiers. Type checking will occur in the
// compiler.
//
private checkIdent(): boolean {
return [
TokenKind.Ident,
TokenKind.IntIdent,
TokenKind.RealIdent,
TokenKind.BoolIdent,
TokenKind.StringIdent,
].reduce((check, tok) => check || this.check(tok), false);
}
private matchIdent(): boolean {
return this.match(
TokenKind.Ident,
TokenKind.IntIdent,
TokenKind.RealIdent,
TokenKind.BoolIdent,
TokenKind.StringIdent,
);
}
private consumeIdent(message: string): Token {
if (this.checkIdent()) return this.advance() as Token;
this.syntaxError(this.current, message);
}
// NOTE: Corresponds to parsing declaration()/varDeclaration() in clox.
private let(): Instr {
// NOTE: Corresponds to `global` in global-only clox
let variable: Variable;
if (this.matchIdent()) {
// NOTE: Roughly corresponds to parseVariable, though see also
// emitIdent in compiler/base.ts
variable = this.variable();
} else {
this.syntaxError(this.current, 'Expected variable name');
}
let value: Expr | null = null;
if (this.match(TokenKind.Eq)) {
value = this.expression();
}
return new Let(variable, value);
}
private assign(): Instr | null {
// We can't match here because we need to check the *next* token
// before advancing...
if (this.checkIdent() && this.checkNext(TokenKind.Eq)) {
// ...and so we advance here.
this.advance();
const variable = this.variable();
this.consume(TokenKind.Eq, 'Expected =');
const value = this.expression();
return new Assign(variable, value);
}
return null;
}
private if_(): Instr {
const condition = this.ifCondition();
// A bare "if" with a multi-line block
if (!this.isShortIf && this.isInstrBoundary) {
const if_ = new If(condition);
return if_;
}
return this.shortIf(condition);
}
private ifCondition(): Expr {
const condition = this.expression();
this.consume(TokenKind.Then, 'Expected then');
return condition;
}
private shortIf(condition: Expr): Instr {
const prevShortIf = this.isShortIf;
this.isShortIf = true;
const then: Instr[] = this.instructions();
let else_: Instr[] = [];
if (this.match(TokenKind.Else)) {
else_ = this.instructions();
}
this.consume(TokenKind.EndIf, "Expected 'endif' after 'if' instruction");
this.isShortIf = prevShortIf;
return new ShortIf(condition, then, else_);
}
private else_(): Instr {
if (this.isShortIf) {
this.syntaxError(this.previous!, "Unexpected 'else'");
}
if (this.match(TokenKind.If)) {
return this.elseIf();
}
return new Else();
}
private elseIf(): Instr {
return new ElseIf(this.ifCondition());
}
private endIf(): Instr {
if (this.isShortIf) {
this.syntaxError(this.previous!, "Unexpected 'endif'");
}
return new EndIf();
}
private for_(): Instr {
const assign = this.assign() as Assign;
if (!assign) {
this.syntaxError(this.previous!, 'Expected assignment');
}
this.consume(TokenKind.To, "Expected 'to'");
const stop = this.expression();
let step: Expr | null = null;
if (this.match(TokenKind.Step)) {
step = this.expression();
}
return new For(assign.variable, assign.value, stop, step);
}
private onward(): Instr {
return new Onward();
}
private endFor(): Instr {
return new Next();
}
private while_(): Instr {
const condition = this.expression();
return new While(condition);
}
private endWhile(): Instr {
return new EndWhile();
}
private repeat(): Instr {
return new Repeat();
}
private until(): Instr {
const condition = this.expression();
return new Until(condition);
}
private def<T>(kind: DefKind<T>): T {
const name = this.defName(kind);
const params = this.defParams(kind);
let body: Expr | null = null;
if (!this.isInstrBoundary) {
// Optional return
this.match(TokenKind.Return);
body = this.expression();
this.consume(TokenKind.EndDef, "Expected 'enddef' after function body");
}
return kind.create(name, params, body);
}
private requiresDefName(kind: DefKind<any>): boolean {
return kind instanceof FunctionKind;
}
private defName(kind: DefKind<any>): Token | null {
if (this.requiresDefName(kind)) {
return this.consumeIdent(`Expect ${kind} name`);
}
if (this.matchIdent()) {
return this.previous!;
}
return null;
}
private defParams(kind: DefKind<any>): Token[] {
this.consume(TokenKind.LParen, `Expect '(' after ${kind} name`);
const params: Token[] = [];
if (!this.check(TokenKind.RParen)) {
do {
params.push(this.consumeIdent('Expect parameter name'));
} while (this.match(TokenKind.Comma));
}
this.consume(TokenKind.RParen, "Expect ')' after parameters");
return params;
}
private return(): Instr {
const expr = this.optionalExpression();
return new Return(expr);
}
private endDef(): Instr {
return new EndDef();
}
private checkPrimaryStart(): boolean {
// A bare call
if (this.checkIdent() && this.checkNext(TokenKind.LParen)) {
return true;
}
return (
this.check(TokenKind.DecimalLiteral) ||
this.check(TokenKind.HexLiteral) ||
this.check(TokenKind.OctalLiteral) ||
this.check(TokenKind.BinaryLiteral) ||
this.check(TokenKind.RealLiteral) ||
this.check(TokenKind.TrueLiteral) ||
this.check(TokenKind.FalseLiteral) ||
this.check(TokenKind.StringLiteral) ||
this.check(TokenKind.NilLiteral) ||
this.check(TokenKind.IntIdent) ||
this.check(TokenKind.RealIdent) ||
this.check(TokenKind.BoolIdent) ||
this.check(TokenKind.StringIdent) ||
this.check(TokenKind.LParen)
);
}
private checkExpressionStatementStart(): boolean {
return (
this.checkPrimaryStart() ||
[...Object.values(KEYWORDS), TokenKind.Plus, TokenKind.Minus].reduce(
(check, tok) => this.check(tok) || check,
false,
)
);
}
private command(): Instr {
const cmd = this.commandParam();
if (!cmd) {
const token = this.current;
this.syntaxError(
token,
`Unexpected token ${token.text.length ? token.text : token.kind}`,
);
}
const params = this.commandParams();
return new Command(cmd, params);
}
private commandParams(): Expr[] {
const exprs: Expr[] = [];
let current = this.commandParam();
while (current) {
exprs.push(current);
current = this.commandParam();
}
return exprs;
}
private commandParam(): Expr | null {
// Parse literals and groups as expressions
if (this.checkPrimaryStart()) {
return this.primary();
}
return this.shellLiteral();
}
//
// Standard expression parsing
//
private optionalExpression(): Expr | null {
if (this.isInstrBoundary) {
return null;
}
return this.expression();
}
private expression(): Expr {
return this.or();
}
private infixOperator<E extends Expr>(
kinds: TokenKind[],
operand: () => Expr,
factory: (l: Expr, o: TokenKind, r: Expr) => E,
): Expr {
let expr: Expr = operand();
while (this.match(...kinds)) {
const op = this.previous!.kind;
const right = operand();
expr = factory(expr, op, right);
}
return expr;
}
private prefixOperator<E extends Expr>(
kinds: TokenKind[],
operand: () => Expr,
factory: (o: TokenKind, e: Expr) => E,
): Expr {
const unary = this.prefixOperator.bind(this, kinds, operand, factory);
if (this.match(...kinds)) {
const op = this.previous!.kind;
const right = unary();
return factory(op, right);
}
return operand();
}
private or(): Expr {
return this.infixOperator(
[TokenKind.Or],
this.and.bind(this),
(l, o, r) => new Logical(l, o, r),
);
}
private and(): Expr {
return this.infixOperator(
[TokenKind.And],
this.not.bind(this),
(l, o, r) => new Logical(l, o, r),
);
}
private not(): Expr {
return this.prefixOperator(
[TokenKind.Not],
this.equality.bind(this),
(o, e) => new Unary(o, e),
);
}