@rohal12/spindle 0.63.0 → 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.
@@ -3636,6 +3636,18 @@ function peg$parse(input, options) {
3636
3636
  if (peg$success) return peg$result;
3637
3637
  else peg$throw();
3638
3638
  }
3639
+ //#endregion
3640
+ //#region src/components/macros/option-clauses.ts
3641
+ /** The direct value clauses read by the built-in choice controls. */
3642
+ var OPTION_CLAUSE = "option";
3643
+ function isOptionClause(name) {
3644
+ return name.toLowerCase() === OPTION_CLAUSE;
3645
+ }
3646
+ /** Replacements render their own children and do not inherit this contract. */
3647
+ function consumesOptionClauses(macro) {
3648
+ const name = macro.name.toLowerCase();
3649
+ return macro.source === "builtin" && !macro.widget && (name === "listbox" || name === "cycle");
3650
+ }
3639
3651
  new NameMap();
3640
3652
  new NameMap();
3641
3653
  new NameSet();
@@ -3715,10 +3727,30 @@ function parameterError(macro, param, problem, fix) {
3715
3727
  var metadataRegistry = new NameMap();
3716
3728
  /** Indexed at registration, so parsing each tag does not scan every macro. */
3717
3729
  var companionParents = new NameMap();
3730
+ /** Share index construction between live registrations and stateless tooling. */
3731
+ function indexCompanionParents(index, macro) {
3732
+ const name = macro.name.toLowerCase();
3733
+ for (const sub of macro.subMacros) {
3734
+ const parents = index.get(sub) ?? /* @__PURE__ */ new Set();
3735
+ parents.add(name);
3736
+ index.set(sub, parents);
3737
+ }
3738
+ }
3718
3739
  /** The parents declaring a branching companion (input options are values). */
3719
3740
  function branchParents(name, macros) {
3720
- if (!macros) return [...companionParents.get(name) ?? []].filter((parent) => parent !== "listbox" && parent !== "cycle");
3721
- return effectiveNamedDefinitions(macros).filter((macro) => macro.name.toLowerCase() !== "listbox" && macro.name.toLowerCase() !== "cycle" && macro.subMacros.some((sub) => sub.toLowerCase() === name.toLowerCase())).map((macro) => macro.name.toLowerCase());
3741
+ if (!macros) return [...companionParents.get(name) ?? []].filter((parent) => !consumesOptionClauses(metadataRegistry.get(parent)));
3742
+ return [...branchParentLookup(macros)(name)];
3743
+ }
3744
+ /** Build once per effective metadata snapshot, then look up each token. */
3745
+ function branchParentLookup(macros) {
3746
+ const parents = new NameMap();
3747
+ for (const macro of effectiveNamedDefinitions(macros)) {
3748
+ if (consumesOptionClauses(macro)) continue;
3749
+ indexCompanionParents(parents, macro);
3750
+ }
3751
+ const index = new NameMap();
3752
+ for (const [sub, names] of parents) index.set(sub, [...names]);
3753
+ return (name) => index.get(name) ?? [];
3722
3754
  }
3723
3755
  /** The declared parameters of the macro `name`, if it declares any. */
3724
3756
  function getMacroParameters(name) {
@@ -3774,6 +3806,10 @@ function isBlockMacro(name) {
3774
3806
  if (REGISTERED_BLOCK_MACROS.has(name)) return true;
3775
3807
  if (WIDGETS.has(name)) return BLOCK_WIDGETS.has(name);
3776
3808
  if (DEFINED_MACROS.has(name)) return DEFINED_BLOCK_MACROS.has(name);
3809
+ return isBuiltinBlockMacro(name);
3810
+ }
3811
+ /** Built-in defaults without any process-global registrations or widgets. */
3812
+ function isBuiltinBlockMacro(name) {
3777
3813
  return BLOCK_MACROS.has(name);
3778
3814
  }
3779
3815
  /** Explicit parser registrations, unaffected by effective tooling metadata. */
@@ -3936,9 +3972,11 @@ function pairMarkup(tokens, options = {}) {
3936
3972
  const isBlock = options.isBlock ?? isBlockMacro;
3937
3973
  const isRaw = options.isRaw ?? isRawMacro;
3938
3974
  const parentsOf = (name) => {
3975
+ if (options.branchParents) return options.branchParents(name);
3976
+ const registered = branchParents(name);
3939
3977
  const lower = name.toLowerCase();
3940
3978
  const builtin = Object.prototype.hasOwnProperty.call(BRANCH_PARENT, lower) ? BRANCH_PARENT[lower] : void 0;
3941
- return builtin ? [builtin] : options.branchParents?.(name) ?? branchParents(name);
3979
+ return builtin && getMacroParameters.source(builtin) === void 0 ? [...registered, builtin] : registered;
3942
3980
  };
3943
3981
  const errors = [];
3944
3982
  const noticedAtEnd = (tokens[tokens.length - 1]?.end ?? 0) + 1;
@@ -11320,7 +11358,7 @@ function macroArgumentSpans(rawArgs, parameters) {
11320
11358
  return result.sort((a, b) => a.start - b.start || b.end - a.end);
11321
11359
  }
11322
11360
  /** The parameters of the built-in sub-macros that take arguments. */
11323
- var SUB_MACRO_PARAMETERS = /* @__PURE__ */ new Map([["option", [{
11361
+ var SUB_MACRO_PARAMETERS = /* @__PURE__ */ new Map([[OPTION_CLAUSE, [{
11324
11362
  name: "value",
11325
11363
  type: "string",
11326
11364
  holds: "text",
@@ -11410,6 +11448,30 @@ function widgetParameters(params, holds = {}) {
11410
11448
  ...hasOwn(holds, name) ? { holds: holds[name] } : {}
11411
11449
  }));
11412
11450
  }
11451
+ /** A consumed branch uses its parent's argument contract, not standalone metadata. */
11452
+ function macroArgumentLookup(tokens, parametersOf) {
11453
+ let owners;
11454
+ const parentsOf = parametersOf.pairing?.branchParents ?? branchParents;
11455
+ return (token) => {
11456
+ const name = token.name.toLowerCase();
11457
+ if (parentsOf(name).length > 0 && !owners) {
11458
+ owners = /* @__PURE__ */ new Map();
11459
+ const pending = [...pairMarkup(tokens, parametersOf.pairing).nodes];
11460
+ while (pending.length) {
11461
+ const node = pending.pop();
11462
+ if (!node.body) continue;
11463
+ for (const branch of node.body.branches) {
11464
+ if (node.token.type === "macro") owners.set(branch.tag, node.token.name.toLowerCase());
11465
+ for (const child of branch.children) pending.push(child);
11466
+ }
11467
+ for (const child of node.body.children) pending.push(child);
11468
+ }
11469
+ }
11470
+ const owner = owners?.get(token);
11471
+ if (owner !== void 0) return CONDITION_MACROS.has(name) && owner === BRANCH_PARENT[name] && usesBuiltinSemantics(owner, parametersOf) ? "condition" : "branch";
11472
+ return CONDITION_MACROS.has(name) && usesBuiltinSemantics(name, parametersOf) ? "condition" : "invocation";
11473
+ };
11474
+ }
11413
11475
  /** Whether builtin-only interpretation still belongs to this implementation. */
11414
11476
  function usesBuiltinSemantics(name, parametersOf) {
11415
11477
  return parametersOf.widget?.(name) === void 0 && parametersOf.source?.(name) !== "user";
@@ -11443,10 +11505,11 @@ function withHolds(params, holds) {
11443
11505
  * A widget among `macros` says what its parameters hold (see ParametersOf).
11444
11506
  */
11445
11507
  function parameterLookup(macros) {
11508
+ const list = [...macros];
11446
11509
  const parameters = new NameMap();
11447
11510
  const widgets = new NameMap();
11448
11511
  const sources = new NameMap();
11449
- for (const { name, parameters: params, interpolate, widget, source } of macros) {
11512
+ for (const { name, parameters: params, interpolate, widget, source } of list) {
11450
11513
  sources.set(name, source ?? "user");
11451
11514
  if (params) parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
11452
11515
  else parameters.delete(name);
@@ -11463,6 +11526,15 @@ function parameterLookup(macros) {
11463
11526
  };
11464
11527
  if (widgets.size > 0) lookup.widget = (name) => widgets.get(name);
11465
11528
  lookup.source = (name) => sources.get(name);
11529
+ const definitions = new NameMap(effectiveNamedDefinitions([...list.filter((macro) => !macro.widget), ...list.filter((macro) => macro.widget)]).map((macro) => [macro.name, macro]));
11530
+ lookup.pairing = {
11531
+ isBlock: (name) => definitions.get(name)?.block ?? isBuiltinBlockMacro(name),
11532
+ isRaw: (name) => isRawMacro(name, widgets.has(name)),
11533
+ branchParents: branchParentLookup([...definitions.values()].map((macro) => ({
11534
+ ...macro,
11535
+ subMacros: [...macro.subMacros ?? []]
11536
+ })))
11537
+ };
11466
11538
  return lookup;
11467
11539
  }
11468
11540
  /** What a `string` or `text` argument holds when its parameter doesn't say. */
@@ -11485,6 +11557,7 @@ function stringHolds(param) {
11485
11557
  * `parametersOf` gives the declared parameters of a macro, if it has any.
11486
11558
  */
11487
11559
  function* codeAndText(src, tokens, parametersOf) {
11560
+ const argumentRole = macroArgumentLookup(tokens, parametersOf);
11488
11561
  const closeOfTextBody = (t, name) => {
11489
11562
  for (let k = t + 1; k < tokens.length; k++) {
11490
11563
  const c = tokens[k];
@@ -11528,6 +11601,8 @@ function* codeAndText(src, tokens, parametersOf) {
11528
11601
  }
11529
11602
  else if (token.type === "macro" && !token.isClose) {
11530
11603
  const name = token.name.toLowerCase();
11604
+ const role = argumentRole(token);
11605
+ if (role === "branch") continue;
11531
11606
  const widget = parametersOf.widget?.(name);
11532
11607
  if (executesRawBody(name, parametersOf)) {
11533
11608
  const close = closeOfTextBody(t, name);
@@ -11561,7 +11636,7 @@ function* codeAndText(src, tokens, parametersOf) {
11561
11636
  if (!args) continue;
11562
11637
  const label = `{${token.name} ${args}}`;
11563
11638
  const argsAt = token.argsStart;
11564
- if (CONDITION_MACROS.has(name) && usesBuiltinSemantics(name, parametersOf)) {
11639
+ if (role === "condition") {
11565
11640
  yield {
11566
11641
  kind: "code",
11567
11642
  code: args,
@@ -11617,6 +11692,7 @@ function* expand(root, src, tokens, parametersOf, options, toRoot, where, locate
11617
11692
  const inner = analyzeMarkup(flat.text, {
11618
11693
  text: true,
11619
11694
  hooks: {
11695
+ ...parametersOf.pairing,
11620
11696
  ...options.isBlock && { isBlock: options.isBlock },
11621
11697
  isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0)
11622
11698
  }
@@ -12000,11 +12076,9 @@ function completionContext(source, cursor, macros = []) {
12000
12076
  const name = token.name.toLowerCase();
12001
12077
  const args = token.rawArgs;
12002
12078
  const widget = parametersOf.widget?.(name);
12003
- if (usesBuiltinSemantics(name, parametersOf) && [
12004
- "if",
12005
- "elseif",
12006
- "case"
12007
- ].includes(name)) return codeAt(args, token.argsStart);
12079
+ const role = macroArgumentLookup(tokens, parametersOf)(token);
12080
+ if (role === "branch") return LITERAL;
12081
+ if (role === "condition") return codeAt(args, token.argsStart);
12008
12082
  const stringContext = (raw, at, holds, escapes = "quotes") => {
12009
12083
  const quoted = readQuoted(raw, 0, true);
12010
12084
  if (!quoted) {
@@ -13336,6 +13410,7 @@ function boundReference(token, at, all) {
13336
13410
  /** Report the `$var` references in the tokens of `content`. */
13337
13411
  function collectTokenRefs(content, tokens, at, emit, options) {
13338
13412
  const { storeVarMacros, parametersOf } = options;
13413
+ const argumentRole = macroArgumentLookup(tokens, parametersOf);
13339
13414
  for (let t = 0; t < tokens.length; t++) {
13340
13415
  const token = tokens[t];
13341
13416
  if (options.all && token.type !== "macro" && token.type !== "html" && token.type !== "text") scanSelectors(content, token, at, emit, options);
@@ -13361,13 +13436,15 @@ function collectTokenRefs(content, tokens, at, emit, options) {
13361
13436
  else scanInterpolations(value, valueIn, emit, options);
13362
13437
  }
13363
13438
  else if (token.type === "macro" && !token.isClose) {
13364
- const binding = storeVarMacros.has(token.name.toLowerCase()) && !parametersOf.widget?.(token.name) ? boundReference(token, at, options.all) : void 0;
13365
- scanArgs(token, parametersOf, at, (ref) => {
13439
+ const role = argumentRole(token);
13440
+ const binding = role === "invocation" && storeVarMacros.has(token.name.toLowerCase()) && !parametersOf.widget?.(token.name) ? boundReference(token, at, options.all) : void 0;
13441
+ if (role === "condition") scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
13442
+ else if (role === "invocation") scanArgs(token, parametersOf, at, (ref) => {
13366
13443
  if (!binding || ref.start < binding.start || ref.start >= binding.end) emit(ref);
13367
13444
  }, options);
13368
13445
  scanSelectors(content, token, at, emit, options);
13369
13446
  if (binding) emit(binding);
13370
- if (executesRawBody(token.name, parametersOf)) {
13447
+ if (role === "invocation" && executesRawBody(token.name, parametersOf)) {
13371
13448
  let close = t + 1;
13372
13449
  while (close < tokens.length) {
13373
13450
  const c = tokens[close];
@@ -25964,7 +26041,7 @@ function tokenizationOptions(options) {
25964
26041
  hooks: {
25965
26042
  isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0),
25966
26043
  isBlock: blockLookup(macros),
25967
- branchParents: (name) => branchParents(name, macros),
26044
+ branchParents: branchParentLookup(macros),
25968
26045
  ...options.hooks
25969
26046
  }
25970
26047
  };
@@ -25988,6 +26065,12 @@ function validateStoryMarkup(passages, macros, options = {}) {
25988
26065
  const all = effectiveToolingMacros(macros);
25989
26066
  const known = /* @__PURE__ */ new Set();
25990
26067
  const widgets = effectiveWidgetDefinitions(widgetDefinitions$1(list, parameterLookup(all)));
26068
+ const effective = effectiveToolingMacros([...all, ...widgets.map((widget) => ({
26069
+ name: widget.name,
26070
+ block: widget.block,
26071
+ subMacros: [],
26072
+ widget
26073
+ }))]);
25991
26074
  const parametersOf = parameterLookup([...all, ...definedWidgetMacros(widgets)]);
25992
26075
  for (const macro of all) {
25993
26076
  const name = macro.name.toLowerCase();
@@ -25995,16 +26078,11 @@ function validateStoryMarkup(passages, macros, options = {}) {
25995
26078
  for (const sub of macro.subMacros) known.add(sub.toLowerCase());
25996
26079
  }
25997
26080
  return validateMarkup(list, {
25998
- branchParents: (name) => branchParents(name, all),
26081
+ branchParents: branchParentLookup(effective),
25999
26082
  isKnownMacro: (name) => known.has(name),
26000
26083
  macroNames: known,
26001
26084
  parametersOf,
26002
- isBlockMacro: blockLookup([...all, ...widgets.map((w) => ({
26003
- name: w.name,
26004
- block: w.block,
26005
- subMacros: [],
26006
- widget: w
26007
- }))]),
26085
+ isBlockMacro: blockLookup(effective),
26008
26086
  checkPassageNames: options.checkPassageNames,
26009
26087
  tolerant: options.tolerant
26010
26088
  });
@@ -26017,10 +26095,81 @@ function definedWidgetMacros(widgets) {
26017
26095
  }));
26018
26096
  }
26019
26097
  /** Whether a macro takes a body, among `macros` and the built-in ones. */
26020
- function blockLookup(macros) {
26098
+ function blockLookup(macros, includeRuntime = true) {
26021
26099
  const definitions = new NameMap();
26022
26100
  for (const macro of effectiveToolingMacros(macros)) definitions.set(macro.name, macro.block);
26023
- return (name) => isRegisteredBlockMacro(name) || (definitions.get(name) ?? isBlockMacro(name));
26101
+ return (name) => includeRuntime && isRegisteredBlockMacro(name) || (definitions.get(name) ?? (includeRuntime ? isBlockMacro(name) : isBuiltinBlockMacro(name)));
26102
+ }
26103
+ /**
26104
+ * Classify heads against explicit effective metadata, without running code.
26105
+ * Labels and attributes are separate markup scopes and never inherit a
26106
+ * surrounding control's clause ownership. This describes dispatch, not
26107
+ * whether a conditional body will execute.
26108
+ */
26109
+ function macroCalls(source, macros = []) {
26110
+ const all = effectiveToolingMacros(macros);
26111
+ const definitions = new NameMap(all.map((macro) => [macro.name, macro]));
26112
+ const parametersOf = parameterLookup(all);
26113
+ const options = tokenizationOptions({
26114
+ macros: all,
26115
+ hooks: { isBlock: blockLookup(all, false) }
26116
+ });
26117
+ const hooks = options.hooks;
26118
+ const tokens = tokenizeMarkupTolerant$1(source, options).tokens;
26119
+ const calls = [];
26120
+ const classify = (tokens) => {
26121
+ const found = /* @__PURE__ */ new Map();
26122
+ const pending = pairMarkup(tokens, hooks).nodes.map((node) => ({ node }));
26123
+ while (pending.length) {
26124
+ const { node, parent } = pending.pop();
26125
+ const token = node.token;
26126
+ if (token.type === "macro") {
26127
+ const definition = parent && definitions.get(parent.name);
26128
+ const value = definition && consumesOptionClauses(definition) && isOptionClause(token.name);
26129
+ found.set(token, {
26130
+ token,
26131
+ kind: value ? "value" : "invocation",
26132
+ ...value && { owner: parent }
26133
+ });
26134
+ }
26135
+ if (!node.body) continue;
26136
+ const owner = token.type === "macro" ? token : void 0;
26137
+ for (const child of node.body.children) pending.push({
26138
+ node: child,
26139
+ parent: owner
26140
+ });
26141
+ for (const branch of node.body.branches) {
26142
+ found.set(branch.tag, {
26143
+ token: branch.tag,
26144
+ kind: "branch",
26145
+ owner
26146
+ });
26147
+ for (const child of branch.children) pending.push({
26148
+ node: child,
26149
+ parent: owner
26150
+ });
26151
+ }
26152
+ }
26153
+ for (const token of tokens) {
26154
+ if (token.type !== "macro" || token.isClose) continue;
26155
+ const call = found.get(token) ?? {
26156
+ token,
26157
+ kind: "branch"
26158
+ };
26159
+ calls.push(call);
26160
+ }
26161
+ };
26162
+ classify(tokens);
26163
+ for (const piece of passagePiecesOf(source, tokens, parametersOf, { isBlock: hooks.isBlock })) {
26164
+ if (piece.kind !== "text" || !piece.tokens.length) continue;
26165
+ classify(piece.tokens);
26166
+ }
26167
+ let literalEnd = -1;
26168
+ return calls.sort((a, b) => a.token.start - b.token.start).filter((call) => {
26169
+ if (call.token.start < literalEnd) return false;
26170
+ if (call.kind === "value" || call.kind === "branch") literalEnd = call.token.argsEnd;
26171
+ return true;
26172
+ });
26024
26173
  }
26025
26174
  /**
26026
26175
  * What a passage's markup runs and names, and where: the pieces of code
@@ -26119,4 +26268,4 @@ function validateVariableReferences(passages, declarations, macros = []) {
26119
26268
  return checkVariableReferences(list.filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros, false, list));
26120
26269
  }
26121
26270
  //#endregion
26122
- export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, isSpecialPassage, lexJs, lexTemplate, macroArgumentSpans, pairMarkup, parseBoundVariable, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
26271
+ export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, completionContext, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, isSpecialPassage, lexJs, lexTemplate, macroArgumentSpans, macroCalls, pairMarkup, parseBoundVariable, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
@@ -14,6 +14,7 @@ export {
14
14
  completionContext,
15
15
  pieceOffset,
16
16
  pairMarkup,
17
+ macroCalls,
17
18
  isBlockMacro,
18
19
  isSpecialPassage,
19
20
  parseStoryVariables,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.63.0",
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,9 +56,9 @@ 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';
53
63
  import { MarkupExpansionBudget } from './markup/expansion-budget';
54
64
 
@@ -234,6 +244,45 @@ export interface ParametersOf {
234
244
  widget?(name: string): readonly WidgetParameter[] | undefined;
235
245
  /** Effective registration origin; absent metadata retains builtin defaults. */
236
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
+ };
237
286
  }
238
287
 
239
288
  /** Whether builtin-only interpretation still belongs to this implementation. */
@@ -258,6 +307,8 @@ export function executesRawBody(
258
307
  /** What the argument check needs to know of a macro (see MacroMetadata). */
259
308
  export interface MacroParameters {
260
309
  name: string;
310
+ block?: boolean;
311
+ subMacros?: readonly string[];
261
312
  source?: 'builtin' | 'user';
262
313
  parameters?: readonly ParameterDef[];
263
314
  interpolate?: boolean;
@@ -296,6 +347,7 @@ function withHolds(
296
347
  export function parameterLookup(
297
348
  macros: Iterable<MacroParameters>,
298
349
  ): ParametersOf {
350
+ const list = [...macros];
299
351
  const parameters = new NameMap<readonly ParameterDef[]>();
300
352
  const widgets = new NameMap<readonly WidgetParameter[]>();
301
353
  const sources = new NameMap<'builtin' | 'user'>();
@@ -305,7 +357,7 @@ export function parameterLookup(
305
357
  interpolate,
306
358
  widget,
307
359
  source,
308
- } of macros) {
360
+ } of list) {
309
361
  sources.set(name, source ?? 'user');
310
362
  if (params)
311
363
  parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
@@ -324,6 +376,23 @@ export function parameterLookup(
324
376
  };
325
377
  if (widgets.size > 0) lookup.widget = (name) => widgets.get(name);
326
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
+ };
327
396
  return lookup;
328
397
  }
329
398
 
@@ -368,6 +437,7 @@ export function* codeAndText(
368
437
  tokens: readonly Token[],
369
438
  parametersOf: ParametersOf,
370
439
  ): Generator<Piece> {
440
+ const argumentRole = macroArgumentLookup(tokens, parametersOf);
371
441
  // Only a plain-text body is read here: raw JavaScript in {do}, or a
372
442
  // passage name in {dialog}. Start at the opener and stop at any markup,
373
443
  // including a nested opener, rather than rescanning the token prefix.
@@ -433,6 +503,8 @@ export function* codeAndText(
433
503
  }
434
504
  } else if (token.type === 'macro' && !token.isClose) {
435
505
  const name = token.name.toLowerCase();
506
+ const role = argumentRole(token);
507
+ if (role === 'branch') continue;
436
508
  const widget = parametersOf.widget?.(name);
437
509
  if (executesRawBody(name, parametersOf)) {
438
510
  const close = closeOfTextBody(t, name);
@@ -471,10 +543,7 @@ export function* codeAndText(
471
543
  if (!args) continue;
472
544
  const label = `{${token.name} ${args}}`;
473
545
  const argsAt = token.argsStart;
474
- if (
475
- CONDITION_MACROS.has(name) &&
476
- usesBuiltinSemantics(name, parametersOf)
477
- ) {
546
+ if (role === 'condition') {
478
547
  yield {
479
548
  kind: 'code',
480
549
  code: args,
@@ -586,6 +655,7 @@ function* expand(
586
655
  const inner = analyzeMarkup(flat.text, {
587
656
  text: true,
588
657
  hooks: {
658
+ ...parametersOf.pairing,
589
659
  ...(options.isBlock && { isBlock: options.isBlock }),
590
660
  isRaw: (name) =>
591
661
  isRawMacro(name, parametersOf.widget?.(name) !== undefined),
@@ -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 ?? '');
package/src/markup/ast.ts CHANGED
@@ -104,6 +104,11 @@ export function isBlockMacro(name: string): boolean {
104
104
  if (REGISTERED_BLOCK_MACROS.has(name)) return true;
105
105
  if (WIDGETS.has(name)) return BLOCK_WIDGETS.has(name);
106
106
  if (DEFINED_MACROS.has(name)) return DEFINED_BLOCK_MACROS.has(name);
107
+ return isBuiltinBlockMacro(name);
108
+ }
109
+
110
+ /** Built-in defaults without any process-global registrations or widgets. */
111
+ export function isBuiltinBlockMacro(name: string): boolean {
107
112
  return BLOCK_MACROS.has(name);
108
113
  }
109
114