sfmc-handlebars-parser 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,488 @@
1
+ /**
2
+ * Expression / path / literal / hash / subexpression sub-parsers for sfmc-handlebars-parser.
3
+ *
4
+ * These operate over the flat token stream from {@link import('./tokenizer.js').tokenize} and
5
+ * build the INSIDE of a mustache: the call path, positional params, trailing `k=v` hash pairs,
6
+ * and nested subexpressions. The statement/block/mustache layer (W2b) drives them through the
7
+ * shared {@link createReader} cursor, so both layers agree on token navigation.
8
+ *
9
+ * Clean-room note: written from the observed public AST behaviour of `@handlebars/parser`
10
+ * (MIT) and the Handlebars language spec; no upstream source was copied.
11
+ *
12
+ * ── What W2b consumes ────────────────────────────────────────────────────────────────────
13
+ * - {@link createReader}(tokens, table, source) -> a cursor `{ index, tokens, table, source,
14
+ * peek, peekType, next, atEnd, skipWhitespace, expect, sliceOriginal }`.
15
+ * - {@link parsePath}(reader) -> a `PathExpression` (consumes one path).
16
+ * - {@link parseLiteral}(reader) -> a literal node, or `undefined` if the cursor is not on a
17
+ * literal.
18
+ * - {@link parseExpressionParameter}(reader) -> ONE positional param (subexpression | literal |
19
+ * path), or `undefined` if the cursor is not on a param start.
20
+ * - {@link parseSubExpression}(reader) -> a `SubExpression` (cursor must be on `(`).
21
+ * - {@link parseParametersAndHash}(reader, isTerminator) -> `{ params, hash }` where `hash` is
22
+ * `undefined` (a present key, not a node) when there are no `k=v` pairs.
23
+ *
24
+ * The reader skips insignificant {@link import('./tokenizer.js').TokenType.WHITESPACE} tokens
25
+ * on demand (callers invoke `skipWhitespace()` before reading an atom); it never mutates tokens.
26
+ */
27
+
28
+ import { TokenType } from './tokenizer.js';
29
+ import { HandlebarsException } from './errors.js';
30
+ import { offsetToPosition } from './loc.js';
31
+ import {
32
+ booleanLiteral,
33
+ hash as hashNodeFactory,
34
+ hashPair,
35
+ nullLiteral,
36
+ numberLiteral,
37
+ pathExpression,
38
+ stringLiteral,
39
+ subExpression,
40
+ undefinedLiteral,
41
+ } from './nodes.js';
42
+
43
+ /**
44
+ * Bare-word keywords that classify an `ID` token as a literal rather than a path segment.
45
+ */
46
+ const KEYWORD_LITERALS = new Set(['true', 'false', 'null', 'undefined']);
47
+
48
+ /**
49
+ * Token types that form a path segment (and, when contiguous, join into one segment string).
50
+ */
51
+ const SEGMENT_TOKEN_TYPES = new Set([TokenType.ID, TokenType.NUMBER, TokenType.SEGMENT]);
52
+
53
+ /**
54
+ * Creates a cursor over a token array shared by the expression sub-parsers and W2b's statement
55
+ * layer. The cursor is a plain object with an integer `index` that the methods advance; both
56
+ * layers mutate the SAME object so navigation stays consistent.
57
+ *
58
+ * @param {object[]} tokens - The token stream from {@link import('./tokenizer.js').tokenize}.
59
+ * @param {import('./loc.js').LineTable} table - Line table for the source.
60
+ * @param {string} source - The original source string (for `sliceOriginal`).
61
+ * @returns {object} The reader cursor (see the module header for its shape).
62
+ */
63
+ export function createReader(tokens, table, source) {
64
+ const reader = {
65
+ tokens,
66
+ table,
67
+ source,
68
+ index: 0,
69
+
70
+ /**
71
+ * Returns the token at `offset` from the current index without advancing (default 0).
72
+ *
73
+ * @param {number} [offset] - Look-ahead distance from the current index.
74
+ * @returns {object|undefined} The token, or `undefined` past the end.
75
+ */
76
+ peek(offset = 0) {
77
+ return tokens[reader.index + offset];
78
+ },
79
+
80
+ /**
81
+ * Returns the `type` of the token at `offset` from the current index (default 0).
82
+ *
83
+ * @param {number} [offset] - Look-ahead distance from the current index.
84
+ * @returns {string|undefined} The token type, or `undefined` past the end.
85
+ */
86
+ peekType(offset = 0) {
87
+ const token = tokens[reader.index + offset];
88
+ return token && token.type;
89
+ },
90
+
91
+ /**
92
+ * Returns the current token and advances the cursor by one.
93
+ *
94
+ * @returns {object|undefined} The consumed token, or `undefined` past the end.
95
+ */
96
+ next() {
97
+ return tokens[reader.index++];
98
+ },
99
+
100
+ /**
101
+ * Whether the cursor is at (or past) the terminal `EOF` token.
102
+ *
103
+ * @returns {boolean} True when no more real tokens remain.
104
+ */
105
+ atEnd() {
106
+ const token = tokens[reader.index];
107
+ return !token || token.type === TokenType.EOF;
108
+ },
109
+
110
+ /**
111
+ * Advances past any run of insignificant `WHITESPACE` tokens.
112
+ *
113
+ * @returns {void}
114
+ */
115
+ skipWhitespace() {
116
+ let token = tokens[reader.index];
117
+ while (token && token.type === TokenType.WHITESPACE) {
118
+ reader.index++;
119
+ token = tokens[reader.index];
120
+ }
121
+ },
122
+
123
+ /**
124
+ * Consumes the current token, asserting its `type`. Throws a plain `Error` (W2b owns
125
+ * user-facing error classes) when the type does not match.
126
+ *
127
+ * @param {string} type - The expected {@link import('./tokenizer.js').TokenType}.
128
+ * @returns {object} The consumed token.
129
+ */
130
+ expect(type) {
131
+ const token = tokens[reader.index];
132
+ if (!token || token.type !== type) {
133
+ throw new Error(
134
+ `expected ${type} but found ${token ? token.type : 'end of input'}`,
135
+ );
136
+ }
137
+ reader.index++;
138
+ return token;
139
+ },
140
+
141
+ /**
142
+ * Returns `source.slice(startOffset, endOffset)` (raw text of a span).
143
+ *
144
+ * @param {number} startOffset - Start offset.
145
+ * @param {number} endOffset - End offset.
146
+ * @returns {string} The raw source slice.
147
+ */
148
+ sliceOriginal(startOffset, endOffset) {
149
+ return source.slice(startOffset, endOffset);
150
+ },
151
+ };
152
+ return reader;
153
+ }
154
+
155
+ /**
156
+ * Whether `token` can begin (or continue) a path: an `ID`, `SEGMENT`, `DATA` (`@`) prefix, a
157
+ * path separator `SEP`, or a bare `NUMBER` segment.
158
+ *
159
+ * @param {object|undefined} token - A token, or `undefined`.
160
+ * @returns {boolean} True when `token` starts/continues a path.
161
+ */
162
+ function isPathToken(token) {
163
+ if (!token) {
164
+ return false;
165
+ }
166
+ return (
167
+ SEGMENT_TOKEN_TYPES.has(token.type) ||
168
+ token.type === TokenType.DATA ||
169
+ token.type === TokenType.SEP
170
+ );
171
+ }
172
+
173
+ /**
174
+ * Reads one path segment: a maximal run of ADJACENT `ID`/`NUMBER`/`SEGMENT` tokens (each token's
175
+ * `start` equal to the previous token's `end`, i.e. no whitespace or separator between them). The
176
+ * tokenizer emits sub-tokens for lexemes like `0x1` (`NUMBER(0)` + `ID(x1)`); upstream rejoins
177
+ * such a contiguous run into a single segment string. The cursor must be on the run's first token.
178
+ *
179
+ * @param {object} reader - The shared cursor from {@link createReader}.
180
+ * @returns {{value: string, endOffset: number}} The joined segment text and its end offset.
181
+ */
182
+ function readContiguousSegment(reader) {
183
+ let value = '';
184
+ let endOffset = reader.peek().start;
185
+ while (!reader.atEnd()) {
186
+ const token = reader.peek();
187
+ if (!SEGMENT_TOKEN_TYPES.has(token.type) || token.start !== endOffset) {
188
+ break;
189
+ }
190
+ value += token.value;
191
+ endOffset = token.end;
192
+ reader.next();
193
+ }
194
+ return { value, endOffset };
195
+ }
196
+
197
+ /**
198
+ * Parses a single `PathExpression` starting at the cursor (leading whitespace is skipped first).
199
+ *
200
+ * Grammar handled: an optional `@` data prefix; leading `../` parent hops (each `..` increments
201
+ * `depth`); a `this` context head; `.`- and legacy `/`-separated segments; bare-word `ID`
202
+ * segments (including `$`/`_`/`-` ids); and `[segment literal]` parts whose inner text is kept
203
+ * verbatim. `original` is the raw path text with segment-literal brackets removed and every
204
+ * separator kept. See {@link pathExpression} for how `head`/`tail`/`this` are derived.
205
+ *
206
+ * @param {object} reader - The shared cursor from {@link createReader}.
207
+ * @returns {object} A `PathExpression` node.
208
+ */
209
+ export function parsePath(reader) {
210
+ reader.skipWhitespace();
211
+ const startToken = reader.peek();
212
+ const startOffset = startToken.start;
213
+
214
+ let isData = false;
215
+ let depth = 0;
216
+ let endOffset = startOffset;
217
+ /**
218
+ * @type {string[]}
219
+ */
220
+ const parts = [];
221
+ let isSawThisHead = false;
222
+ let segmentCount = 0;
223
+
224
+ // Optional `@` data prefix.
225
+ if (reader.peekType() === TokenType.DATA) {
226
+ isData = true;
227
+ endOffset = reader.next().end;
228
+ }
229
+
230
+ // Walk segments and separators until the path can no longer continue.
231
+ while (!reader.atEnd()) {
232
+ const token = reader.peek();
233
+ if (token.type === TokenType.SEP) {
234
+ if (token.value === '..') {
235
+ // A parent hop (`..`) is only valid at the START of a path (leading `../`).
236
+ // Once a real segment has been collected, upstream rejects a later `..` with an
237
+ // exception-class `Invalid path` error anchored at the path's start column. The
238
+ // reported `original` is the raw path text up to and including this `..`.
239
+ if (parts.length > 0) {
240
+ const bad = reader.source
241
+ .slice(startOffset, token.end)
242
+ .replaceAll(/[[\]]/g, '');
243
+ const at = offsetToPosition(reader.table, startOffset);
244
+ throw new HandlebarsException(
245
+ `Invalid path: ${bad} - ${at.line}:${at.column}`,
246
+ {
247
+ lineNumber: at.line,
248
+ column: at.column,
249
+ },
250
+ );
251
+ }
252
+ depth++;
253
+ }
254
+ endOffset = token.end;
255
+ reader.next();
256
+ continue;
257
+ }
258
+ if (SEGMENT_TOKEN_TYPES.has(token.type)) {
259
+ // One segment = a maximal run of adjacent ID/NUMBER/SEGMENT tokens (no gap between
260
+ // them). The tokenizer splits e.g. `0x1` into NUMBER(0)+ID(x1); upstream treats the
261
+ // contiguous run as one path segment (`parts: ["0x1"]`).
262
+ const segment = readContiguousSegment(reader);
263
+ endOffset = segment.endOffset;
264
+ if (segmentCount === 0 && token.type === TokenType.ID && segment.value === 'this') {
265
+ // A `this` head is not a part; it only sets the `this` flag (when a tail follows).
266
+ isSawThisHead = true;
267
+ } else {
268
+ parts.push(segment.value);
269
+ }
270
+ segmentCount++;
271
+ // Continue only if the next token is a separator (a contiguous path).
272
+ if (reader.peekType() !== TokenType.SEP) {
273
+ break;
274
+ }
275
+ continue;
276
+ }
277
+ break;
278
+ }
279
+
280
+ const original = reader.source.slice(startOffset, endOffset).replaceAll(/[[\]]/g, '');
281
+ return pathExpression(reader.table, startOffset, endOffset, {
282
+ data: isData,
283
+ depth,
284
+ parts,
285
+ original,
286
+ this: isSawThisHead && parts.length > 0,
287
+ });
288
+ }
289
+
290
+ /**
291
+ * Parses a literal at the cursor (leading whitespace is skipped first), or returns `undefined`
292
+ * when the cursor is not on a literal. String/number literals come from dedicated tokens;
293
+ * boolean/`null`/`undefined` literals arrive as bare `ID` tokens and are classified by value
294
+ * (only when they stand alone — an `ID` keyword immediately followed by a `SEP` is a path
295
+ * segment, e.g. `true.x`, and is left for {@link parsePath}).
296
+ *
297
+ * @param {object} reader - The shared cursor from {@link createReader}.
298
+ * @returns {object|undefined} A literal node, or `undefined` if the cursor is not on a literal.
299
+ */
300
+ export function parseLiteral(reader) {
301
+ reader.skipWhitespace();
302
+ const token = reader.peek();
303
+ if (!token) {
304
+ return;
305
+ }
306
+ if (token.type === TokenType.STRING) {
307
+ reader.next();
308
+ return stringLiteral(reader.table, token.start, token.end, token.value);
309
+ }
310
+ if (token.type === TokenType.NUMBER) {
311
+ // A NUMBER immediately followed (no gap) by an ID/NUMBER/SEGMENT is really a path
312
+ // segment (e.g. `0x1` -> NUMBER(0)+ID(x1)); leave it for parsePath.
313
+ const next = reader.peek(1);
314
+ if (next && next.start === token.end && SEGMENT_TOKEN_TYPES.has(next.type)) {
315
+ return;
316
+ }
317
+ reader.next();
318
+ return numberLiteral(reader.table, token.start, token.end, Number(token.value));
319
+ }
320
+ if (token.type === TokenType.ID && KEYWORD_LITERALS.has(token.value)) {
321
+ // Only a standalone keyword is a literal; `true.x` etc. is a path.
322
+ if (reader.peekType(1) === TokenType.SEP) {
323
+ return;
324
+ }
325
+ reader.next();
326
+ switch (token.value) {
327
+ case 'true': {
328
+ return booleanLiteral(reader.table, token.start, token.end, true);
329
+ }
330
+ case 'false': {
331
+ return booleanLiteral(reader.table, token.start, token.end, false);
332
+ }
333
+ case 'null': {
334
+ return nullLiteral(reader.table, token.start, token.end);
335
+ }
336
+ default: {
337
+ return undefinedLiteral(reader.table, token.start, token.end);
338
+ }
339
+ }
340
+ }
341
+ return;
342
+ }
343
+
344
+ /**
345
+ * Parses ONE positional parameter at the cursor (leading whitespace skipped first): a
346
+ * subexpression `( … )`, a literal, or a path — in that precedence. Returns `undefined` when the
347
+ * cursor is not on a parameter start (e.g. a terminator or a hash pair).
348
+ *
349
+ * @param {object} reader - The shared cursor from {@link createReader}.
350
+ * @returns {object|undefined} A param node, or `undefined` when none starts here.
351
+ */
352
+ export function parseExpressionParameter(reader) {
353
+ reader.skipWhitespace();
354
+ const token = reader.peek();
355
+ if (!token) {
356
+ return;
357
+ }
358
+ if (token.type === TokenType.OPEN_PAREN) {
359
+ return parseSubExpression(reader);
360
+ }
361
+ const literal = parseLiteral(reader);
362
+ if (literal) {
363
+ return literal;
364
+ }
365
+ if (isPathToken(token)) {
366
+ return parsePath(reader);
367
+ }
368
+ return;
369
+ }
370
+
371
+ /**
372
+ * Parses a `SubExpression` — `( path params hash )` — with the cursor on the opening `(`.
373
+ * Recurses through {@link parseParametersAndHash} for nested params/subexpressions. The `loc` spans
374
+ * the parens inclusive.
375
+ *
376
+ * @param {object} reader - The shared cursor from {@link createReader}.
377
+ * @returns {object} A `SubExpression` node.
378
+ */
379
+ export function parseSubExpression(reader) {
380
+ const open = reader.expect(TokenType.OPEN_PAREN);
381
+ reader.skipWhitespace();
382
+ const path = parsePath(reader);
383
+ const { params, hash } = parseParametersAndHash(
384
+ reader,
385
+ (token) => token.type === TokenType.CLOSE_PAREN,
386
+ );
387
+ reader.skipWhitespace();
388
+ const close = reader.expect(TokenType.CLOSE_PAREN);
389
+ return subExpression(reader.table, open.start, close.end, path, params, hash);
390
+ }
391
+
392
+ /**
393
+ * Parses the positional-params-then-hash-pairs tail of a call (mustache body, block open,
394
+ * subexpression, partial, decorator). Consumes positional params until a `k=v` hash pair begins
395
+ * (an `ID` immediately followed by `EQUALS`) or `isTerminator` matches the next non-whitespace
396
+ * token, then consumes the trailing hash pairs.
397
+ *
398
+ * @param {object} reader - The shared cursor from {@link createReader}.
399
+ * @param {(token: object) => boolean} isTerminator - Predicate matching the token that ends the
400
+ * param/hash sequence (e.g. `CLOSE`, `CLOSE_PAREN`, `PIPE`). WHITESPACE is skipped before the
401
+ * check, so the predicate sees the next significant token.
402
+ * @returns {{params: object[], hash: (object|undefined)}} The positional params and the `Hash`
403
+ * node (or `undefined` when there is no `k=v` pair — a present key, per the AST contract).
404
+ */
405
+ export function parseParametersAndHash(reader, isTerminator) {
406
+ /**
407
+ * @type {object[]}
408
+ */
409
+ const parameters = [];
410
+ /**
411
+ * @type {object[]}
412
+ */
413
+ const pairs = [];
414
+
415
+ // Positional params: stop at a terminator or the first hash pair.
416
+ while (true) {
417
+ reader.skipWhitespace();
418
+ const token = reader.peek();
419
+ if (!token || token.type === TokenType.EOF || isTerminator(token)) {
420
+ break;
421
+ }
422
+ if (isHashPairStart(reader)) {
423
+ break;
424
+ }
425
+ const parameter = parseExpressionParameter(reader);
426
+ if (!parameter) {
427
+ break;
428
+ }
429
+ parameters.push(parameter);
430
+ }
431
+
432
+ // Trailing hash pairs: `key = value` sequences.
433
+ let firstPairStart;
434
+ let lastPairEnd;
435
+ while (true) {
436
+ reader.skipWhitespace();
437
+ const token = reader.peek();
438
+ if (!token || token.type === TokenType.EOF || isTerminator(token)) {
439
+ break;
440
+ }
441
+ if (!isHashPairStart(reader)) {
442
+ break;
443
+ }
444
+ const { pair, startOffset, endOffset } = parseHashPair(reader);
445
+ if (firstPairStart === undefined) {
446
+ firstPairStart = startOffset;
447
+ }
448
+ lastPairEnd = endOffset;
449
+ pairs.push(pair);
450
+ }
451
+
452
+ let hash;
453
+ if (pairs.length > 0) {
454
+ hash = hashNodeFactory(reader.table, firstPairStart, lastPairEnd, pairs);
455
+ }
456
+ return { params: parameters, hash };
457
+ }
458
+
459
+ /**
460
+ * Whether a `k=v` hash pair begins at the cursor: an `ID` token immediately followed (no
461
+ * whitespace) by an `EQUALS` token.
462
+ *
463
+ * @param {object} reader - The shared cursor from {@link createReader}.
464
+ * @returns {boolean} True when the next significant tokens are `ID EQUALS`.
465
+ */
466
+ function isHashPairStart(reader) {
467
+ reader.skipWhitespace();
468
+ return reader.peekType() === TokenType.ID && reader.peekType(1) === TokenType.EQUALS;
469
+ }
470
+
471
+ /**
472
+ * Parses one `HashPair` — `key = value` — with the cursor on the key `ID`. The value is a
473
+ * subexpression, literal, or path. Returns the `HashPair` node plus its raw start/end offsets so
474
+ * the caller can span the enclosing `Hash` node's `loc`.
475
+ *
476
+ * @param {object} reader - The shared cursor from {@link createReader}.
477
+ * @returns {{pair: object, startOffset: number, endOffset: number}} The pair and its span.
478
+ */
479
+ function parseHashPair(reader) {
480
+ const keyToken = reader.expect(TokenType.ID);
481
+ reader.expect(TokenType.EQUALS);
482
+ const value = parseExpressionParameter(reader);
483
+ // The value's last code unit is the end of the last token the value parser consumed.
484
+ const lastValueToken = reader.peek(-1);
485
+ const endOffset = lastValueToken ? lastValueToken.end : keyToken.end;
486
+ const pair = hashPair(reader.table, keyToken.start, endOffset, keyToken.value, value);
487
+ return { pair, startOffset: keyToken.start, endOffset };
488
+ }