@aftertext/compiler 0.1.0 → 0.3.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.
Files changed (58) hide show
  1. package/README.md +31 -1
  2. package/dist/ast/expression.d.ts +1 -1
  3. package/dist/ast/index.d.ts +2 -2
  4. package/dist/ast/index.d.ts.map +1 -1
  5. package/dist/ast/presentation.d.ts +18 -4
  6. package/dist/ast/presentation.d.ts.map +1 -1
  7. package/dist/ast/presentation.js +4 -3
  8. package/dist/ast/presentation.js.map +1 -1
  9. package/dist/ast/story.d.ts +30 -16
  10. package/dist/ast/story.d.ts.map +1 -1
  11. package/dist/diagnostics/codes.d.ts +6 -0
  12. package/dist/diagnostics/codes.d.ts.map +1 -1
  13. package/dist/diagnostics/codes.js +25 -1
  14. package/dist/diagnostics/codes.js.map +1 -1
  15. package/dist/diagnostics/types.d.ts +1 -1
  16. package/dist/diagnostics/types.d.ts.map +1 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +3 -3
  20. package/dist/index.js.map +1 -1
  21. package/dist/limits.d.ts +16 -0
  22. package/dist/limits.d.ts.map +1 -0
  23. package/dist/limits.js +16 -0
  24. package/dist/limits.js.map +1 -0
  25. package/dist/parser/blocks.d.ts +1 -1
  26. package/dist/parser/blocks.d.ts.map +1 -1
  27. package/dist/parser/blocks.js +425 -117
  28. package/dist/parser/blocks.js.map +1 -1
  29. package/dist/parser/directive-line.d.ts +8 -2
  30. package/dist/parser/directive-line.d.ts.map +1 -1
  31. package/dist/parser/directive-line.js +23 -6
  32. package/dist/parser/directive-line.js.map +1 -1
  33. package/dist/parser/expression-lexer.d.ts +19 -1
  34. package/dist/parser/expression-lexer.d.ts.map +1 -1
  35. package/dist/parser/expression-lexer.js +31 -2
  36. package/dist/parser/expression-lexer.js.map +1 -1
  37. package/dist/parser/expression-parser.d.ts.map +1 -1
  38. package/dist/parser/expression-parser.js +58 -16
  39. package/dist/parser/expression-parser.js.map +1 -1
  40. package/dist/parser/frontmatter.d.ts.map +1 -1
  41. package/dist/parser/frontmatter.js +65 -7
  42. package/dist/parser/frontmatter.js.map +1 -1
  43. package/dist/parser/lexical-primitives.d.ts +2 -2
  44. package/dist/parser/lexical-primitives.js +2 -2
  45. package/dist/parser/lines.d.ts.map +1 -1
  46. package/dist/parser/lines.js +9 -2
  47. package/dist/parser/lines.js.map +1 -1
  48. package/dist/parser/markdown.d.ts.map +1 -1
  49. package/dist/parser/markdown.js +39 -13
  50. package/dist/parser/markdown.js.map +1 -1
  51. package/dist/parser/serializer-safety.d.ts +4 -3
  52. package/dist/parser/serializer-safety.d.ts.map +1 -1
  53. package/dist/parser/serializer-safety.js +4 -3
  54. package/dist/parser/serializer-safety.js.map +1 -1
  55. package/dist/validation/validate.d.ts.map +1 -1
  56. package/dist/validation/validate.js +5 -4
  57. package/dist/validation/validate.js.map +1 -1
  58. package/package.json +1 -2
@@ -1,8 +1,10 @@
1
1
  import { Diagnostics } from "../diagnostics/codes.js";
2
- import { matchDirectiveLine, SIMPLE_PRESENTATION_DIRECTIVES } from "./directive-line.js";
2
+ import { matchDirectiveLine, REGISTERED_DIRECTIVES, SIMPLE_PRESENTATION_DIRECTIVES } from "./directive-line.js";
3
3
  import { joinLineText, lineEnd, lineStart, positionAt } from "./lines.js";
4
+ import { MAX_BLOCK_DEPTH } from "../limits.js";
4
5
  import { parseProseChunk } from "./markdown.js";
5
6
  import { ExpressionSyntaxError, parseExpression } from "./expression-parser.js";
7
+ import { RESERVED_VARIABLE_NAMES } from "./expression-lexer.js";
6
8
  import { findLastUnescapedArrow, SEPARATOR_WHITESPACE_PATTERN, SEPARATOR_WHITESPACE_SOURCE } from "./lexical-primitives.js";
7
9
  function spanOf(line) {
8
10
  return { start: lineStart(line), end: lineEnd(line) };
@@ -46,15 +48,24 @@ function tryParseExpression(argsText, line, argsStartColumn, diagnostics) {
46
48
  }
47
49
  }
48
50
  const PARAM_TOKEN_PATTERN = /^([A-Za-z_][A-Za-z0-9_]*)=(.+)$/;
51
+ /**
52
+ * A string-keyed dictionary with no prototype, so an author-supplied key such
53
+ * as `constructor` or `__proto__` is ordinary data: it is never confused with
54
+ * an inherited property and assigning it never changes the dictionary's
55
+ * prototype.
56
+ */
57
+ function dictionary() {
58
+ return Object.create(null);
59
+ }
49
60
  function tokenizePresentationArgs(argsText) {
50
- const params = {};
51
- const paramValueRanges = {};
52
- const paramOccurrences = {};
61
+ const params = dictionary();
62
+ const paramValueRanges = dictionary();
63
+ const paramOccurrences = dictionary();
53
64
  const positional = [];
54
65
  const positionalRanges = [];
55
66
  const tokens = [];
56
67
  let unterminatedQuoteAt;
57
- // A small deterministic single-pass scanner (docs/PROJECT_SPEC.md
68
+ // A small deterministic single-pass scanner (docs/CORE_SPEC.md
58
69
  // Section 14, Quoted Presentation positional arguments) — replaces the
59
70
  // previous plain `argsText.matchAll(/\S+/g)` regex scan, which could not
60
71
  // express quote-aware token grouping, escape decoding, or precise
@@ -81,7 +92,7 @@ function tokenizePresentationArgs(argsText) {
81
92
  }
82
93
  const tokenStart = i;
83
94
  if (ch === '"') {
84
- // Quoted positional token (docs/PROJECT_SPEC.md Section 14) — always
95
+ // Quoted positional token (docs/CORE_SPEC.md Section 14) — always
85
96
  // positional, NEVER passed through `PARAM_TOKEN_PATTERN`: lexical
86
97
  // grouping (this whole quoted token) is determined before named-
87
98
  // parameter classification is ever considered, so a token like
@@ -122,7 +133,7 @@ function tokenizePresentationArgs(argsText) {
122
133
  // No authored separator whitespace was found between this quoted
123
134
  // token's closing quote and whatever comes next — shell-style
124
135
  // concatenation is not implemented as a general grammar feature
125
- // (docs/PROJECT_SPEC.md Section 14), but this token must still end
136
+ // (docs/CORE_SPEC.md Section 14), but this token must still end
126
137
  // deterministically somewhere: it simply continues, raw and
127
138
  // undecoded, through to the next separator whitespace, exactly like
128
139
  // an ordinary token already does. This only matters for the
@@ -160,14 +171,14 @@ function tokenizePresentationArgs(argsText) {
160
171
  }
161
172
  }
162
173
  // A safe, trivia-aware removal range for a named parameter exists only
163
- // when its key occurs EXACTLY ONCE (docs/PROJECT_SPEC.md Section 14) —
174
+ // when its key occurs EXACTLY ONCE (docs/CORE_SPEC.md Section 14) —
164
175
  // with 2+ occurrences, no single range could delete "the property"
165
176
  // without either silently reviving an earlier duplicate (deleting only
166
177
  // the effective last occurrence) or requiring multi-range deletion, so
167
178
  // no range is produced for that key at all. Reuses the token adjacency
168
179
  // already scanned above (one extra pass over the small in-memory
169
180
  // `tokens` array — not a second scan of `argsText`, not a new grammar).
170
- const paramRemovalRanges = {};
181
+ const paramRemovalRanges = dictionary();
171
182
  tokens.forEach((tok, index) => {
172
183
  if (tok.key === undefined || paramOccurrences[tok.key] !== 1)
173
184
  return;
@@ -191,7 +202,7 @@ function tokenizePresentationArgs(argsText) {
191
202
  paramRemovalRanges[tok.key] = { start: previous.end, end: tok.end };
192
203
  }
193
204
  });
194
- // The contiguous positional run (docs/PROJECT_SPEC.md Section 14) — a
205
+ // The contiguous positional run (docs/CORE_SPEC.md Section 14) — a
195
206
  // strict, additive generalization of the single-positional-token case
196
207
  // above, reusing the same `tokens` adjacency data with no second scan.
197
208
  // Populated iff at least one positional token exists AND every token
@@ -240,6 +251,9 @@ function parseNumericParam(text) {
240
251
  return NUMBER_PATTERN.test(text) ? Number(text) : undefined;
241
252
  }
242
253
  const KNOWN_CAMERA_ACTIONS = new Set(["zoom"]);
254
+ /** Not an AST type — unlike Camera's `action`, Sprite's action is encoded entirely by the command's `type` discriminant (docs/CORE_SPEC.md Section 31.2). */
255
+ const KNOWN_SPRITE_ACTIONS = new Set(["show", "hide"]);
256
+ const KNOWN_SPRITE_POSITIONS = new Set(["left", "center", "right"]);
243
257
  /**
244
258
  * Parses, validates, and normalizes a presentation directive into a typed
245
259
  * PresentationCommand (see ast/presentation.ts). Unit strings like `6s` and
@@ -250,7 +264,7 @@ const KNOWN_CAMERA_ACTIONS = new Set(["zoom"]);
250
264
  */
251
265
  function parsePresentation(kind, argsText, span, line, argsStartColumn, diagnostics) {
252
266
  const tokenized = tokenizePresentationArgs(argsText);
253
- // An unclosed quoted positional token (docs/PROJECT_SPEC.md Section 14,
267
+ // An unclosed quoted positional token (docs/CORE_SPEC.md Section 14,
254
268
  // Quoted Presentation positional arguments) reuses the existing AT1301
255
269
  // (`malformedPresentation`) — no new diagnostic code — with a span from
256
270
  // the opening quote through the end of this physical directive line
@@ -267,28 +281,30 @@ function parsePresentation(kind, argsText, span, line, argsStartColumn, diagnost
267
281
  return undefined;
268
282
  }
269
283
  const { value, params, paramValueRanges, paramRemovalRanges, positionalRanges, contiguousPositionalRange } = tokenized;
270
- // Absolute source spans for every recognized parameter value (docs/PROJECT_SPEC.md
284
+ // Absolute source spans for every recognized parameter value (docs/CORE_SPEC.md
271
285
  // Section 25.36) — computed once, reused by every return below, always
272
286
  // present (an empty record when the directive has no named parameters).
273
- const parameterValueSpans = {};
274
- for (const [key, range] of Object.entries(paramValueRanges)) {
275
- parameterValueSpans[key] = {
287
+ // Built with `Object.fromEntries` (own data properties) so a key such as
288
+ // `__proto__` is recorded rather than silently dropped.
289
+ const parameterValueSpans = Object.fromEntries(Object.entries(paramValueRanges).map(([key, range]) => [
290
+ key,
291
+ {
276
292
  start: positionAt(line, argsStartColumn + range.start),
277
293
  end: positionAt(line, argsStartColumn + range.end)
278
- };
279
- }
280
- // Absolute, duplicate-safe removal spans (docs/PROJECT_SPEC.md Section
294
+ }
295
+ ]));
296
+ // Absolute, duplicate-safe removal spans (docs/CORE_SPEC.md Section
281
297
  // 14) — present only for a key with exactly one authored occurrence;
282
298
  // computed once, reused by every return below.
283
- const parameterRemovalSpans = {};
284
- for (const [key, range] of Object.entries(paramRemovalRanges)) {
285
- parameterRemovalSpans[key] = {
299
+ const parameterRemovalSpans = Object.fromEntries(Object.entries(paramRemovalRanges).map(([key, range]) => [
300
+ key,
301
+ {
286
302
  start: positionAt(line, argsStartColumn + range.start),
287
303
  end: positionAt(line, argsStartColumn + range.end)
288
- };
289
- }
304
+ }
305
+ ]));
290
306
  // The positional value has a safe, contiguous source span only when
291
- // there is exactly one positional token (docs/PROJECT_SPEC.md Section
307
+ // there is exactly one positional token (docs/CORE_SPEC.md Section
292
308
  // 14) — with zero or two-or-more, `value` either doesn't exist or is a
293
309
  // synthetic join of non-contiguous source text, so no span is produced.
294
310
  const positionalValueSpan = positionalRanges.length === 1
@@ -297,7 +313,7 @@ function parsePresentation(kind, argsText, span, line, argsStartColumn, diagnost
297
313
  end: positionAt(line, argsStartColumn + positionalRanges[0].end)
298
314
  }
299
315
  : undefined;
300
- // Absolute contiguous-positional-run span (docs/PROJECT_SPEC.md Section
316
+ // Absolute contiguous-positional-run span (docs/CORE_SPEC.md Section
301
317
  // 14) — a strict, additive generalization of `positionalValueSpan`;
302
318
  // never derived when `contiguousPositionalRange` is `undefined` (zero
303
319
  // positional tokens, or a named token interrupting the run).
@@ -308,13 +324,13 @@ function parsePresentation(kind, argsText, span, line, argsStartColumn, diagnost
308
324
  }
309
325
  : undefined;
310
326
  // The position immediately after the last non-whitespace character of
311
- // `argsText` (docs/PROJECT_SPEC.md Section 14) — `argsText` is already
327
+ // `argsText` (docs/CORE_SPEC.md Section 14) — `argsText` is already
312
328
  // `.trimEnd()`-ed by `matchDirectiveLine`, so `argsStartColumn +
313
329
  // argsText.length` lands exactly there, before any trailing line
314
330
  // whitespace/terminator. Never derived from the whole-node `span.end`,
315
331
  // which includes that trailing whitespace.
316
332
  const argumentsEndPosition = positionAt(line, argsStartColumn + argsText.length);
317
- // Whole-command removal span (docs/PROJECT_SPEC.md Section 14) — always
333
+ // Whole-command removal span (docs/CORE_SPEC.md Section 14) — always
318
334
  // starts at the directive's own span.start (never adjusted backward
319
335
  // into preceding source); extends span.end by exactly this directive's
320
336
  // own physical line's terminator width (0 at true EOF, 1 for `\n`, 2 for
@@ -336,7 +352,7 @@ function parsePresentation(kind, argsText, span, line, argsStartColumn, diagnost
336
352
  * text (AT1301); a lexically-valid literal that converts to a non-finite
337
353
  * number (e.g. an extreme digit run, or a finite seconds amount that
338
354
  * overflows only after the `* 1000` conversion) is a distinct condition
339
- * reported as AT1302 (docs/PROJECT_SPEC.md Section 24).
355
+ * reported as AT1302 (docs/CORE_SPEC.md Section 24).
340
356
  */
341
357
  function failNotFinite() {
342
358
  diagnostics.push(Diagnostics.presentationNumericNotFinite(span));
@@ -441,9 +457,56 @@ function parsePresentation(kind, argsText, span, line, argsStartColumn, diagnost
441
457
  commandRemovalSpan
442
458
  };
443
459
  }
460
+ case "sprite": {
461
+ if (value === undefined)
462
+ return fail("@sprite requires an action");
463
+ if (!KNOWN_SPRITE_ACTIONS.has(value)) {
464
+ return fail(`unsupported sprite action "${value}"`);
465
+ }
466
+ if (params["id"] === undefined)
467
+ return fail(`@sprite ${value} requires "id="`);
468
+ const id = params["id"];
469
+ if (value === "hide") {
470
+ return {
471
+ type: "Presentation",
472
+ command: { type: "HideSprite", id },
473
+ span,
474
+ parameterValueSpans,
475
+ positionalValueSpan,
476
+ argumentsEndPosition,
477
+ parameterRemovalSpans,
478
+ contiguousPositionalSpan,
479
+ commandRemovalSpan
480
+ };
481
+ }
482
+ // value === "show" — the only other member of KNOWN_SPRITE_ACTIONS.
483
+ if (params["image"] === undefined)
484
+ return fail('@sprite show requires "image="');
485
+ const image = params["image"];
486
+ if (params["position"] === undefined)
487
+ return fail('@sprite show requires "position="');
488
+ if (!KNOWN_SPRITE_POSITIONS.has(params["position"])) {
489
+ return fail(`unsupported position "${params["position"]}"`);
490
+ }
491
+ const position = params["position"];
492
+ return {
493
+ type: "Presentation",
494
+ command: { type: "ShowSprite", id, image, position },
495
+ span,
496
+ parameterValueSpans,
497
+ positionalValueSpan,
498
+ argumentsEndPosition,
499
+ parameterRemovalSpans,
500
+ contiguousPositionalSpan,
501
+ commandRemovalSpan
502
+ };
503
+ }
444
504
  }
445
505
  }
446
- const SET_PATTERN = /^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.+)$/;
506
+ // `\S.*` (not `.+`) after the separator keeps `\s*` and the expression from
507
+ // overlapping, so the pattern cannot backtrack across whitespace. `args` are
508
+ // trimmed and never contain a line terminator, so it accepts the same lines.
509
+ const SET_PATTERN = /^([A-Za-z_]\w*)\s*=\s*(\S.*)$/;
447
510
  function parseSet(directive, line, diagnostics) {
448
511
  const match = SET_PATTERN.exec(directive.args);
449
512
  if (!match) {
@@ -454,9 +517,28 @@ function parseSet(directive, line, diagnostics) {
454
517
  const exprText = match[2];
455
518
  const exprOffsetInArgs = directive.args.length - exprText.length;
456
519
  const base = positionAt(line, directive.argsStartColumn + exprOffsetInArgs);
520
+ const nameSourceSpan = {
521
+ start: positionAt(line, directive.argsStartColumn),
522
+ end: positionAt(line, directive.argsStartColumn + name.length)
523
+ };
524
+ if (RESERVED_VARIABLE_NAMES.has(name)) {
525
+ diagnostics.push(Diagnostics.malformedExpression(`"${name}" is a reserved word and cannot be a variable name`, nameSourceSpan));
526
+ return undefined;
527
+ }
528
+ const expressionSourceSpan = {
529
+ start: base,
530
+ end: positionAt(line, directive.argsStartColumn + directive.args.length)
531
+ };
457
532
  try {
458
533
  const expression = parseExpression(exprText, base);
459
- return { type: "Set", name, expression, span: spanOf(line) };
534
+ return {
535
+ type: "Set",
536
+ name,
537
+ expression,
538
+ span: spanOf(line),
539
+ nameSourceSpan,
540
+ expressionSourceSpan
541
+ };
460
542
  }
461
543
  catch (err) {
462
544
  if (err instanceof ExpressionSyntaxError) {
@@ -466,6 +548,168 @@ function parseSet(directive, line, diagnostics) {
466
548
  throw err;
467
549
  }
468
550
  }
551
+ // ---------------------------------------------------------------------------
552
+ // Dialogue: @say
553
+ // ---------------------------------------------------------------------------
554
+ /**
555
+ * Recognizes a Dialogue header token (docs/CORE_SPEC.md Section 32.6).
556
+ * Deliberately `(.*)` rather than Presentation's `(.+)` (`PARAM_TOKEN_PATTERN`
557
+ * above): `speaker=` with nothing after it must still be recognized as *the*
558
+ * speaker token, with an empty value, so it is diagnosed as "missing/empty
559
+ * speaker" (category 1) rather than falling through to "unsupported header
560
+ * token" (category 2) — Section 32.11's locked diagnostic precedence.
561
+ */
562
+ const SAY_SPEAKER_TOKEN_PATTERN = /^speaker=(.*)$/;
563
+ const SAY_SPEAKER_PREFIX_LENGTH = "speaker=".length;
564
+ /**
565
+ * Parses `@say`'s header argument text (docs/CORE_SPEC.md Section 32.6/32.7).
566
+ * A small, Dialogue-local scanner — deliberately NOT `tokenizePresentationArgs`,
567
+ * which Section 14 locks to the seven Presentation directive families only
568
+ * and which Dialogue (not a PresentationCommand, Section 32.12) must not
569
+ * extend. Reuses only the shared `SEPARATOR_WHITESPACE_PATTERN` token-boundary
570
+ * primitive both already rely on. `@say` has no positional-argument token at
571
+ * all (Section 32.6): every token must be `speaker=...`-shaped, or the whole
572
+ * header is malformed. A duplicate `speaker=` is not an error — the last
573
+ * occurrence wins for both the semantic value and `speakerSourceSpan`
574
+ * (Section 32.6).
575
+ */
576
+ function parseDialogueHeader(directive, line, diagnostics) {
577
+ const argsText = directive.args;
578
+ let speakerValue;
579
+ let speakerValueStart = -1;
580
+ let speakerValueEnd = -1;
581
+ let unsupportedToken;
582
+ let pos = 0;
583
+ while (pos < argsText.length) {
584
+ while (pos < argsText.length && SEPARATOR_WHITESPACE_PATTERN.test(argsText[pos]))
585
+ pos += 1;
586
+ if (pos >= argsText.length)
587
+ break;
588
+ const tokenStart = pos;
589
+ while (pos < argsText.length && !SEPARATOR_WHITESPACE_PATTERN.test(argsText[pos]))
590
+ pos += 1;
591
+ const tokenEnd = pos;
592
+ const match = SAY_SPEAKER_TOKEN_PATTERN.exec(argsText.slice(tokenStart, tokenEnd));
593
+ if (match) {
594
+ // Last-occurrence-wins (docs/CORE_SPEC.md Section 32.6), mirroring the
595
+ // compiler's existing duplicate-named-parameter convention (Section 14).
596
+ speakerValue = match[1];
597
+ speakerValueStart = tokenStart + SAY_SPEAKER_PREFIX_LENGTH;
598
+ speakerValueEnd = tokenEnd;
599
+ }
600
+ else {
601
+ // First unsupported token only — Section 32.11's diagnostic precedence
602
+ // reports at most one AT1301 per malformed `@say`, so later unsupported
603
+ // tokens (if any) are never separately diagnosed.
604
+ unsupportedToken ??= { start: tokenStart, end: tokenEnd };
605
+ }
606
+ }
607
+ // Category 1 (missing/empty speaker) takes precedence over category 2
608
+ // (unsupported header token) regardless of token order — Section 32.11.
609
+ if (speakerValue === undefined || speakerValue.trim().length === 0) {
610
+ diagnostics.push(Diagnostics.malformedDialogue("missing or empty speaker", spanOf(line)));
611
+ return { ok: false, speaker: "", speakerSourceSpan: undefined };
612
+ }
613
+ if (unsupportedToken) {
614
+ diagnostics.push(Diagnostics.malformedDialogue("unsupported header token", {
615
+ start: positionAt(line, directive.argsStartColumn + unsupportedToken.start),
616
+ end: positionAt(line, directive.argsStartColumn + unsupportedToken.end)
617
+ }));
618
+ return { ok: false, speaker: "", speakerSourceSpan: undefined };
619
+ }
620
+ return {
621
+ ok: true,
622
+ speaker: speakerValue,
623
+ speakerSourceSpan: {
624
+ start: positionAt(line, directive.argsStartColumn + speakerValueStart),
625
+ end: positionAt(line, directive.argsStartColumn + speakerValueEnd)
626
+ }
627
+ };
628
+ }
629
+ /** A zero-length line, or a line containing only spaces and/or tabs (docs/CORE_SPEC.md Section 32.3's exact blank-line predicate). Deliberately `/^[ \t]*$/`, not `.trim()`: `String.prototype.trim()` also strips other Unicode whitespace (e.g. U+00A0, U+2028/U+2029) that Section 32.3 does not — a line containing only such characters must remain non-blank Markdown content, not leading trivia or a body terminator. */
630
+ const BLANK_LINE_PATTERN = /^[ \t]*$/;
631
+ function isBlankLine(line) {
632
+ return BLANK_LINE_PATTERN.test(line.text);
633
+ }
634
+ /**
635
+ * Parses one Dialogue block starting at the `@say` header line at `openIndex`
636
+ * (docs/CORE_SPEC.md Section 32). Body-boundary scan (Section 32.3) always
637
+ * runs, even when the header is malformed, so recovery is deterministic
638
+ * (Section 32.11): the complete claimed extent — header plus every scanned
639
+ * body line — is dropped together on any failure; the terminating blank
640
+ * line, directive line, `@scene`, or EOF is never consumed.
641
+ */
642
+ function parseDialogue(lines, openIndex, diagnostics) {
643
+ const headerLine = lines[openIndex];
644
+ const directive = matchDirectiveLine(headerLine.text);
645
+ const header = parseDialogueHeader(directive, headerLine, diagnostics);
646
+ let i = openIndex + 1;
647
+ while (i < lines.length && isBlankLine(lines[i]))
648
+ i += 1; // leading trivia (Section 32.3 step 1)
649
+ const bodyStart = i;
650
+ while (i < lines.length &&
651
+ !isBlankLine(lines[i]) &&
652
+ !matchDirectiveLine(lines[i].text) // a directive line, @scene included, ends the body
653
+ ) {
654
+ i += 1;
655
+ }
656
+ const bodyEnd = i;
657
+ if (!header.ok) {
658
+ return { block: undefined, nextIndex: bodyEnd };
659
+ }
660
+ if (bodyStart === bodyEnd) {
661
+ const headerEnd = lineEnd(headerLine);
662
+ diagnostics.push(Diagnostics.malformedDialogue("missing dialogue content", { start: headerEnd, end: headerEnd }));
663
+ return { block: undefined, nextIndex: bodyEnd };
664
+ }
665
+ const bodyLines = lines.slice(bodyStart, bodyEnd);
666
+ const first = bodyLines[0];
667
+ const text = joinLineText(bodyLines);
668
+ // Buffered, not pushed to `diagnostics` directly: `parseProseChunk` can
669
+ // emit its own warnings (e.g. AT3001 for an unsupported construct falling
670
+ // back to plain text) as a side effect of parsing, independently of
671
+ // whether the resulting blocks even satisfy Dialogue's cardinality rule.
672
+ // Section 32.11 locks exactly one diagnostic per malformed `@say` — so
673
+ // these are discarded on every malformed-body path below and merged into
674
+ // `diagnostics` only once the body is confirmed to be a valid single
675
+ // Paragraph.
676
+ const bodyDiagnostics = [];
677
+ const blocks = parseProseChunk(text, { startLine: first.number, startOffset: first.startOffset }, bodyDiagnostics);
678
+ if (blocks.length === 0) {
679
+ const headerEnd = lineEnd(headerLine);
680
+ diagnostics.push(Diagnostics.malformedDialogue("missing dialogue content", { start: headerEnd, end: headerEnd }));
681
+ return { block: undefined, nextIndex: bodyEnd };
682
+ }
683
+ if (blocks.length > 1) {
684
+ // The complete claimed body extent (Section 32.11) is the physical
685
+ // bodyLines range, not the first/last parsed block's own span — a
686
+ // parsed block's span can start after leading indentation, which would
687
+ // otherwise silently exclude claimed body trivia from the diagnostic.
688
+ diagnostics.push(Diagnostics.malformedDialogue("dialogue content must be a single paragraph", {
689
+ start: lineStart(first),
690
+ end: lineEnd(bodyLines.at(-1))
691
+ }));
692
+ return { block: undefined, nextIndex: bodyEnd };
693
+ }
694
+ const only = blocks[0];
695
+ if (only.type !== "Paragraph") {
696
+ diagnostics.push(Diagnostics.malformedDialogue("dialogue content must be a paragraph, not a heading", only.span));
697
+ return { block: undefined, nextIndex: bodyEnd };
698
+ }
699
+ for (const diagnostic of bodyDiagnostics)
700
+ diagnostics.push(diagnostic);
701
+ return {
702
+ block: {
703
+ type: "Dialogue",
704
+ speaker: header.speaker,
705
+ content: only.children,
706
+ span: { start: lineStart(headerLine), end: only.span.end },
707
+ speakerSourceSpan: header.speakerSourceSpan,
708
+ contentSourceSpan: only.span
709
+ },
710
+ nextIndex: bodyEnd
711
+ };
712
+ }
469
713
  /** Bullet marker introducing a choice item: `* ...` or `- ...`. */
470
714
  const CHOICE_BULLET_PATTERN = /^(\s*)[*-]\s+/;
471
715
  /**
@@ -491,6 +735,16 @@ function parseChoice(lines, openIndex, diagnostics) {
491
735
  if (directive && (directive.name === "end" || directive.name === "scene")) {
492
736
  break;
493
737
  }
738
+ // A directive-shaped line inside a choice body can never be an item, and
739
+ // is skipped like any non-item line — but it is authored structure, so it
740
+ // is reported (unlike ordinary narrative text, which stays a silent skip).
741
+ if (directive) {
742
+ diagnostics.push(REGISTERED_DIRECTIVES.has(directive.name)
743
+ ? Diagnostics.misplacedDirective(directive.name, "inside a choice", spanOf(line))
744
+ : Diagnostics.unknownDirective(directive.name, spanOf(line)));
745
+ idx += 1;
746
+ continue;
747
+ }
494
748
  const bulletMatch = CHOICE_BULLET_PATTERN.exec(line.text);
495
749
  if (!bulletMatch) {
496
750
  idx += 1;
@@ -514,7 +768,7 @@ function parseChoice(lines, openIndex, diagnostics) {
514
768
  // Display text is only the "if" delimiter's own condition-grammar is
515
769
  // applied to the tail *after* the target — so an "if" appearing in
516
770
  // display text (before the arrow) can never be mistaken for one.
517
- const displayText = content.slice(0, arrowIndex).trim().replace(/\\->/g, "->");
771
+ const displayText = content.slice(0, arrowIndex).trim().replaceAll(String.raw `\->`, "->");
518
772
  const tailStart = arrowIndex + 2;
519
773
  const tailRaw = content.slice(tailStart);
520
774
  const tailLeadingWs = tailRaw.length - tailRaw.trimStart().length;
@@ -574,7 +828,7 @@ function parseChoice(lines, openIndex, diagnostics) {
574
828
  nextIndex: idx
575
829
  };
576
830
  }
577
- function parseConditional(lines, openIndex, diagnostics) {
831
+ function parseConditional(lines, openIndex, diagnostics, depth) {
578
832
  const openLine = lines[openIndex];
579
833
  const branches = [];
580
834
  let idx = openIndex;
@@ -593,7 +847,7 @@ function parseConditional(lines, openIndex, diagnostics) {
593
847
  }
594
848
  : undefined;
595
849
  idx += 1;
596
- const seq = parseBlockSequence(lines, idx, diagnostics, new Set(["elseif", "else", "end"]));
850
+ const seq = parseBlockSequence(lines, idx, diagnostics, new Set(["elseif", "else", "end"]), depth + 1);
597
851
  const branchSpan = {
598
852
  start: lineStart(branchLine),
599
853
  end: seq.blocks.length > 0 ? seq.blocks[seq.blocks.length - 1].span.end : lineEnd(branchLine)
@@ -628,7 +882,7 @@ function parseConditional(lines, openIndex, diagnostics) {
628
882
  nextIndex: idx
629
883
  };
630
884
  }
631
- function parseVariant(lines, openIndex, diagnostics) {
885
+ function parseVariant(lines, openIndex, diagnostics, depth) {
632
886
  const openLine = lines[openIndex];
633
887
  const openDirective = matchDirectiveLine(openLine.text);
634
888
  const variantId = openDirective.args.trim();
@@ -649,8 +903,17 @@ function parseVariant(lines, openIndex, diagnostics) {
649
903
  let whenCount = 0;
650
904
  let lastEnd = lineEnd(openLine);
651
905
  let idx = openIndex + 1;
652
- let seq = parseBlockSequence(lines, idx, diagnostics, new Set(["when", "otherwise", "end"]));
906
+ let seq = parseBlockSequence(lines, idx, diagnostics, new Set(["when", "otherwise", "end"]), depth + 1);
653
907
  idx = seq.nextIndex;
908
+ // Content between the `@variant` header and the first branch belongs to no
909
+ // branch and is not kept in the AST; report the range that is ignored.
910
+ const ignored = seq.blocks;
911
+ if (ignored.length > 0) {
912
+ diagnostics.push(Diagnostics.variantContentBeforeBranch({
913
+ start: ignored[0].span.start,
914
+ end: ignored.at(-1).span.end
915
+ }));
916
+ }
654
917
  while (seq.stoppedBy === "when" || seq.stoppedBy === "otherwise") {
655
918
  const kind = seq.stoppedBy;
656
919
  const branchLine = lines[idx];
@@ -674,7 +937,7 @@ function parseVariant(lines, openIndex, diagnostics) {
674
937
  }
675
938
  : undefined;
676
939
  idx += 1;
677
- const bodySeq = parseBlockSequence(lines, idx, diagnostics, new Set(["when", "otherwise", "end"]));
940
+ const bodySeq = parseBlockSequence(lines, idx, diagnostics, new Set(["when", "otherwise", "end"]), depth + 1);
678
941
  const branchSpan = {
679
942
  start: lineStart(branchLine),
680
943
  end: bodySeq.blocks.length > 0
@@ -711,6 +974,47 @@ function parseVariant(lines, openIndex, diagnostics) {
711
974
  nextIndex: idx
712
975
  };
713
976
  }
977
+ /**
978
+ * Returns the index just past the `@end` that closes the construct opened at
979
+ * `openIndex`, counting nested `@if` / `@variant` / `@choice` openers (a `@choice` body is opaque
980
+ * up to its first `@end`, matching `parseChoice`). Stops
981
+ * early at a `@scene` line (scenes bound every construct) or end of input.
982
+ * Iterative on purpose: it is used on input too deep to recurse over.
983
+ */
984
+ function skipConstruct(lines, openIndex) {
985
+ let level = 0;
986
+ let inChoice = false;
987
+ for (let j = openIndex; j < lines.length; j++) {
988
+ const name = matchDirectiveLine(lines[j].text)?.name;
989
+ if (name === undefined)
990
+ continue;
991
+ if (name === "scene" && j > openIndex)
992
+ return j;
993
+ const step = skipStep(name, inChoice);
994
+ level += step.delta;
995
+ inChoice = step.inChoice;
996
+ if (step.delta < 0 && level === 0)
997
+ return j + 1;
998
+ }
999
+ return lines.length;
1000
+ }
1001
+ /**
1002
+ * How one directive changes `skipConstruct`'s scan: the nesting-level delta
1003
+ * and whether it is inside a `@choice` body. `parseChoice` treats its body as
1004
+ * opaque up to the first `@end`, so directive-shaped lines inside it open
1005
+ * nothing here either.
1006
+ */
1007
+ function skipStep(name, inChoice) {
1008
+ if (name === "end")
1009
+ return { delta: -1, inChoice: false };
1010
+ if (inChoice)
1011
+ return { delta: 0, inChoice };
1012
+ if (name === "choice")
1013
+ return { delta: 1, inChoice: true };
1014
+ if (name === "if" || name === "variant")
1015
+ return { delta: 1, inChoice };
1016
+ return { delta: 0, inChoice };
1017
+ }
714
1018
  /**
715
1019
  * Parses a run of lines into StoryBlocks until either a directive in
716
1020
  * `terminators` is reached, a `@scene` line is reached (scenes always
@@ -720,23 +1024,18 @@ function parseVariant(lines, openIndex, diagnostics) {
720
1024
  * conditional/variant branch bodies) — nesting falls out of recursive
721
1025
  * calls to parseConditional/parseVariant/parseChoice below.
722
1026
  */
723
- export function parseBlockSequence(lines, start, diagnostics, terminators) {
1027
+ export function parseBlockSequence(lines, start, diagnostics, terminators, depth = 0) {
724
1028
  const blocks = [];
725
1029
  let i = start;
726
1030
  let proseStart = -1;
727
1031
  const flushProse = (endExclusive) => {
728
- if (proseStart === -1)
729
- return;
730
- const chunkLines = lines.slice(proseStart, endExclusive);
1032
+ if (proseStart !== -1) {
1033
+ // Not `push(...run)`: a spread passes every element as a call argument,
1034
+ // which overflows the engine's argument/stack limit for a very long run.
1035
+ for (const block of parseProseRun(lines, proseStart, endExclusive, diagnostics))
1036
+ blocks.push(block);
1037
+ }
731
1038
  proseStart = -1;
732
- if (chunkLines.length === 0)
733
- return;
734
- const text = joinLineText(chunkLines);
735
- if (text.trim().length === 0)
736
- return;
737
- const first = chunkLines[0];
738
- const proseBlocks = parseProseChunk(text, { startLine: first.number, startOffset: first.startOffset }, diagnostics);
739
- blocks.push(...proseBlocks);
740
1039
  };
741
1040
  while (i < lines.length) {
742
1041
  const line = lines[i];
@@ -747,80 +1046,83 @@ export function parseBlockSequence(lines, start, diagnostics, terminators) {
747
1046
  i += 1;
748
1047
  continue;
749
1048
  }
1049
+ flushProse(i);
750
1050
  if (directive.name === "scene" || terminators.has(directive.name)) {
751
- flushProse(i);
752
1051
  return { blocks, nextIndex: i, stoppedBy: directive.name };
753
1052
  }
754
- flushProse(i);
755
- if (SIMPLE_PRESENTATION_SET.has(directive.name)) {
756
- const node = parsePresentation(directive.name, directive.args, spanOf(line), line, directive.argsStartColumn, diagnostics);
757
- if (node)
758
- blocks.push(node);
759
- i += 1;
760
- continue;
761
- }
762
- switch (directive.name) {
763
- case "set": {
764
- const node = parseSet(directive, line, diagnostics);
765
- if (node)
766
- blocks.push(node);
767
- i += 1;
768
- break;
769
- }
770
- case "goto": {
771
- const targetSourceSpan = {
1053
+ const parsed = parseDirectiveBlock(directive, lines, i, diagnostics, depth);
1054
+ if (parsed.block)
1055
+ blocks.push(parsed.block);
1056
+ i = parsed.nextIndex;
1057
+ }
1058
+ flushProse(i);
1059
+ return { blocks, nextIndex: i, stoppedBy: null };
1060
+ }
1061
+ /** Parses the prose lines `[startIndex, endExclusive)` (no directives) into Markdown blocks. */
1062
+ function parseProseRun(lines, startIndex, endExclusive, diagnostics) {
1063
+ const chunkLines = lines.slice(startIndex, endExclusive);
1064
+ if (chunkLines.length === 0)
1065
+ return [];
1066
+ const text = joinLineText(chunkLines);
1067
+ if (text.trim().length === 0)
1068
+ return [];
1069
+ const first = chunkLines[0];
1070
+ return parseProseChunk(text, { startLine: first.number, startOffset: first.startOffset }, diagnostics);
1071
+ }
1072
+ /**
1073
+ * Parses the single directive (or construct) starting at `lines[index]`.
1074
+ * `block` is undefined when the directive produces no node (an invalid
1075
+ * presentation/set, a stray terminator, an unknown directive, or an
1076
+ * over-deep construct that was skipped).
1077
+ */
1078
+ function parseDirectiveBlock(directive, lines, index, diagnostics, depth) {
1079
+ const line = lines[index];
1080
+ const single = (block) => ({ block, nextIndex: index + 1 });
1081
+ if (SIMPLE_PRESENTATION_SET.has(directive.name)) {
1082
+ return single(parsePresentation(directive.name, directive.args, spanOf(line), line, directive.argsStartColumn, diagnostics));
1083
+ }
1084
+ switch (directive.name) {
1085
+ case "set":
1086
+ return single(parseSet(directive, line, diagnostics));
1087
+ case "goto": {
1088
+ const node = {
1089
+ type: "Goto",
1090
+ target: directive.args.trim(),
1091
+ span: spanOf(line),
1092
+ targetSourceSpan: {
772
1093
  start: positionAt(line, directive.argsStartColumn),
773
1094
  end: positionAt(line, directive.argsStartColumn + directive.args.length)
774
- };
775
- const node = {
776
- type: "Goto",
777
- target: directive.args.trim(),
778
- span: spanOf(line),
779
- targetSourceSpan
780
- };
781
- blocks.push(node);
782
- i += 1;
783
- break;
784
- }
785
- case "if": {
786
- const { block, nextIndex } = parseConditional(lines, i, diagnostics);
787
- blocks.push(block);
788
- i = nextIndex;
789
- break;
790
- }
791
- case "variant": {
792
- const { block, nextIndex } = parseVariant(lines, i, diagnostics);
793
- blocks.push(block);
794
- i = nextIndex;
795
- break;
796
- }
797
- case "choice": {
798
- const { block, nextIndex } = parseChoice(lines, i, diagnostics);
799
- blocks.push(block);
800
- i = nextIndex;
801
- break;
802
- }
803
- case "elseif":
804
- case "else":
805
- case "end":
806
- case "when":
807
- case "otherwise": {
808
- // A terminator directive outside the construct it belongs to (the
809
- // matching construct parser above always intercepts these via
810
- // `terminators`). No dedicated diagnostic code covers this shape
811
- // of error in v0.1 — skip defensively rather than crash.
812
- i += 1;
813
- break;
814
- }
815
- default: {
816
- diagnostics.push(Diagnostics.unknownDirective(directive.name, spanOf(line)));
817
- i += 1;
818
- break;
819
- }
1095
+ }
1096
+ };
1097
+ return single(node);
820
1098
  }
1099
+ case "say":
1100
+ return parseDialogue(lines, index, diagnostics);
1101
+ case "if":
1102
+ case "variant":
1103
+ if (depth >= MAX_BLOCK_DEPTH) {
1104
+ diagnostics.push(Diagnostics.blocksNestedTooDeeply(MAX_BLOCK_DEPTH, spanOf(line)));
1105
+ return { block: undefined, nextIndex: skipConstruct(lines, index) };
1106
+ }
1107
+ return directive.name === "if"
1108
+ ? parseConditional(lines, index, diagnostics, depth)
1109
+ : parseVariant(lines, index, diagnostics, depth);
1110
+ case "choice":
1111
+ return parseChoice(lines, index, diagnostics);
1112
+ case "elseif":
1113
+ case "else":
1114
+ case "end":
1115
+ case "when":
1116
+ case "otherwise":
1117
+ // A terminator directive outside the construct it belongs to (the
1118
+ // matching construct parser always intercepts these via
1119
+ // `terminators`). The line is dropped as before; AT1009 reports it.
1120
+ diagnostics.push(Diagnostics.misplacedDirective(directive.name, "here", spanOf(line)));
1121
+ return single(undefined);
1122
+ default:
1123
+ diagnostics.push(Diagnostics.unknownDirective(directive.name, spanOf(line)));
1124
+ return single(undefined);
821
1125
  }
822
- flushProse(i);
823
- return { blocks, nextIndex: i, stoppedBy: null };
824
1126
  }
825
1127
  /**
826
1128
  * The deterministic id used for content appearing before the first explicit
@@ -835,7 +1137,7 @@ export const SYNTHETIC_LEADING_SCENE_ID = "main";
835
1137
  const DOCUMENT_START_POSITION = { line: 1, column: 1, offset: 0 };
836
1138
  /**
837
1139
  * The exact line-terminator bytes immediately following `position`
838
- * (docs/PROJECT_SPEC.md Section 25.35) — read directly from the already-
1140
+ * (docs/CORE_SPEC.md Section 25.35) — read directly from the already-
839
1141
  * computed `SourceLine.newlineLength` of the physical line `position`
840
1142
  * falls on, never rescanned from raw source. `""` when that line has no
841
1143
  * terminator at all (true end-of-file).
@@ -843,7 +1145,7 @@ const DOCUMENT_START_POSITION = { line: 1, column: 1, offset: 0 };
843
1145
  function lineEndingAt(lines, position) {
844
1146
  if (lines.length === 0)
845
1147
  return "";
846
- // `lines` may be a slice starting after stripped frontmatter (docs/PROJECT_SPEC.md
1148
+ // `lines` may be a slice starting after stripped frontmatter (docs/CORE_SPEC.md
847
1149
  // Section 12) — its own first entry's absolute `.number` (never assumed
848
1150
  // to be 1) anchors the lookup, so this remains correct regardless of
849
1151
  // whether `lines` is the full document or a post-frontmatter slice.
@@ -883,6 +1185,12 @@ export function parseScenes(lines, diagnostics) {
883
1185
  const sceneLine = lines[i];
884
1186
  const directive = matchDirectiveLine(sceneLine.text);
885
1187
  const sceneId = directive.args.trim();
1188
+ if (sceneId === "") {
1189
+ // Zero-width insertion point right after the `@scene` keyword
1190
+ // (`@` + name), where an id could be written.
1191
+ const insertion = positionAt(sceneLine, directive.name.length + 1);
1192
+ diagnostics.push(Diagnostics.emptySceneId({ start: insertion, end: insertion }));
1193
+ }
886
1194
  i += 1;
887
1195
  const seq = parseBlockSequence(lines, i, diagnostics, new Set());
888
1196
  const span = {