@rohal12/spindle 0.61.7 → 0.62.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.
@@ -9154,34 +9154,6 @@ function parse$1(input, options) {
9154
9154
  }
9155
9155
  //#endregion
9156
9156
  //#region src/js-lexer.ts
9157
- /**
9158
- * The JavaScript in story markup, read with acorn.
9159
- *
9160
- * acorn reads the code: where string, template and regex literals and
9161
- * comments begin and end, whether `/` opens a regex, and (`parseCode`) the
9162
- * syntax tree. A plugin (`SigilParser`) teaches its tokenizer the two sigils
9163
- * that are no JavaScript: `@name` (locals) anywhere, and `%name`
9164
- * (transients) where an operand is expected, the same place acorn reads `/`
9165
- * as a regex; `%` elsewhere is the modulo operator. `$name` and `_name` are
9166
- * identifiers already; the syntax tree tells references from property names
9167
- * and declarations.
9168
- *
9169
- * - `parseCode`: the references and string text of well-formed code, or a
9170
- * `CodeSyntaxError` that says what is wrong and where. The expression
9171
- * engine (`expression.ts`) rewrites the references it finds, and the
9172
- * story-start check (`markup/validate.ts`) reports the errors.
9173
- * - `findCodeEnd`: where the code in a `{…}` ends, for the markup grammar
9174
- * (`markup/code-end.ts`). -1 when acorn can't read it: the grammar then
9175
- * scans it leniently, as prose-like macro arguments (`{link Don't go}`)
9176
- * need.
9177
- * - `lexJs`: a lenient token walk for the macro argument splitters
9178
- * (`components/macros/arg-utils.ts`), which also read text that is no
9179
- * JavaScript.
9180
- *
9181
- * Restrictions (docs/variables.md "Code in passages"): sigil variables can't
9182
- * be declared (`let _x`, `(_a) => …`) or be property names (`a.@x`), and
9183
- * code must be valid modern JavaScript (a non-strict script).
9184
- */
9185
9157
  /** Code runs through `new Function`: a non-strict script body. */
9186
9158
  var OPTIONS = {
9187
9159
  ecmaVersion: "latest",
@@ -9542,13 +9514,13 @@ function propertyName(node, src) {
9542
9514
  * identifiers here are declared (a `let`, a parameter), where a sigil
9543
9515
  * variable can't be. `shorthand`: the node is a shorthand property's value.
9544
9516
  */
9545
- function walk(node, src, out, binding, shorthand) {
9517
+ function walk(node, src, out, binding, shorthand, access = "read") {
9546
9518
  if (Array.isArray(node)) {
9547
- for (const n of node) walk(n, src, out, binding, false);
9519
+ for (const n of node) walk(n, src, out, binding, false, access);
9548
9520
  return;
9549
9521
  }
9550
9522
  if (!isNode(node)) return;
9551
- const sub = (child, bind = false, short = false) => walk(child, src, out, bind, short);
9523
+ const sub = (child, bind = false, short = false, role = "read") => walk(child, src, out, bind, short, role);
9552
9524
  switch (node.type) {
9553
9525
  case "Identifier": {
9554
9526
  const sigil = sigilOf(node, src);
@@ -9559,7 +9531,9 @@ function walk(node, src, out, binding, shorthand) {
9559
9531
  name: sigil[1],
9560
9532
  start: node.start,
9561
9533
  end: node.end,
9562
- shorthand
9534
+ shorthand,
9535
+ read: access !== "write",
9536
+ write: access !== "read"
9563
9537
  });
9564
9538
  return;
9565
9539
  }
@@ -9580,10 +9554,10 @@ function walk(node, src, out, binding, shorthand) {
9580
9554
  if (node.shorthand) {
9581
9555
  const value = node.value;
9582
9556
  if (value.type === "AssignmentPattern") {
9583
- sub(value.left, binding, true);
9557
+ sub(value.left, binding, true, access);
9584
9558
  sub(value.right);
9585
- } else sub(value, binding, true);
9586
- } else sub(node.value, binding);
9559
+ } else sub(value, binding, true, access);
9560
+ } else sub(node.value, binding, false, access);
9587
9561
  return;
9588
9562
  case "MethodDefinition":
9589
9563
  case "PropertyDefinition":
@@ -9619,8 +9593,24 @@ function walk(node, src, out, binding, shorthand) {
9619
9593
  sub(node.param, true);
9620
9594
  sub(node.body);
9621
9595
  return;
9596
+ case "AssignmentExpression":
9597
+ sub(node.left, false, false, node.operator === "=" ? "write" : "readwrite");
9598
+ sub(node.right);
9599
+ return;
9600
+ case "UnaryExpression":
9601
+ sub(node.argument, false, false, node.operator === "delete" ? "write" : "read");
9602
+ return;
9603
+ case "UpdateExpression":
9604
+ sub(node.argument, false, false, "readwrite");
9605
+ return;
9606
+ case "ForInStatement":
9607
+ case "ForOfStatement":
9608
+ sub(node.left, false, false, "write");
9609
+ sub(node.right);
9610
+ sub(node.body);
9611
+ return;
9622
9612
  case "AssignmentPattern":
9623
- sub(node.left, binding);
9613
+ sub(node.left, binding, false, access);
9624
9614
  sub(node.right);
9625
9615
  return;
9626
9616
  case "ObjectPattern":
@@ -9630,7 +9620,7 @@ function walk(node, src, out, binding, shorthand) {
9630
9620
  "properties",
9631
9621
  "elements",
9632
9622
  "argument"
9633
- ]) sub(node[key], binding);
9623
+ ]) sub(node[key], binding, false, access);
9634
9624
  return;
9635
9625
  default: for (const key in node) {
9636
9626
  if (key === "type" || key === "start" || key === "end") continue;
@@ -10485,14 +10475,15 @@ function unescapeQuoted(body) {
10485
10475
  * Read the `"…"` or `'…'` string whose opening quote is at `start`.
10486
10476
  * Returns its unescaped value and the index just past the closing quote, or
10487
10477
  * `null` if there is no such quote at `start` or the string is unterminated.
10478
+ * With `tolerant`, an unterminated string instead extends to its scanned end.
10488
10479
  */
10489
- function readQuoted(src, start) {
10480
+ function readQuoted(src, start, tolerant = false) {
10490
10481
  const quote = src[start];
10491
10482
  if (quote !== "\"" && quote !== "'") return null;
10492
10483
  const { end, closed } = scanStringLiteral(src, start);
10493
- if (!closed) return null;
10484
+ if (!closed && !tolerant) return null;
10494
10485
  return {
10495
- value: unescapeQuoted(src.slice(start + 1, end - 1)),
10486
+ value: unescapeQuoted(src.slice(start + 1, closed ? end - 1 : end)),
10496
10487
  end
10497
10488
  };
10498
10489
  }
@@ -10687,11 +10678,16 @@ var MacroArgumentError = class extends Error {
10687
10678
  };
10688
10679
  /** Read `src`, at `place`, as `param` says. */
10689
10680
  function readValue(param, src, place) {
10690
- place.spans?.set(param, [place.at, place.at + src.length]);
10681
+ const span = [place.at, place.at + src.length];
10682
+ place.spans?.set(param, span);
10683
+ place.toolingSpans?.set(param, span);
10691
10684
  switch (param.type) {
10692
10685
  case "string": {
10693
10686
  const value = readWholeQuoted(src);
10694
- if (value === null) throw new MacroArgumentError(param, src);
10687
+ if (value === null) {
10688
+ if (place.toolingSpans && (src[0] === "\"" || src[0] === "'")) return readText(src);
10689
+ throw new MacroArgumentError(param, src);
10690
+ }
10695
10691
  return value;
10696
10692
  }
10697
10693
  case "text": return readText(src);
@@ -10722,20 +10718,21 @@ function matchAt(re, src, pos) {
10722
10718
  * skipped. A keyword of a `string` parameter must be followed by a quoted
10723
10719
  * string.
10724
10720
  */
10725
- function readOptions(params, src, { at, spans }) {
10721
+ function readOptions(params, src, { at, spans, toolingSpans }) {
10726
10722
  const options = {};
10727
10723
  let i = 0;
10728
10724
  while (i < src.length) {
10729
10725
  const key = matchAt(WORD_RE$1, src, i);
10730
10726
  if (!key) {
10731
- i = readQuoted(src, i)?.end ?? i + 1;
10727
+ i = readQuoted(src, i, !!toolingSpans)?.end ?? i + 1;
10732
10728
  continue;
10733
10729
  }
10730
+ const keyAt = i;
10734
10731
  i += key.length;
10735
10732
  let val;
10736
10733
  let j = i;
10737
10734
  while (j < src.length && isWhitespace(src[j])) j++;
10738
- const quoted = readQuoted(src, j);
10735
+ const quoted = readQuoted(src, j, !!toolingSpans);
10739
10736
  const digits = quoted || j === i ? null : matchAt(NUMBER_RE$1, src, j);
10740
10737
  if (quoted) {
10741
10738
  val = quoted.value;
@@ -10746,7 +10743,8 @@ function readOptions(params, src, { at, spans }) {
10746
10743
  }
10747
10744
  const param = params.find((p) => p.name === key);
10748
10745
  if (param && param.type !== "flag" && val !== void 0) spans?.set(param, [at + j, at + i]);
10749
- if (param?.type === "string" && !quoted) throw new MacroArgumentError(param, matchAt(WORD_OR_PUNCT_RE, src, j) ?? "");
10746
+ if (param) toolingSpans?.set(param, [at + keyAt, at + i]);
10747
+ if (param?.type === "string" && !quoted && !toolingSpans) throw new MacroArgumentError(param, matchAt(WORD_OR_PUNCT_RE, src, j) ?? "");
10750
10748
  if (param?.type === "flag") options[key] = true;
10751
10749
  else if (param?.type === "number") options[key] = Number(val ?? 0);
10752
10750
  else if (param) options[key] = val;
@@ -10782,7 +10780,7 @@ function takeFlag(src, word, alone) {
10782
10780
  * term with terms on both sides; `=` is an assignment at depth 0, not part
10783
10781
  * of `==` or `!=`.
10784
10782
  */
10785
- function findSeparator(src, word) {
10783
+ function findSeparator(src, word, tolerant = false) {
10786
10784
  if (word === "=") {
10787
10785
  const indices = topLevelIndices(src, (ch) => ch === "=");
10788
10786
  for (let k = 0; k < indices.length; k++) {
@@ -10796,7 +10794,7 @@ function findSeparator(src, word) {
10796
10794
  return null;
10797
10795
  }
10798
10796
  const spans = terms(src);
10799
- for (let k = 1; k < spans.length - 1; k++) if (slice(src, spans[k]) === word) return [spans[k - 1][1], spans[k + 1][0]];
10797
+ for (let k = 1; k < spans.length - (tolerant ? 0 : 1); k++) if (slice(src, spans[k]) === word) return [spans[k - 1][1], spans[k + 1]?.[0] ?? src.length];
10800
10798
  return null;
10801
10799
  }
10802
10800
  var takesRest = (param) => param.type === "expression" || param.type === "statements" || param.type === "passage" || param.type === "text";
@@ -10809,23 +10807,36 @@ function trimmed(src, at) {
10809
10807
  * Read the parameters of one group from `src` (`null`: no text), which is
10810
10808
  * at `at` in the raw arguments, into `args`.
10811
10809
  */
10812
- function readGroup(params, src, args, { at: srcAt, spans }) {
10810
+ function readGroup(params, src, args, { at: srcAt, spans, toolingSpans }) {
10813
10811
  let [text, at] = trimmed(src ?? "", srcAt);
10814
10812
  const alone = !params.some((p) => p.type !== "flag" && p.required);
10815
10813
  for (const flag of params.filter((p) => p.type === "flag")) {
10816
10814
  const rest = src === null ? null : takeFlag(text, flag.name, alone);
10817
10815
  args[flag.name] = rest !== null;
10818
- if (rest) [text, at] = trimmed(slice(text, rest), at + rest[0]);
10816
+ if (rest) {
10817
+ const flagSpan = rest[0] > 0 ? [0, text.indexOf(flag.name) + flag.name.length] : [text.lastIndexOf(flag.name), text.length];
10818
+ toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
10819
+ [text, at] = trimmed(slice(text, rest), at + rest[0]);
10820
+ }
10819
10821
  }
10820
10822
  const positional = params.filter((p) => p.type !== "flag");
10821
10823
  if (positional.length === 0) return;
10822
10824
  const lastText = positional.findIndex((p, i) => takesRest(p) && !positional.slice(i + 1).some(takesRest));
10823
10825
  const restIndex = lastText < 0 ? positional.length - 1 : lastText;
10824
10826
  /** Read `param` from the text from `start` to `end`. */
10825
- const read = (param, [start, end]) => start === end ? unset(param) : readValue(param, text.slice(start, end), {
10826
- at: at + start,
10827
- spans
10828
- });
10827
+ const read = (param, [start, end], tolerant = true) => {
10828
+ if (start === end) return unset(param);
10829
+ try {
10830
+ return readValue(param, text.slice(start, end), {
10831
+ at: at + start,
10832
+ spans,
10833
+ toolingSpans
10834
+ });
10835
+ } catch (error) {
10836
+ if (toolingSpans && tolerant && error instanceof MacroArgumentError) return;
10837
+ throw error;
10838
+ }
10839
+ };
10829
10840
  if (positional.length === 1) {
10830
10841
  args[positional[0].name] = read(positional[0], [0, text.length]);
10831
10842
  return;
@@ -10836,7 +10847,7 @@ function readGroup(params, src, args, { at: srcAt, spans }) {
10836
10847
  for (const param of positional.slice(0, restIndex)) args[param.name] = from < to ? read(param, parts[from++]) : unset(param);
10837
10848
  const readTrailing = (param, span) => {
10838
10849
  try {
10839
- return read(param, span);
10850
+ return read(param, span, false);
10840
10851
  } catch (error) {
10841
10852
  if (error instanceof MacroArgumentError) return void 0;
10842
10853
  throw error;
@@ -10846,7 +10857,10 @@ function readGroup(params, src, args, { at: srcAt, spans }) {
10846
10857
  const value = from < to && !endsWithOperator(text.slice(0, parts[to - 1][0])) ? readTrailing(param, parts[to - 1]) : void 0;
10847
10858
  args[param.name] = value ?? unset(param);
10848
10859
  if (value !== void 0) to--;
10849
- else spans?.delete(param);
10860
+ else {
10861
+ spans?.delete(param);
10862
+ toolingSpans?.delete(param);
10863
+ }
10850
10864
  }
10851
10865
  const rest = positional[restIndex];
10852
10866
  args[rest.name] = from < to ? read(rest, [parts[from][0], parts[to - 1][1]]) : unset(rest);
@@ -10855,18 +10869,23 @@ function readGroup(params, src, args, { at: srcAt, spans }) {
10855
10869
  * Read `rawArgs` into the declared `parameters` (see above). With `spans`,
10856
10870
  * note there where each argument set was read.
10857
10871
  */
10858
- function parseMacroArgs(rawArgs, parameters, spans) {
10872
+ function parseMacroArgs(rawArgs, parameters, spans, toolingSpans) {
10859
10873
  const args = {};
10860
10874
  let [rest, restAt] = trimmed(rawArgs, 0);
10861
10875
  let groupStart = 0;
10862
10876
  parameters.forEach((separator, i) => {
10863
10877
  if (separator.type !== "separator") return;
10864
- const at = rest === null ? null : findSeparator(rest, separator.name);
10878
+ const at = rest === null ? null : findSeparator(rest, separator.name, !!toolingSpans);
10865
10879
  args[separator.name] = at !== null;
10880
+ if (at && toolingSpans) {
10881
+ const start = restAt + at[0] + rest.slice(at[0], at[1]).indexOf(separator.name);
10882
+ toolingSpans.set(separator, [start, start + separator.name.length]);
10883
+ }
10866
10884
  const before = at ? rest.slice(0, at[0]) : rest;
10867
10885
  readGroup(parameters.slice(groupStart, i), before, args, {
10868
10886
  at: restAt,
10869
- spans
10887
+ spans,
10888
+ toolingSpans
10870
10889
  });
10871
10890
  rest = at ? rest.slice(at[1]) : null;
10872
10891
  if (at) restAt += at[1];
@@ -10874,7 +10893,8 @@ function parseMacroArgs(rawArgs, parameters, spans) {
10874
10893
  });
10875
10894
  readGroup(parameters.slice(groupStart), rest, args, {
10876
10895
  at: restAt,
10877
- spans
10896
+ spans,
10897
+ toolingSpans
10878
10898
  });
10879
10899
  return args;
10880
10900
  }
@@ -10907,6 +10927,34 @@ function evaluatePassageName(expr, evaluate, { storyData, currentPassage }) {
10907
10927
  if (storyData && !storyData.passages.has(name)) throw noPassageError(name, currentPassage);
10908
10928
  return name;
10909
10929
  }
10930
+ /**
10931
+ * The runtime's argument grouping, tolerant of missing or unclosed strings.
10932
+ * Includes quotes, flags, separators and option keywords; offsets are into
10933
+ * rawArgs. Absent arguments have no span. Options also have their enclosing
10934
+ * parameter span, so consumers can choose the most specific overlapping span.
10935
+ * No expressions are evaluated. Parameter identities are preserved.
10936
+ */
10937
+ function macroArgumentSpans(rawArgs, parameters) {
10938
+ const spans = /* @__PURE__ */ new Map();
10939
+ parseMacroArgs(rawArgs, parameters, void 0, spans);
10940
+ const result = [];
10941
+ const add = (params, path) => {
10942
+ params.forEach((parameter, index) => {
10943
+ const parameterPath = [...path, index];
10944
+ const span = spans.get(parameter);
10945
+ if (span) result.push({
10946
+ parameter,
10947
+ parameterIndex: parameterPath[0],
10948
+ parameterPath,
10949
+ start: span[0],
10950
+ end: span[1]
10951
+ });
10952
+ if (parameter.parameters) add(parameter.parameters, parameterPath);
10953
+ });
10954
+ };
10955
+ add(parameters, []);
10956
+ return result.sort((a, b) => a.start - b.start || b.end - a.end);
10957
+ }
10910
10958
  /** The parameters of the built-in sub-macros that take arguments. */
10911
10959
  var SUB_MACRO_PARAMETERS = /* @__PURE__ */ new Map([["option", [{
10912
10960
  name: "value",
@@ -25392,4 +25440,4 @@ function validateVariableReferences(passages, declarations, macros = []) {
25392
25440
  return checkVariableReferences(list.filter((p) => !p.tags?.some((t) => NOT_MARKUP_TAGS.includes(t))), declarations, referenceOptions(macros, false, list));
25393
25441
  }
25394
25442
  //#endregion
25395
- export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, discoverMacros, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, lexJs, lexTemplate, pairMarkup, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
25443
+ export { MarkupError, SIGIL_SCOPES, checkParameterTypes, collectStoryPassageReferences, discoverMacros, effectiveWidgetDefinitions, endsWithOperator, evaluatePassageName, findCodeEnd, formatDiagnostic, formatPassage, isBlockMacro, isSigil, lexJs, lexTemplate, macroArgumentSpans, pairMarkup, parseCode, parseDeclarations, parseSelectors, parseStoryVariables, parseWidgetDef, passagePieces, passagePiecesOfTokens, passageTarget, pieceOffset, readQuoted, scanStringLiteral, splitArgs, splitIncludeFlag, splitTopLevel, stripLooseQuotes, tokenizeMarkup, tokenizeMarkupTolerant, transform, unescapeQuoted, validateStoryMarkup, validateVariableReferences, variableReferences, widgetDefinitions };
@@ -17,6 +17,9 @@ export {
17
17
  parseStoryVariables,
18
18
  parseDeclarations,
19
19
  formatDiagnostic,
20
+ parseCode,
21
+ macroArgumentSpans,
22
+ effectiveWidgetDefinitions,
20
23
  findCodeEnd,
21
24
  lexJs,
22
25
  lexTemplate,
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.61.7",
3
+ "version": "0.62.0",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
7
7
  "author": "Rohal12",
8
8
  "engines": {
9
- "node": ">=22.17"
9
+ "node": ">=24"
10
10
  },
11
11
  "publishConfig": {
12
12
  "access": "public"
@@ -57,7 +57,7 @@
57
57
  ],
58
58
  "scripts": {
59
59
  "build": "vite build && bun run scripts/dump-macro-registry.ts && bun run scripts/build-format.ts",
60
- "compile": "bun run scripts/compile-story.ts",
60
+ "compile": "node scripts/compile-story.ts",
61
61
  "preview": "bun run build && bun run compile",
62
62
  "test": "vitest run",
63
63
  "test:coverage": "vitest run --coverage",
@@ -84,7 +84,7 @@
84
84
  "zustand": "^5.0.15"
85
85
  },
86
86
  "peerDependencies": {
87
- "@rohal12/twee-ts": "^1.18.2",
87
+ "@rohal12/twee-ts": "^2.0.0",
88
88
  "happy-dom": ">=20.14.6"
89
89
  },
90
90
  "peerDependenciesMeta": {
@@ -101,7 +101,7 @@
101
101
  "devDependencies": {
102
102
  "@fast-check/vitest": "^0.5.0",
103
103
  "@preact/preset-vite": "^2.10.6",
104
- "@rohal12/twee-ts": "^1.18.2",
104
+ "@rohal12/twee-ts": "^2.0.0",
105
105
  "@types/codemirror": "^5.60.18",
106
106
  "@types/node": "^26.6.5",
107
107
  "@types/react": "^19.3.0",
@@ -48,16 +48,21 @@ export function unescapeQuoted(body: string): string {
48
48
  * Read the `"…"` or `'…'` string whose opening quote is at `start`.
49
49
  * Returns its unescaped value and the index just past the closing quote, or
50
50
  * `null` if there is no such quote at `start` or the string is unterminated.
51
+ * With `tolerant`, an unterminated string instead extends to its scanned end.
51
52
  */
52
53
  export function readQuoted(
53
54
  src: string,
54
55
  start: number,
56
+ tolerant = false,
55
57
  ): { value: string; end: number } | null {
56
58
  const quote = src[start];
57
59
  if (quote !== '"' && quote !== "'") return null;
58
60
  const { end, closed } = scanStringLiteral(src, start);
59
- if (!closed) return null;
60
- return { value: unescapeQuoted(src.slice(start + 1, end - 1)), end };
61
+ if (!closed && !tolerant) return null;
62
+ return {
63
+ value: unescapeQuoted(src.slice(start + 1, closed ? end - 1 : end)),
64
+ end,
65
+ };
61
66
  }
62
67
 
63
68
  /**
@@ -15,6 +15,7 @@
15
15
  * empty).
16
16
  */
17
17
  import { parseDelay } from '../../utils/parse-delay';
18
+ import type { Span as SourceSpan } from '../../markup/tokens';
18
19
  import type { MacroArgs, ParameterDef } from '../../registry';
19
20
  import type { StoryState } from '../../store';
20
21
  import { noPassageError } from '../../runtime-errors';
@@ -42,6 +43,8 @@ interface Place {
42
43
  /** The index in the raw arguments of the text being read. */
43
44
  at: number;
44
45
  spans: ArgSpans | undefined;
46
+ /** Full parameter spans for tolerant editor input, including keywords. */
47
+ toolingSpans?: ArgSpans;
45
48
  }
46
49
 
47
50
  /** The terms of `src`: the runs of text between its depth-0 whitespace. */
@@ -80,11 +83,18 @@ export class MacroArgumentError extends Error {
80
83
 
81
84
  /** Read `src`, at `place`, as `param` says. */
82
85
  function readValue(param: ParameterDef, src: string, place: Place): unknown {
83
- place.spans?.set(param, [place.at, place.at + src.length]);
86
+ const span: Span = [place.at, place.at + src.length];
87
+ place.spans?.set(param, span);
88
+ place.toolingSpans?.set(param, span);
84
89
  switch (param.type) {
85
90
  case 'string': {
86
91
  const value = readWholeQuoted(src);
87
- if (value === null) throw new MacroArgumentError(param, src);
92
+ if (value === null) {
93
+ if (place.toolingSpans && (src[0] === '"' || src[0] === "'")) {
94
+ return readText(src);
95
+ }
96
+ throw new MacroArgumentError(param, src);
97
+ }
88
98
  return value;
89
99
  }
90
100
  case 'text':
@@ -128,7 +138,7 @@ function matchAt(re: RegExp, src: string, pos: number): string | null {
128
138
  function readOptions(
129
139
  params: readonly ParameterDef[],
130
140
  src: string,
131
- { at, spans }: Place,
141
+ { at, spans, toolingSpans }: Place,
132
142
  ): Record<string, unknown> {
133
143
  const options: Record<string, unknown> = {};
134
144
  let i = 0;
@@ -136,9 +146,10 @@ function readOptions(
136
146
  const key = matchAt(WORD_RE, src, i);
137
147
  if (!key) {
138
148
  // Skip whitespace and stray characters, or a stray quoted string.
139
- i = readQuoted(src, i)?.end ?? i + 1;
149
+ i = readQuoted(src, i, !!toolingSpans)?.end ?? i + 1;
140
150
  continue;
141
151
  }
152
+ const keyAt = i;
142
153
  i += key.length;
143
154
 
144
155
  // A value is a quoted string, which may follow the keyword directly
@@ -147,7 +158,7 @@ function readOptions(
147
158
  let val: string | undefined;
148
159
  let j = i;
149
160
  while (j < src.length && isWhitespace(src[j]!)) j++;
150
- const quoted = readQuoted(src, j);
161
+ const quoted = readQuoted(src, j, !!toolingSpans);
151
162
  const digits = quoted || j === i ? null : matchAt(NUMBER_RE, src, j);
152
163
  if (quoted) {
153
164
  val = quoted.value;
@@ -161,8 +172,9 @@ function readOptions(
161
172
  if (param && param.type !== 'flag' && val !== undefined) {
162
173
  spans?.set(param, [at + j, at + i]);
163
174
  }
175
+ if (param) toolingSpans?.set(param, [at + keyAt, at + i]);
164
176
  // A keyword that takes a string was given anything else, or nothing
165
- if (param?.type === 'string' && !quoted) {
177
+ if (param?.type === 'string' && !quoted && !toolingSpans) {
166
178
  throw new MacroArgumentError(
167
179
  param,
168
180
  matchAt(WORD_OR_PUNCT_RE, src, j) ?? '',
@@ -210,7 +222,11 @@ function takeFlag(src: string, word: string, alone: boolean): Span | null {
210
222
  * term with terms on both sides; `=` is an assignment at depth 0, not part
211
223
  * of `==` or `!=`.
212
224
  */
213
- function findSeparator(src: string, word: string): Span | null {
225
+ function findSeparator(
226
+ src: string,
227
+ word: string,
228
+ tolerant = false,
229
+ ): Span | null {
214
230
  if (word === '=') {
215
231
  const indices = topLevelIndices(src, (ch) => ch === '=');
216
232
  for (let k = 0; k < indices.length; k++) {
@@ -224,9 +240,9 @@ function findSeparator(src: string, word: string): Span | null {
224
240
  return null;
225
241
  }
226
242
  const spans = terms(src);
227
- for (let k = 1; k < spans.length - 1; k++) {
243
+ for (let k = 1; k < spans.length - (tolerant ? 0 : 1); k++) {
228
244
  if (slice(src, spans[k]!) === word) {
229
- return [spans[k - 1]![1], spans[k + 1]![0]];
245
+ return [spans[k - 1]![1], spans[k + 1]?.[0] ?? src.length];
230
246
  }
231
247
  }
232
248
  return null;
@@ -252,7 +268,7 @@ function readGroup(
252
268
  params: readonly ParameterDef[],
253
269
  src: string | null,
254
270
  args: Record<string, unknown>,
255
- { at: srcAt, spans }: Place,
271
+ { at: srcAt, spans, toolingSpans }: Place,
256
272
  ): void {
257
273
  let [text, at] = trimmed(src ?? '', srcAt);
258
274
  // A lone word is the passage of {include inline}, not its flag
@@ -260,7 +276,14 @@ function readGroup(
260
276
  for (const flag of params.filter((p) => p.type === 'flag')) {
261
277
  const rest = src === null ? null : takeFlag(text, flag.name, alone);
262
278
  args[flag.name] = rest !== null;
263
- if (rest) [text, at] = trimmed(slice(text, rest), at + rest[0]);
279
+ if (rest) {
280
+ const flagSpan: Span =
281
+ rest[0] > 0
282
+ ? [0, text.indexOf(flag.name) + flag.name.length]
283
+ : [text.lastIndexOf(flag.name), text.length];
284
+ toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
285
+ [text, at] = trimmed(slice(text, rest), at + rest[0]);
286
+ }
264
287
  }
265
288
  const positional = params.filter((p) => p.type !== 'flag');
266
289
  if (positional.length === 0) return;
@@ -271,10 +294,21 @@ function readGroup(
271
294
  );
272
295
  const restIndex = lastText < 0 ? positional.length - 1 : lastText;
273
296
  /** Read `param` from the text from `start` to `end`. */
274
- const read = (param: ParameterDef, [start, end]: Span) =>
275
- start === end
276
- ? unset(param)
277
- : readValue(param, text.slice(start, end), { at: at + start, spans });
297
+ const read = (param: ParameterDef, [start, end]: Span, tolerant = true) => {
298
+ if (start === end) return unset(param);
299
+ try {
300
+ return readValue(param, text.slice(start, end), {
301
+ at: at + start,
302
+ spans,
303
+ toolingSpans,
304
+ });
305
+ } catch (error) {
306
+ if (toolingSpans && tolerant && error instanceof MacroArgumentError) {
307
+ return undefined;
308
+ }
309
+ throw error;
310
+ }
311
+ };
278
312
 
279
313
  // One parameter reads the whole text: no need to split it.
280
314
  if (positional.length === 1) {
@@ -292,7 +326,7 @@ function readGroup(
292
326
  // `string` that isn't quoted) belongs to the rest, as in {meter $hp 100}
293
327
  const readTrailing = (param: ParameterDef, span: Span) => {
294
328
  try {
295
- return read(param, span);
329
+ return read(param, span, false);
296
330
  } catch (error) {
297
331
  if (error instanceof MacroArgumentError) return undefined;
298
332
  throw error;
@@ -306,7 +340,10 @@ function readGroup(
306
340
  args[param.name] = value ?? unset(param);
307
341
  if (value !== undefined) to--;
308
342
  // A term it didn't take
309
- else spans?.delete(param);
343
+ else {
344
+ spans?.delete(param);
345
+ toolingSpans?.delete(param);
346
+ }
310
347
  }
311
348
  const rest = positional[restIndex]!;
312
349
  args[rest.name] =
@@ -328,6 +365,7 @@ export function parseMacroArgs<const P extends readonly ParameterDef[]>(
328
365
  rawArgs: string,
329
366
  parameters: P,
330
367
  spans?: ArgSpans,
368
+ toolingSpans?: ArgSpans,
331
369
  ): MacroArgs<P> {
332
370
  const args: Record<string, unknown> = {};
333
371
  // The text after the last separator read, null once one is missing
@@ -335,18 +373,31 @@ export function parseMacroArgs<const P extends readonly ParameterDef[]>(
335
373
  let groupStart = 0;
336
374
  parameters.forEach((separator, i) => {
337
375
  if (separator.type !== 'separator') return;
338
- const at = rest === null ? null : findSeparator(rest, separator.name);
376
+ const at =
377
+ rest === null
378
+ ? null
379
+ : findSeparator(rest, separator.name, !!toolingSpans);
339
380
  args[separator.name] = at !== null;
381
+ if (at && toolingSpans) {
382
+ const start =
383
+ restAt + at[0] + rest!.slice(at[0], at[1]).indexOf(separator.name);
384
+ toolingSpans.set(separator, [start, start + separator.name.length]);
385
+ }
340
386
  const before = at ? rest!.slice(0, at[0]) : rest;
341
387
  readGroup(parameters.slice(groupStart, i), before, args, {
342
388
  at: restAt,
343
389
  spans,
390
+ toolingSpans,
344
391
  });
345
392
  rest = at ? rest!.slice(at[1]) : null;
346
393
  if (at) restAt += at[1];
347
394
  groupStart = i + 1;
348
395
  });
349
- readGroup(parameters.slice(groupStart), rest, args, { at: restAt, spans });
396
+ readGroup(parameters.slice(groupStart), rest, args, {
397
+ at: restAt,
398
+ spans,
399
+ toolingSpans,
400
+ });
350
401
  return args as MacroArgs<P>;
351
402
  }
352
403
 
@@ -399,3 +450,46 @@ export function readBoundVariable(rawArgs: string): string {
399
450
  const first = terms(src)[0];
400
451
  return first ? slice(src, first) : '';
401
452
  }
453
+
454
+ /** A consumed argument and its declared parameter, with UTF-16 source offsets. */
455
+ export interface MacroArgumentSpan extends SourceSpan {
456
+ /** The original parameter object, including for nested keyword options. */
457
+ parameter: ParameterDef;
458
+ /** Index of the top-level parameter, for signature help. */
459
+ parameterIndex: number;
460
+ /** Indices through nested options, starting at parameterIndex. */
461
+ parameterPath: number[];
462
+ }
463
+
464
+ /**
465
+ * The runtime's argument grouping, tolerant of missing or unclosed strings.
466
+ * Includes quotes, flags, separators and option keywords; offsets are into
467
+ * rawArgs. Absent arguments have no span. Options also have their enclosing
468
+ * parameter span, so consumers can choose the most specific overlapping span.
469
+ * No expressions are evaluated. Parameter identities are preserved.
470
+ */
471
+ export function macroArgumentSpans(
472
+ rawArgs: string,
473
+ parameters: readonly ParameterDef[],
474
+ ): MacroArgumentSpan[] {
475
+ const spans: ArgSpans = new Map();
476
+ parseMacroArgs(rawArgs, parameters, undefined, spans);
477
+ const result: MacroArgumentSpan[] = [];
478
+ const add = (params: readonly ParameterDef[], path: number[]) => {
479
+ params.forEach((parameter, index) => {
480
+ const parameterPath = [...path, index];
481
+ const span = spans.get(parameter);
482
+ if (span)
483
+ result.push({
484
+ parameter,
485
+ parameterIndex: parameterPath[0]!,
486
+ parameterPath,
487
+ start: span[0],
488
+ end: span[1],
489
+ });
490
+ if (parameter.parameters) add(parameter.parameters, parameterPath);
491
+ });
492
+ };
493
+ add(parameters, []);
494
+ return result.sort((a, b) => a.start - b.start || b.end - a.end);
495
+ }