forked from msironi/expr-eval
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathparser-state.ts
More file actions
687 lines (580 loc) · 21.8 KB
/
Copy pathparser-state.ts
File metadata and controls
687 lines (580 loc) · 21.8 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
// cSpell:words TEOF TNUMBER TSTRING TCONST TPAREN TBRACKET TCOMMA TNAME TSEMICOLON TUNDEFINED TKEYWORD TBRACE
// cSpell:words ISCALAR IVAR IFUNCALL IEXPREVAL IMEMBER IARRAY IARROW
// cSpell:words IUNDEFINED ICASEMATCH ICASECOND IWHENCOND IWHENMATCH ICASEELSE IPROPERTY
// cSpell:words IOBJECT IOBJECTEND
import {
TOP, TNUMBER, TSTRING, TPAREN, TBRACKET, TCOMMA, TNAME, TSEMICOLON, TEOF, TKEYWORD, TBRACE, Token, TokenType,
TCONST
} from './token.js';
import { Instruction, ISCALAR, IVAR, IFUNCALL, IMEMBER, IARRAY, IUNDEFINED, binaryInstruction, unaryInstruction, IWHENMATCH, ICASEMATCH, ICASEELSE, ICASECOND, IWHENCOND, IPROPERTY, IOBJECT, IOBJECTEND, InstructionType, IVARNAME, IEXPR, IARROW } from './instruction.js';
import contains from '../core/contains.js';
import { TokenStream } from './token-stream.js';
import { ParseError, AccessError } from '../types/errors.js';
import { AssignmentParser } from './utils/assignment-parser.js';
import { ConditionalExpressionParser } from './utils/conditional-expression-parser.js';
import { StatementParser } from './utils/statement-parser.js';
// Parser interface (will be more complete when we convert parser.js)
interface ParserLike {
isOperatorEnabled(op: string): boolean;
}
// Options interface
interface ParserStateOptions {
allowMemberAccess?: boolean;
}
// Token matching function type
type TokenMatcher = (token: Token) => boolean;
// Token value matcher - can be various types
type TokenValueMatcher = string | readonly string[] | string[] | TokenMatcher | undefined;
export class ParserState {
public parser: ParserLike;
public tokens: TokenStream;
public current: Token | null = null;
public nextToken: Token | null = null;
public savedCurrent: Token | null = null;
public savedNextToken: Token | null = null;
public allowMemberAccess: boolean;
private assignmentParser: AssignmentParser;
private conditionalParser: ConditionalExpressionParser;
private statementParser: StatementParser;
constructor(parser: ParserLike, tokenStream: TokenStream, options: ParserStateOptions) {
this.parser = parser;
this.tokens = tokenStream;
this.allowMemberAccess = options.allowMemberAccess !== false;
this.assignmentParser = new AssignmentParser(tokenStream);
this.conditionalParser = new ConditionalExpressionParser();
this.statementParser = new StatementParser();
this.next();
}
next(): Token {
this.current = this.nextToken;
return (this.nextToken = this.tokens.next());
}
tokenMatches(token: Token, value: TokenValueMatcher, exclude?: string[]): boolean {
if (exclude && contains(exclude, token.value as string)) {
return false;
}
if (typeof value === 'undefined') {
return true;
} else if (Array.isArray(value)) {
return contains([...value], token.value as string);
} else if (typeof value === 'function') {
return value(token);
} else {
return token.value === value;
}
}
save(): void {
this.savedCurrent = this.current;
this.savedNextToken = this.nextToken;
this.tokens.save();
}
restore(): void {
this.tokens.restore();
this.current = this.savedCurrent;
this.nextToken = this.savedNextToken;
}
accept(type: TokenType, value?: TokenValueMatcher, exclude?: string[]): boolean {
if (this.nextToken!.type === type && this.tokenMatches(this.nextToken!, value, exclude)) {
this.next();
return true;
}
return false;
}
expect(type: TokenType, value?: TokenValueMatcher): void {
if (!this.accept(type, value)) {
const coords = this.tokens.getCoordinates();
throw new ParseError(
`Expected ${value || type}`,
{
position: { line: coords.line, column: coords.column },
token: this.nextToken?.value?.toString(),
expression: this.tokens.expression
}
);
}
}
parseAtom(instr: Instruction[]): void {
const unaryOps = this.tokens.unaryOps;
function isPrefixOperator(token: Token): boolean {
return token.value as string in unaryOps;
}
if (this.accept(TNAME) || this.accept(TOP, isPrefixOperator)) {
if (this.current!.value === 'undefined') {
// undefined is a reserved work that evaluates to JavaScript undefined.
instr.push(new Instruction(IUNDEFINED));
} else {
// Check if this is a single-parameter arrow function: x => expr
if (this.nextToken!.type === TOP && this.nextToken!.value === '=>') {
this.parseArrowFunctionFromParameter(instr, this.current!.value as string);
} else {
instr.push(new Instruction(IVAR, this.current!.value));
}
}
} else if (this.accept(TNUMBER) || this.accept(TSTRING) || this.accept(TCONST)) {
instr.push(new Instruction(ISCALAR, this.current!.value));
} else if (this.accept(TPAREN, '(')) {
// Check if this is a multi-parameter arrow function: (x, y) => expr
if (this.tryParseArrowFunction(instr)) {
// Arrow function was parsed successfully
return;
}
this.parseExpression(instr);
this.expect(TPAREN, ')');
} else if (this.accept(TBRACE, '{')) {
this.parseObject(instr);
} else if (this.accept(TBRACKET, '[')) {
if (this.accept(TBRACKET, ']')) {
instr.push(new Instruction(IARRAY, 0));
} else {
const argCount = this.parseArrayList(instr);
instr.push(new Instruction(IARRAY, argCount));
}
} else if (this.accept(TKEYWORD)) {
this.parseKeywordExpression(instr);
} else {
const coords = this.tokens.getCoordinates();
throw new ParseError(
`Unexpected token: ${this.nextToken}`,
{
position: { line: coords.line, column: coords.column },
token: this.nextToken?.value?.toString(),
expression: this.tokens.expression
}
);
}
}
/**
* Parses an arrow function when we already have a single parameter name.
* Called when we detect: `paramName =>` pattern
*/
private parseArrowFunctionFromParameter(instr: Instruction[], paramName: string): void {
// Validate that arrow functions are enabled
if (!this.parser.isOperatorEnabled('=>')) {
const coords = this.tokens.getCoordinates();
throw new ParseError(
'Arrow function syntax is not permitted',
{
position: { line: coords.line, column: coords.column },
expression: this.tokens.expression
}
);
}
// Consume the '=>' operator
this.expect(TOP, '=>');
// Parse the function body expression. We use parseConditionalExpression instead of
// parseExpression because arrow function bodies should be single expressions and
// should NOT consume semicolons. The semicolon terminates the arrow function
// definition, allowing patterns like: `fn = x => x * 2; map(fn, arr)`
// If we used parseExpression, the semicolon and subsequent statements would be
// incorrectly included in the arrow function body.
const bodyInstr: Instruction[] = [];
this.parseConditionalExpression(bodyInstr);
// Build the arrow function: push param name, body expression, and IARROW instruction
instr.push(new Instruction(IVARNAME, paramName));
instr.push(new Instruction(IEXPR, bodyInstr));
instr.push(new Instruction(IARROW, 1));
}
/**
* Attempts to parse an arrow function after seeing '('.
* Returns true if it successfully parsed an arrow function, false otherwise.
* Uses lookahead to detect arrow function syntax without consuming tokens on failure.
*/
private tryParseArrowFunction(instr: Instruction[]): boolean {
// Save current position for backtracking
this.save();
// Try to parse parameter list
const params: string[] = [];
// Check for empty parameter list: () => expr
if (this.accept(TPAREN, ')')) {
// Check if followed by =>
if (this.accept(TOP, '=>')) {
// Validate that arrow functions are enabled
if (!this.parser.isOperatorEnabled('=>')) {
this.restore();
return false;
}
// Parse the function body
const bodyInstr: Instruction[] = [];
this.parseExpression(bodyInstr);
// Build the arrow function with no parameters
instr.push(new Instruction(IEXPR, bodyInstr));
instr.push(new Instruction(IARROW, 0));
return true;
}
// Not an arrow function, restore and return false
this.restore();
return false;
}
// Try to parse comma-separated parameter names
if (!this.accept(TNAME)) {
// Not a parameter list, restore and return false
this.restore();
return false;
}
params.push(this.current!.value as string);
// Parse additional parameters separated by commas
while (this.accept(TCOMMA)) {
if (!this.accept(TNAME)) {
// Invalid parameter, restore and return false
this.restore();
return false;
}
params.push(this.current!.value as string);
}
// Expect closing parenthesis
if (!this.accept(TPAREN, ')')) {
// Not a parameter list, restore and return false
this.restore();
return false;
}
// Check for arrow operator
if (!this.accept(TOP, '=>')) {
// Not an arrow function, restore and return false
this.restore();
return false;
}
// Validate that arrow functions are enabled
if (!this.parser.isOperatorEnabled('=>')) {
const coords = this.tokens.getCoordinates();
throw new ParseError(
'Arrow function syntax is not permitted',
{
position: { line: coords.line, column: coords.column },
expression: this.tokens.expression
}
);
}
// Parse the function body expression. We use parseConditionalExpression instead of
// parseExpression because arrow function bodies should be single expressions and
// should NOT consume semicolons. This allows patterns like: `fn = (a, b) => a + b; map(fn, arr)`
const bodyInstr: Instruction[] = [];
this.parseConditionalExpression(bodyInstr);
// Build the arrow function: push param names, body expression, and IARROW instruction
for (const param of params) {
instr.push(new Instruction(IVARNAME, param));
}
instr.push(new Instruction(IEXPR, bodyInstr));
instr.push(new Instruction(IARROW, params.length));
return true;
}
parseExpression(instr: Instruction[]): void {
const exprInstr: Instruction[] = [];
if (this.parseUntilEndStatement(instr, exprInstr)) {
return;
}
this.parseVariableAssignmentExpression(exprInstr);
if (this.parseUntilEndStatement(instr, exprInstr)) {
return;
}
this.pushExpression(instr, exprInstr);
}
pushExpression(instr: Instruction[], exprInstr: Instruction[]): void {
for (let i = 0, len = exprInstr.length; i < len; i++) {
instr.push(exprInstr[i]);
}
}
parseUntilEndStatement(instr: Instruction[], exprInstr: Instruction[]): boolean {
if (!this.accept(TSEMICOLON)) {
return false;
}
// Add end statement if needed based on next token
if (this.statementParser.shouldAddEndStatement(this.nextToken)) {
exprInstr.push(this.statementParser.createEndStatement());
}
// Continue parsing if there are more tokens
if (this.statementParser.shouldContinueParsing(this.nextToken)) {
this.parseExpression(exprInstr);
}
// Finalize the statement
this.statementParser.processStatementTermination(instr, exprInstr, this.nextToken);
return true;
}
parseArrayList(instr: Instruction[]): number {
let argCount = 0;
while (!this.accept(TBRACKET, ']')) {
this.parseExpression(instr);
++argCount;
while (this.accept(TCOMMA)) {
this.parseExpression(instr);
++argCount;
}
}
return argCount;
}
parseVariableAssignmentExpression(instr: Instruction[]): void {
this.parseConditionalExpression(instr);
while (this.accept(TOP, '=')) {
const assignmentTarget = instr.pop()!;
const assignmentValue = this.assignmentParser.createVariableValueArray();
const lastInstructionIndex = instr.length - 1;
if (this.assignmentParser.isFunctionCallAssignment(assignmentTarget)) {
this.parseVariableAssignmentExpression(assignmentValue);
this.assignmentParser.processFunctionDefinition(instr, assignmentTarget, assignmentValue, lastInstructionIndex);
continue;
}
if (this.assignmentParser.isVariableAssignment(assignmentTarget)) {
this.parseVariableAssignmentExpression(assignmentValue);
this.assignmentParser.processVariableAssignment(instr, assignmentTarget, assignmentValue);
} else {
throw new Error('expected variable for assignment');
}
}
}
parseConditionalExpression(instr: Instruction[]): void {
this.parseOrExpression(instr);
while (this.accept(TOP, '?')) {
const { trueBranch, falseBranch } = this.conditionalParser.createTernaryBranches();
this.parseConditionalExpression(trueBranch);
this.expect(TOP, ':');
this.parseConditionalExpression(falseBranch);
this.conditionalParser.finalizeTernaryExpression(instr, trueBranch, falseBranch);
}
}
parseOrExpression(instr: Instruction[]): void {
this.parseAndExpression(instr);
while (this.accept(TOP, ['or', '||'])) {
const rightOperandBranch = this.conditionalParser.createLogicalBranch();
this.parseAndExpression(rightOperandBranch);
this.conditionalParser.finalizeOrExpression(instr, rightOperandBranch);
}
}
parseAndExpression(instr: Instruction[]): void {
this.parseComparison(instr);
while (this.accept(TOP, ['and', '&&'])) {
const rightOperandBranch = this.conditionalParser.createLogicalBranch();
this.parseComparison(rightOperandBranch);
this.conditionalParser.finalizeAndExpression(instr, rightOperandBranch);
}
}
private static readonly COMPARISON_OPERATORS = ['==', '!=', '<', '<=', '>=', '>', 'in', 'not in'] as const;
parseComparison(instr: Instruction[]): void {
this.parseAddSub(instr);
while (this.accept(TOP, ParserState.COMPARISON_OPERATORS)) {
const op = this.current!;
this.parseAddSub(instr);
instr.push(binaryInstruction(op.value as string));
}
}
private static readonly ADD_SUB_OPERATORS = ['+', '-', '|'] as const;
parseAddSub(instr: Instruction[]): void {
this.parseTerm(instr);
while (this.accept(TOP, ParserState.ADD_SUB_OPERATORS, ['||'])) {
const op = this.current!;
this.parseTerm(instr);
instr.push(binaryInstruction(op.value as string));
}
}
private static readonly TERM_OPERATORS = ['*', '/', '%'] as const;
parseTerm(instr: Instruction[]): void {
// this.parseFactor(instr);
this.parseCoalesceExpression(instr);
while (this.accept(TOP, ParserState.TERM_OPERATORS)) {
const op = this.current!;
this.parseFactor(instr);
instr.push(binaryInstruction(op.value as string));
}
}
private static readonly COALESCE_OPERATORS = ['??', 'as'] as const;
parseCoalesceExpression(instr: Instruction[]): void {
this.parseFactor(instr);
while (this.accept(TOP, ParserState.COALESCE_OPERATORS)) {
const op = this.current!;
this.parseFactor(instr);
instr.push(binaryInstruction(op.value as string));
}
}
parseFactor(instr: Instruction[]): void {
const unaryOps = this.tokens.unaryOps;
function isPrefixOperator(token: Token): boolean {
return token.value as string in unaryOps;
}
this.save();
if (this.accept(TOP, isPrefixOperator)) {
if (this.current!.value !== '-' && this.current!.value !== '+') {
if (this.nextToken!.type === TPAREN && this.nextToken!.value === '(') {
this.restore();
this.parseExponential(instr);
return;
} else if (this.nextToken!.type === TSEMICOLON || this.nextToken!.type === TCOMMA || this.nextToken!.type === TEOF || (this.nextToken!.type === TPAREN && this.nextToken!.value === ')')) {
this.restore();
this.parseAtom(instr);
return;
}
}
const op = this.current!;
this.parseFactor(instr);
instr.push(unaryInstruction(op.value as string));
} else {
this.parseExponential(instr);
}
}
parseExponential(instr: Instruction[]): void {
this.parsePostfixExpression(instr);
while (this.accept(TOP, '^')) {
this.parseFactor(instr);
instr.push(binaryInstruction('^'));
}
}
parsePostfixExpression(instr: Instruction[]): void {
this.parseFunctionCall(instr);
while (this.accept(TOP, '!')) {
instr.push(unaryInstruction('!'));
}
}
parseFunctionCall(instr: Instruction[]): void {
const unaryOps = this.tokens.unaryOps;
function isPrefixOperator(token: Token): boolean {
return token.value as string in unaryOps;
}
if (this.accept(TOP, isPrefixOperator)) {
const op = this.current!;
this.parseAtom(instr);
instr.push(unaryInstruction(op.value as string));
} else {
this.parseMemberExpression(instr);
while (this.accept(TPAREN, '(')) {
if (this.accept(TPAREN, ')')) {
instr.push(new Instruction(IFUNCALL, 0));
} else {
const argCount = this.parseArgumentList(instr);
instr.push(new Instruction(IFUNCALL, argCount));
}
}
}
}
parseArgumentList(instr: Instruction[]): number {
let argCount = 0;
while (!this.accept(TPAREN, ')')) {
this.parseExpression(instr);
++argCount;
while (this.accept(TCOMMA)) {
this.parseExpression(instr);
++argCount;
}
}
return argCount;
}
parseMemberExpression(instr: Instruction[]): void {
this.parseAtom(instr);
while (this.accept(TOP, '.') || this.accept(TBRACKET, '[')) {
const op = this.current!;
if (op.value === '.') {
if (!this.allowMemberAccess) {
throw new AccessError(
'member access is not permitted',
{
expression: this.tokens.expression
}
);
}
this.expect(TNAME);
instr.push(new Instruction(IMEMBER, this.current!.value));
} else if (op.value === '[') {
if (!this.tokens.isOperatorEnabled('[')) {
throw new AccessError(
'Array access is disabled',
{
expression: this.tokens.expression
}
);
}
this.parseExpression(instr);
this.expect(TBRACKET, ']');
instr.push(binaryInstruction('['));
} else {
throw new Error('unexpected symbol: ' + op.value);
}
}
}
parseKeywordExpression(instr: Instruction[]): void {
if (this.current!.value === 'case') {
this.parseCaseWhen(instr);
return;
}
throw new Error(`unexpected keyword: ${this.current!.value}`);
}
parseCaseWhen(instr: Instruction[]): void {
/*
cases look like:
case $input
when $match1 then $value1
when $match2 then $value2
else $value3
end
OR
case
when $expr1 then $value1
when $expr2 then $value2
else $value3
end
The first case is comparing the match values to the input, the second case is essentially an if/else/if chain.
The parse tree uses postfix notation so the trees for the above should look like
$input $match1 $value1 WHEN $match2 $value2 WHEN $value3 ELSE
$expr1 $value1 WHEN $expr2 $value2 WHEN $value3 ELSE
*/
// Before doing anything we need to look a head at the next token to see whether it is
// a WHEN or something else; if it is a WHEN then we have a case with no input (ICASECOND)
// vs. a case with input (ICASEMATCH).
const caseWithInput = this.nextToken!.type !== TKEYWORD;
const caseInstruction: InstructionType = caseWithInput ? ICASEMATCH : ICASECOND;
const whenInstruction: InstructionType = caseWithInput ? IWHENMATCH : IWHENCOND;
// Parse the expression for the value being checked by the case.
if (caseWithInput) {
this.parseConditionalExpression(instr);
}
// Parse all the when xxx then yyy conditions.
let count = 0;
while (this.accept(TKEYWORD, 'when')) {
this.parseConditionalExpression(instr);
if (this.accept(TKEYWORD, 'then')) {
this.parseConditionalExpression(instr);
instr.push(new Instruction(whenInstruction, count++));
} else {
throw new Error('case block missing when');
}
}
// Parse the optional else which gets added to the parse tree as when true then yyy
if (this.accept(TKEYWORD, 'else')) {
this.parseConditionalExpression(instr);
instr.push(new Instruction(ICASEELSE, count++));
}
// Parse the end of the case.
if (this.accept(TKEYWORD, 'end')) {
instr.push(new Instruction(caseInstruction, count));
} else {
throw new Error('invalid case block');
}
}
parseObject(instr: Instruction[]): number {
const error = 'invalid object definition';
let count = 0;
instr.push(new Instruction(IOBJECT, 0));
for (let first = true; !this.accept(TBRACE, '}'); first = false) {
// There should be a command before the 2nd-nth property.
if (!first && !this.accept(TCOMMA, ',')) {
throw new Error(error);
}
// We want to allow an extraneous trailing comma after the last property
// so if there is a closing brace after the comma we allow it and the
// object is complete.
if (this.accept(TBRACE, '}')) {
return count;
}
// Expect a name token for the property name.
if (!this.accept(TNAME)) {
throw new Error(error);
}
const name = this.current!.value;
// Expect a colon.
if (!this.accept(TOP, ':')) {
throw new Error(error);
}
// Expect an expression for the property value.
this.parseExpression(instr);
instr.push(new Instruction(IPROPERTY, name));
++count;
}
instr.push(new Instruction(IOBJECTEND, count));
return count;
}
}