-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathexpression.ts
More file actions
608 lines (526 loc) · 15.1 KB
/
expression.ts
File metadata and controls
608 lines (526 loc) · 15.1 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
// =============================================================================
// Expression Engine: Lexer + Pratt Parser
// =============================================================================
// Converts expression strings into a typed AST.
// Pipeline: tokenize(input) -> Token[] -> parse(tokens) -> ASTNode
// No eval() or Function constructor -- custom recursive descent Pratt parser.
// =============================================================================
const MAX_AST_DEPTH = 50;
// -----------------------------------------------------------------------------
// ExpressionError
// -----------------------------------------------------------------------------
export class ExpressionError extends Error {
readonly position?: number;
constructor(message: string, position?: number) {
super(message);
this.name = "ExpressionError";
this.position = position;
}
}
// -----------------------------------------------------------------------------
// Token Types & Token
// -----------------------------------------------------------------------------
export enum TokenType {
Number = "Number",
String = "String",
Boolean = "Boolean",
Null = "Null",
Identifier = "Identifier",
Dot = "Dot",
EqualEqual = "EqualEqual",
BangEqual = "BangEqual",
Less = "Less",
Greater = "Greater",
LessEqual = "LessEqual",
GreaterEqual = "GreaterEqual",
AmpAmp = "AmpAmp",
PipePipe = "PipePipe",
Bang = "Bang",
Question = "Question",
Colon = "Colon",
LeftParen = "LeftParen",
RightParen = "RightParen",
Comma = "Comma",
EOF = "EOF",
}
export interface Token {
type: TokenType;
value: string;
position: number;
}
// -----------------------------------------------------------------------------
// AST Node Types (discriminated union)
// -----------------------------------------------------------------------------
export interface LiteralNode {
type: "Literal";
value: unknown;
}
export interface IdentifierNode {
type: "Identifier";
name: string;
}
export interface MemberExpressionNode {
type: "MemberExpression";
object: ASTNode;
property: string;
}
export interface BinaryExpressionNode {
type: "BinaryExpression";
operator: string;
left: ASTNode;
right: ASTNode;
}
export interface UnaryExpressionNode {
type: "UnaryExpression";
operator: string;
operand: ASTNode;
}
export interface ConditionalExpressionNode {
type: "ConditionalExpression";
test: ASTNode;
consequent: ASTNode;
alternate: ASTNode;
}
export interface CallExpressionNode {
type: "CallExpression";
callee: ASTNode;
property: string;
args: ASTNode[];
}
export type ASTNode =
| LiteralNode
| IdentifierNode
| MemberExpressionNode
| BinaryExpressionNode
| UnaryExpressionNode
| ConditionalExpressionNode
| CallExpressionNode;
// -----------------------------------------------------------------------------
// Precedence Levels
// -----------------------------------------------------------------------------
enum Precedence {
None = 0,
Ternary = 1,
Or = 2,
And = 3,
Equality = 4,
Comparison = 5,
Unary = 6,
Call = 7,
Member = 8,
}
function getInfixPrecedence(type: TokenType): Precedence {
switch (type) {
case TokenType.Question:
return Precedence.Ternary;
case TokenType.PipePipe:
return Precedence.Or;
case TokenType.AmpAmp:
return Precedence.And;
case TokenType.EqualEqual:
case TokenType.BangEqual:
return Precedence.Equality;
case TokenType.Less:
case TokenType.Greater:
case TokenType.LessEqual:
case TokenType.GreaterEqual:
return Precedence.Comparison;
case TokenType.Dot:
return Precedence.Member;
default:
return Precedence.None;
}
}
// -----------------------------------------------------------------------------
// Lexer
// -----------------------------------------------------------------------------
function isDigit(ch: string): boolean {
return ch >= "0" && ch <= "9";
}
function isAlpha(ch: string): boolean {
return (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || ch === "_";
}
function isAlphaNumeric(ch: string): boolean {
return isAlpha(ch) || isDigit(ch);
}
export function tokenize(input: string): Token[] {
const tokens: Token[] = [];
let pos = 0;
while (pos < input.length) {
const ch = input[pos]!;
// Skip whitespace
if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") {
pos++;
continue;
}
// Two-character operators (check before single-char)
if (pos + 1 < input.length) {
const two = `${input[pos]!}${input[pos + 1]!}`;
let twoCharType: TokenType | undefined;
switch (two) {
case "==":
twoCharType = TokenType.EqualEqual;
break;
case "!=":
twoCharType = TokenType.BangEqual;
break;
case "<=":
twoCharType = TokenType.LessEqual;
break;
case ">=":
twoCharType = TokenType.GreaterEqual;
break;
case "&&":
twoCharType = TokenType.AmpAmp;
break;
case "||":
twoCharType = TokenType.PipePipe;
break;
}
if (twoCharType !== undefined) {
tokens.push({ type: twoCharType, value: two, position: pos });
pos += 2;
continue;
}
}
// Single-character operators and delimiters
let singleType: TokenType | undefined;
switch (ch) {
case ".":
singleType = TokenType.Dot;
break;
case "<":
singleType = TokenType.Less;
break;
case ">":
singleType = TokenType.Greater;
break;
case "!":
singleType = TokenType.Bang;
break;
case "?":
singleType = TokenType.Question;
break;
case ":":
singleType = TokenType.Colon;
break;
case "(":
singleType = TokenType.LeftParen;
break;
case ")":
singleType = TokenType.RightParen;
break;
case ",":
singleType = TokenType.Comma;
break;
}
if (singleType !== undefined) {
tokens.push({ type: singleType, value: ch, position: pos });
pos++;
continue;
}
// Number literals
if (isDigit(ch)) {
const start = pos;
while (pos < input.length && isDigit(input[pos]!)) {
pos++;
}
if (pos < input.length && input[pos]! === ".") {
pos++;
while (pos < input.length && isDigit(input[pos]!)) {
pos++;
}
}
tokens.push({
type: TokenType.Number,
value: input.slice(start, pos),
position: start,
});
continue;
}
// String literals
if (ch === '"' || ch === "'") {
const quote = ch;
const start = pos;
pos++; // skip opening quote
const strStart = pos;
while (pos < input.length && input[pos]! !== quote) {
pos++;
}
if (pos >= input.length) {
throw new ExpressionError(`Unterminated string literal`, start);
}
const value = input.slice(strStart, pos);
pos++; // skip closing quote
tokens.push({ type: TokenType.String, value, position: start });
continue;
}
// Identifiers and keywords
if (isAlpha(ch)) {
const start = pos;
while (pos < input.length && isAlphaNumeric(input[pos]!)) {
pos++;
}
const word = input.slice(start, pos);
if (word === "true" || word === "false") {
tokens.push({ type: TokenType.Boolean, value: word, position: start });
} else if (word === "null") {
tokens.push({ type: TokenType.Null, value: word, position: start });
} else {
tokens.push({
type: TokenType.Identifier,
value: word,
position: start,
});
}
continue;
}
throw new ExpressionError(`Unexpected character: ${ch}`, pos);
}
tokens.push({ type: TokenType.EOF, value: "", position: pos });
return tokens;
}
// -----------------------------------------------------------------------------
// Pratt Parser
// -----------------------------------------------------------------------------
export function parse(tokens: Token[]): ASTNode {
let pos = 0;
let depth = 0;
function peek(): Token {
const token = tokens[pos];
if (!token) {
throw new ExpressionError("Unexpected end of expression");
}
return token;
}
function advance(): Token {
const token = peek();
pos++;
return token;
}
function expect(type: TokenType): Token {
const token = peek();
if (token.type !== type) {
throw new ExpressionError(`Expected ${type} but got ${token.type}`, token.position);
}
return advance();
}
function parseExpression(precedence: Precedence): ASTNode {
depth++;
if (depth > MAX_AST_DEPTH) {
throw new ExpressionError("Expression too deeply nested");
}
let left = parsePrefix();
while (precedence < getInfixPrecedence(peek().type)) {
left = parseInfix(left);
}
depth--;
return left;
}
function parsePrefix(): ASTNode {
const token = advance();
switch (token.type) {
case TokenType.Number:
return { type: "Literal", value: Number(token.value) };
case TokenType.String:
return { type: "Literal", value: token.value };
case TokenType.Boolean:
return { type: "Literal", value: token.value === "true" };
case TokenType.Null:
return { type: "Literal", value: null };
case TokenType.Identifier:
return { type: "Identifier", name: token.value };
case TokenType.Bang: {
const operand = parseExpression(Precedence.Unary);
return { type: "UnaryExpression", operator: "!", operand };
}
case TokenType.LeftParen: {
const expr = parseExpression(Precedence.None);
expect(TokenType.RightParen);
return expr;
}
default:
throw new ExpressionError(`Unexpected token: ${token.type}`, token.position);
}
}
function parseInfix(left: ASTNode): ASTNode {
const token = peek();
switch (token.type) {
case TokenType.EqualEqual:
case TokenType.BangEqual:
case TokenType.Less:
case TokenType.Greater:
case TokenType.LessEqual:
case TokenType.GreaterEqual:
case TokenType.AmpAmp:
case TokenType.PipePipe: {
const prec = getInfixPrecedence(token.type);
advance();
const right = parseExpression(prec);
return {
type: "BinaryExpression",
operator: token.value,
left,
right,
};
}
case TokenType.Dot: {
advance(); // consume dot
const propToken = expect(TokenType.Identifier);
// Check if this is a method call: identifier followed by LeftParen
if (peek().type === TokenType.LeftParen) {
advance(); // consume '('
const args: ASTNode[] = [];
if (peek().type !== TokenType.RightParen) {
args.push(parseExpression(Precedence.None));
while (peek().type === TokenType.Comma) {
advance(); // consume ','
args.push(parseExpression(Precedence.None));
}
}
expect(TokenType.RightParen);
return {
type: "CallExpression",
callee: left,
property: propToken.value,
args,
};
}
return {
type: "MemberExpression",
object: left,
property: propToken.value,
};
}
case TokenType.Question: {
advance(); // consume '?'
const consequent = parseExpression(Precedence.None);
expect(TokenType.Colon);
const alternate = parseExpression(Precedence.Ternary);
return {
type: "ConditionalExpression",
test: left,
consequent,
alternate,
};
}
default:
throw new ExpressionError(`Unexpected infix token: ${token.type}`, token.position);
}
}
const result = parseExpression(Precedence.None);
if (peek().type !== TokenType.EOF) {
throw new ExpressionError(`Unexpected token after expression: ${peek().type}`, peek().position);
}
return result;
}
// -----------------------------------------------------------------------------
// Expression Context
// -----------------------------------------------------------------------------
export type ExpressionContext = Record<string, unknown>;
// -----------------------------------------------------------------------------
// Delimiter Extraction
// -----------------------------------------------------------------------------
function extractExpression(template: string): string {
const trimmed = template.trim();
if (!trimmed.startsWith("{{") || !trimmed.endsWith("}}")) {
throw new ExpressionError("Expression must be wrapped in {{ }} delimiters");
}
return trimmed.slice(2, -2).trim();
}
// -----------------------------------------------------------------------------
// Tree-Walk Evaluator
// -----------------------------------------------------------------------------
function evaluateNode(node: ASTNode, context: ExpressionContext): unknown {
switch (node.type) {
case "Literal":
return node.value;
case "Identifier":
return context[node.name];
case "MemberExpression": {
const obj = evaluateNode(node.object, context);
if (obj === null || obj === undefined) {
return undefined;
}
return (obj as Record<string, unknown>)[node.property];
}
case "BinaryExpression": {
// Short-circuit for logical operators
if (node.operator === "&&") {
const leftVal = evaluateNode(node.left, context);
if (!leftVal) return leftVal;
return evaluateNode(node.right, context);
}
if (node.operator === "||") {
const leftVal = evaluateNode(node.left, context);
if (leftVal) return leftVal;
return evaluateNode(node.right, context);
}
const left = evaluateNode(node.left, context);
const right = evaluateNode(node.right, context);
switch (node.operator) {
case "==":
return left == right;
case "!=":
return left != right;
case "<":
return (left as number) < (right as number);
case ">":
return (left as number) > (right as number);
case "<=":
return (left as number) <= (right as number);
case ">=":
return (left as number) >= (right as number);
default:
throw new ExpressionError(`Unknown operator: ${node.operator}`);
}
}
case "UnaryExpression": {
const operand = evaluateNode(node.operand, context);
if (node.operator === "!") {
return !operand;
}
throw new ExpressionError(`Unknown unary operator: ${node.operator}`);
}
case "ConditionalExpression": {
const test = evaluateNode(node.test, context);
return test ? evaluateNode(node.consequent, context) : evaluateNode(node.alternate, context);
}
case "CallExpression": {
const target = evaluateNode(node.callee, context);
if (!Array.isArray(target)) {
throw new ExpressionError(`Cannot call .${node.property}() on non-array value`);
}
const evaluatedArgs = node.args.map((arg) => evaluateNode(arg, context));
switch (node.property) {
case "contains":
return target.includes(evaluatedArgs[0]);
case "every": {
if (evaluatedArgs.length === 0) {
return target.every(Boolean);
}
const propName = evaluatedArgs[0] as string;
return target.every((item) => (item as Record<string, unknown>)[propName]);
}
case "some": {
if (evaluatedArgs.length === 0) {
return target.some(Boolean);
}
const propName = evaluatedArgs[0] as string;
return target.some((item) => (item as Record<string, unknown>)[propName]);
}
default:
throw new ExpressionError(`Unknown method: .${node.property}()`);
}
}
}
}
// -----------------------------------------------------------------------------
// Public API
// -----------------------------------------------------------------------------
export function evaluate(template: string, context: ExpressionContext): unknown {
const expr = extractExpression(template);
const tokens = tokenize(expr);
const ast = parse(tokens);
return evaluateNode(ast, context);
}