@rohal12/spindle 0.62.9 → 0.64.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.
@@ -14,7 +14,9 @@ export {
14
14
  completionContext,
15
15
  pieceOffset,
16
16
  pairMarkup,
17
+ macroCalls,
17
18
  isBlockMacro,
19
+ isSpecialPassage,
18
20
  parseStoryVariables,
19
21
  parseDeclarations,
20
22
  formatDiagnostic,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.62.9",
3
+ "version": "0.64.0",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
package/src/code-check.ts CHANGED
@@ -26,7 +26,12 @@
26
26
  * The arguments of macros that declare no parameters may be anything:
27
27
  * they are not checked.
28
28
  */
29
- import type { HtmlToken, Token } from './markup/tokens';
29
+ import type { HtmlToken, MacroToken, Token } from './markup/tokens';
30
+ import {
31
+ pairMarkup,
32
+ BRANCH_PARENT,
33
+ type PairMarkupOptions,
34
+ } from './markup/pair';
30
35
  import { isCodeAttribute, splitSigilTemplate } from './markup/code-attributes';
31
36
  import { analyzeMarkup, MarkupError, mapOffsets } from './markup/parse';
32
37
  import {
@@ -36,7 +41,12 @@ import {
36
41
  type JsGoal,
37
42
  } from './js-lexer';
38
43
  import type { ParsedCode } from './js-lexer';
39
- import type { ParameterDef, StringHolds } from './registry';
44
+ import {
45
+ branchParentLookup,
46
+ branchParents,
47
+ type ParameterDef,
48
+ type StringHolds,
49
+ } from './registry';
40
50
  import {
41
51
  MacroArgumentError,
42
52
  parseMacroArgs,
@@ -46,10 +56,11 @@ import {
46
56
  } from './components/macros/macro-args';
47
57
  import { subMacroParameters } from './components/macros/option-utils';
48
58
  import { splitArgSpans } from './components/macros/arg-utils';
49
- import { NameMap } from './utils/macro-names';
59
+ import { effectiveNamedDefinitions, NameMap } from './utils/macro-names';
50
60
  import { hasOwn } from './utils/namespace';
51
- import { isRawMacro } from './markup/ast';
61
+ import { isBuiltinBlockMacro, isRawMacro } from './markup/ast';
52
62
  import { sourcePositions } from './markup/line-column';
63
+ import { MarkupExpansionBudget } from './markup/expansion-budget';
53
64
 
54
65
  /** While a pass runs: the code it parsed so far, by goal and source. */
55
66
  let parses: Map<string, ParsedCode | CodeSyntaxError> | null = null;
@@ -156,6 +167,8 @@ interface MacroPiece extends LabeledPiece {
156
167
  export interface PassagePiece extends MacroPiece {
157
168
  kind: 'passage';
158
169
  name: string;
170
+ /** A known navigation target, rather than included/dialog content. */
171
+ navigation?: true;
159
172
  }
160
173
 
161
174
  /**
@@ -231,6 +244,45 @@ export interface ParametersOf {
231
244
  widget?(name: string): readonly WidgetParameter[] | undefined;
232
245
  /** Effective registration origin; absent metadata retains builtin defaults. */
233
246
  source?(name: string): 'builtin' | 'user' | undefined;
247
+ /** Pair branch arguments against the same effective definitions. */
248
+ pairing?: PairMarkupOptions;
249
+ }
250
+
251
+ /** A consumed branch uses its parent's argument contract, not standalone metadata. */
252
+ export function macroArgumentLookup(
253
+ tokens: readonly Token[],
254
+ parametersOf: ParametersOf,
255
+ ): (token: MacroToken) => 'condition' | 'branch' | 'invocation' {
256
+ let owners: Map<MacroToken, string> | undefined;
257
+ const parentsOf = parametersOf.pairing?.branchParents ?? branchParents;
258
+ return (token) => {
259
+ const name = token.name.toLowerCase();
260
+ if (parentsOf(name).length > 0 && !owners) {
261
+ owners = new Map();
262
+ const pending = [...pairMarkup(tokens, parametersOf.pairing).nodes];
263
+ while (pending.length) {
264
+ const node = pending.pop()!;
265
+ if (!node.body) continue;
266
+ for (const branch of node.body.branches) {
267
+ if (node.token.type === 'macro')
268
+ owners.set(branch.tag, node.token.name.toLowerCase());
269
+ for (const child of branch.children) pending.push(child);
270
+ }
271
+ for (const child of node.body.children) pending.push(child);
272
+ }
273
+ }
274
+ const owner = owners?.get(token);
275
+ if (owner !== undefined)
276
+ return CONDITION_MACROS.has(name) &&
277
+ owner === BRANCH_PARENT[name] &&
278
+ usesBuiltinSemantics(owner, parametersOf)
279
+ ? 'condition'
280
+ : 'branch';
281
+ return CONDITION_MACROS.has(name) &&
282
+ usesBuiltinSemantics(name, parametersOf)
283
+ ? 'condition'
284
+ : 'invocation';
285
+ };
234
286
  }
235
287
 
236
288
  /** Whether builtin-only interpretation still belongs to this implementation. */
@@ -255,6 +307,8 @@ export function executesRawBody(
255
307
  /** What the argument check needs to know of a macro (see MacroMetadata). */
256
308
  export interface MacroParameters {
257
309
  name: string;
310
+ block?: boolean;
311
+ subMacros?: readonly string[];
258
312
  source?: 'builtin' | 'user';
259
313
  parameters?: readonly ParameterDef[];
260
314
  interpolate?: boolean;
@@ -293,6 +347,7 @@ function withHolds(
293
347
  export function parameterLookup(
294
348
  macros: Iterable<MacroParameters>,
295
349
  ): ParametersOf {
350
+ const list = [...macros];
296
351
  const parameters = new NameMap<readonly ParameterDef[]>();
297
352
  const widgets = new NameMap<readonly WidgetParameter[]>();
298
353
  const sources = new NameMap<'builtin' | 'user'>();
@@ -302,7 +357,7 @@ export function parameterLookup(
302
357
  interpolate,
303
358
  widget,
304
359
  source,
305
- } of macros) {
360
+ } of list) {
306
361
  sources.set(name, source ?? 'user');
307
362
  if (params)
308
363
  parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
@@ -321,6 +376,23 @@ export function parameterLookup(
321
376
  };
322
377
  if (widgets.size > 0) lookup.widget = (name) => widgets.get(name);
323
378
  lookup.source = (name) => sources.get(name);
379
+ const definitions = new NameMap(
380
+ effectiveNamedDefinitions([
381
+ ...list.filter((macro) => !macro.widget),
382
+ ...list.filter((macro) => macro.widget),
383
+ ]).map((macro) => [macro.name, macro]),
384
+ );
385
+ lookup.pairing = {
386
+ isBlock: (name) =>
387
+ definitions.get(name)?.block ?? isBuiltinBlockMacro(name),
388
+ isRaw: (name) => isRawMacro(name, widgets.has(name)),
389
+ branchParents: branchParentLookup(
390
+ [...definitions.values()].map((macro) => ({
391
+ ...macro,
392
+ subMacros: [...(macro.subMacros ?? [])],
393
+ })),
394
+ ),
395
+ };
324
396
  return lookup;
325
397
  }
326
398
 
@@ -365,6 +437,7 @@ export function* codeAndText(
365
437
  tokens: readonly Token[],
366
438
  parametersOf: ParametersOf,
367
439
  ): Generator<Piece> {
440
+ const argumentRole = macroArgumentLookup(tokens, parametersOf);
368
441
  // Only a plain-text body is read here: raw JavaScript in {do}, or a
369
442
  // passage name in {dialog}. Start at the opener and stop at any markup,
370
443
  // including a nested opener, rather than rescanning the token prefix.
@@ -387,6 +460,9 @@ export function* codeAndText(
387
460
  offset: token.targetStart,
388
461
  length: token.targetEnd - token.targetStart,
389
462
  macro: 'link',
463
+ ...(usesBuiltinSemantics('link', parametersOf) && {
464
+ navigation: true as const,
465
+ }),
390
466
  label: src.slice(token.start, token.end),
391
467
  };
392
468
  // The label is markup too (the link renders as `{link}`)
@@ -427,6 +503,8 @@ export function* codeAndText(
427
503
  }
428
504
  } else if (token.type === 'macro' && !token.isClose) {
429
505
  const name = token.name.toLowerCase();
506
+ const role = argumentRole(token);
507
+ if (role === 'branch') continue;
430
508
  const widget = parametersOf.widget?.(name);
431
509
  if (executesRawBody(name, parametersOf)) {
432
510
  const close = closeOfTextBody(t, name);
@@ -465,10 +543,7 @@ export function* codeAndText(
465
543
  if (!args) continue;
466
544
  const label = `{${token.name} ${args}}`;
467
545
  const argsAt = token.argsStart;
468
- if (
469
- CONDITION_MACROS.has(name) &&
470
- usesBuiltinSemantics(name, parametersOf)
471
- ) {
546
+ if (role === 'condition') {
472
547
  yield {
473
548
  kind: 'code',
474
549
  code: args,
@@ -479,7 +554,16 @@ export function* codeAndText(
479
554
  continue;
480
555
  }
481
556
  const params = parametersOf(name);
482
- if (params) yield* argPieces(args, argsAt, params, token.name, label);
557
+ if (params) {
558
+ const navigation = usesBuiltinSemantics(name, parametersOf)
559
+ ? name === 'goto' || name === 'link'
560
+ ? ['passage']
561
+ : name === 'watch'
562
+ ? ['goto']
563
+ : []
564
+ : [];
565
+ yield* argPieces(args, argsAt, params, token.name, label, navigation);
566
+ }
483
567
  if (widget) yield* widgetPieces(args, argsAt, widget, token.name, label);
484
568
  }
485
569
  }
@@ -518,6 +602,7 @@ export function* passagePiecesOf(
518
602
  (i) => i,
519
603
  undefined,
520
604
  locate,
605
+ new MarkupExpansionBudget(src.length),
521
606
  );
522
607
  }
523
608
 
@@ -535,6 +620,7 @@ function* expand(
535
620
  toRoot: (offset: number) => number,
536
621
  where: string | undefined,
537
622
  locate: ReturnType<typeof sourcePositions>,
623
+ budget: MarkupExpansionBudget,
538
624
  ): Generator<Piece> {
539
625
  for (const flat of codeAndText(src, tokens, parametersOf)) {
540
626
  const piece = where ? nestedPiece(flat, toRoot, where) : flat;
@@ -543,41 +629,68 @@ function* expand(
543
629
  continue;
544
630
  }
545
631
  // The text may not be where its length says: a string with escapes
546
- const toText = (i: number) => toRoot(pieceOffset(flat, i));
547
- const inner = analyzeMarkup(flat.text, {
548
- text: true,
549
- hooks: {
550
- ...(options.isBlock && { isBlock: options.isBlock }),
551
- isRaw: (name) =>
552
- isRawMacro(name, parametersOf.widget?.(name) !== undefined),
553
- },
554
- });
555
- yield {
556
- ...(piece as TextPiece),
557
- tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
558
- errors: inner.errors.map((e) => {
559
- const { line, column } = locate(toText(e.offset));
560
- return new MarkupError(
561
- e.reason,
562
- toText(e.offset),
563
- line,
564
- column,
565
- e.code,
566
- toText(e.end),
567
- e.data,
568
- );
569
- }),
570
- };
571
- yield* expand(
572
- root,
573
- flat.text,
574
- inner.tokens,
575
- parametersOf,
576
- options,
577
- toText,
578
- flat.where,
579
- locate,
580
- );
632
+ // nestedPiece flattened the offsets into the root source. Avoid composing
633
+ // a recursive mapping closure for every enclosing label.
634
+ const toText = (i: number) => pieceOffset(piece, i);
635
+ if (!budget.enter(flat.text.length)) {
636
+ const at = toText(0);
637
+ const { line, column } = locate(at);
638
+ yield {
639
+ ...(piece as TextPiece),
640
+ errors: [
641
+ new MarkupError(
642
+ 'Markup in labels and attributes exceeds the nesting or work limit',
643
+ at,
644
+ line,
645
+ column,
646
+ 'nesting-limit',
647
+ toText(flat.text.length),
648
+ { limit: String(MarkupExpansionBudget.maxDepth) },
649
+ ),
650
+ ],
651
+ };
652
+ continue;
653
+ }
654
+ try {
655
+ const inner = analyzeMarkup(flat.text, {
656
+ text: true,
657
+ hooks: {
658
+ ...parametersOf.pairing,
659
+ ...(options.isBlock && { isBlock: options.isBlock }),
660
+ isRaw: (name) =>
661
+ isRawMacro(name, parametersOf.widget?.(name) !== undefined),
662
+ },
663
+ });
664
+ yield {
665
+ ...(piece as TextPiece),
666
+ tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
667
+ errors: inner.errors.map((e) => {
668
+ const { line, column } = locate(toText(e.offset));
669
+ return new MarkupError(
670
+ e.reason,
671
+ toText(e.offset),
672
+ line,
673
+ column,
674
+ e.code,
675
+ toText(e.end),
676
+ e.data,
677
+ );
678
+ }),
679
+ };
680
+ yield* expand(
681
+ root,
682
+ flat.text,
683
+ inner.tokens,
684
+ parametersOf,
685
+ options,
686
+ toText,
687
+ flat.where,
688
+ locate,
689
+ budget,
690
+ );
691
+ } finally {
692
+ budget.leave();
693
+ }
581
694
  }
582
695
  }
583
696
 
@@ -676,6 +789,7 @@ export function* argPieces(
676
789
  params: readonly ParameterDef[],
677
790
  macro: string,
678
791
  label: string,
792
+ navigation: readonly string[] = [],
679
793
  ): Generator<Piece> {
680
794
  let values: Record<string, unknown>;
681
795
  const spans: ArgSpans = new Map();
@@ -702,6 +816,7 @@ export function* argPieces(
702
816
  macro,
703
817
  label,
704
818
  'quotes',
819
+ navigation,
705
820
  );
706
821
  }
707
822
 
@@ -757,6 +872,7 @@ function* valuePieces(
757
872
  macro: string,
758
873
  label: string,
759
874
  escapes: Escapes,
875
+ navigation: readonly string[] = [],
760
876
  ): Generator<Piece> {
761
877
  const name = macro.toLowerCase();
762
878
  /** The pieces of the parameters `list`, with their values in `from`. */
@@ -785,6 +901,7 @@ function* valuePieces(
785
901
  length: end - start,
786
902
  macro: name,
787
903
  label,
904
+ ...(navigation.includes(param.name) && { navigation: true as const }),
788
905
  });
789
906
  const goal = codeGoal(param);
790
907
  if (param.type === 'passage') {
@@ -6,6 +6,7 @@ import {
6
6
  attributeValues,
7
7
  escapeOffsets,
8
8
  parameterLookup,
9
+ macroArgumentLookup,
9
10
  executesRawBody,
10
11
  usesBuiltinSemantics,
11
12
  type PieceBase,
@@ -188,10 +189,9 @@ export function completionContext(
188
189
  const name = token.name.toLowerCase();
189
190
  const args = token.rawArgs;
190
191
  const widget = parametersOf.widget?.(name);
191
- if (
192
- usesBuiltinSemantics(name, parametersOf) &&
193
- ['if', 'elseif', 'case'].includes(name)
194
- ) {
192
+ const role = macroArgumentLookup(tokens, parametersOf)(token);
193
+ if (role === 'branch') return LITERAL;
194
+ if (role === 'condition') {
195
195
  return codeAt(args, token.argsStart);
196
196
  }
197
197
  const stringContext = (
@@ -1,11 +1,12 @@
1
1
  import { actionAttributes } from '../../hooks/use-action';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
4
+ import { OPTION_CLAUSE } from './option-clauses';
4
5
 
5
6
  defineMacro({
6
7
  name: 'cycle',
7
8
  block: true,
8
- subMacros: ['option'],
9
+ subMacros: [OPTION_CLAUSE],
9
10
  interpolate: true,
10
11
  storeVar: true,
11
12
  parameters: [VARIABLE_PARAMETER],
@@ -21,6 +21,7 @@ function selectIfBranch(
21
21
  defineMacro({
22
22
  name: 'if',
23
23
  block: true,
24
+ subMacros: ['elseif', 'else'],
24
25
  interpolate: true,
25
26
  merged: true,
26
27
  render({ branches = [] }, ctx) {
@@ -2,11 +2,12 @@ import { actionAttributes } from '../../hooks/use-action';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { VARIABLE_PARAMETER, useVariableAction } from './input-macro';
4
4
  import { display } from './display';
5
+ import { OPTION_CLAUSE } from './option-clauses';
5
6
 
6
7
  defineMacro({
7
8
  name: 'listbox',
8
9
  interpolate: true,
9
- subMacros: ['option'],
10
+ subMacros: [OPTION_CLAUSE],
10
11
  storeVar: true,
11
12
  parameters: [VARIABLE_PARAMETER],
12
13
  render({ children = [] }, ctx) {
@@ -0,0 +1,20 @@
1
+ /** The direct value clauses read by the built-in choice controls. */
2
+ export const OPTION_CLAUSE = 'option';
3
+
4
+ export function isOptionClause(name: string): boolean {
5
+ return name.toLowerCase() === OPTION_CLAUSE;
6
+ }
7
+
8
+ /** Replacements render their own children and do not inherit this contract. */
9
+ export function consumesOptionClauses(macro: {
10
+ name: string;
11
+ source?: 'builtin' | 'user';
12
+ widget?: unknown;
13
+ }): boolean {
14
+ const name = macro.name.toLowerCase();
15
+ return (
16
+ macro.source === 'builtin' &&
17
+ !macro.widget &&
18
+ (name === 'listbox' || name === 'cycle')
19
+ );
20
+ }
@@ -1,6 +1,7 @@
1
1
  import type { ASTNode } from '../../markup/ast';
2
2
  import { parseMacroArgs } from './macro-args';
3
3
  import type { ParameterDef } from '../../registry';
4
+ import { isOptionClause, OPTION_CLAUSE } from './option-clauses';
4
5
 
5
6
  /** `$var "placeholder"`, the arguments of the input macros. */
6
7
  export function parseVarArgs(rawArgs: string): {
@@ -21,7 +22,7 @@ const OPTION_PARAMETERS = [
21
22
 
22
23
  /** The parameters of the built-in sub-macros that take arguments. */
23
24
  const SUB_MACRO_PARAMETERS: ReadonlyMap<string, readonly ParameterDef[]> =
24
- new Map([['option', OPTION_PARAMETERS]]);
25
+ new Map([[OPTION_CLAUSE, OPTION_PARAMETERS]]);
25
26
 
26
27
  /** The parameters of the built-in sub-macro `name`, if it takes any. */
27
28
  export function subMacroParameters(
@@ -36,7 +37,7 @@ export function subMacroParameters(
36
37
  export function extractOptions(children: ASTNode[]): string[] {
37
38
  const options: string[] = [];
38
39
  for (const node of children) {
39
- if (node.type === 'macro' && node.name === 'option') {
40
+ if (node.type === 'macro' && isOptionClause(node.name)) {
40
41
  // {option "Long Sword"} gives `Long Sword`
41
42
  const { value } = parseMacroArgs(node.rawArgs, OPTION_PARAMETERS);
42
43
  options.push(value ?? '');