@rohal12/spindle 0.62.0 → 0.62.2

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.
@@ -3682,13 +3682,15 @@ var BLOCK_MACROS = new NameSet([
3682
3682
  * definition is, whereas the macros in BLOCK_MACROS stay blocks.
3683
3683
  */
3684
3684
  var BLOCK_WIDGETS = new NameSet();
3685
+ /** All widgets, including inline ones, override built-in parsing semantics. */
3686
+ var WIDGETS = new NameSet();
3685
3687
  /** Classification owned by defineMacro, independent of explicit registrations. */
3686
3688
  var DEFINED_BLOCK_MACROS = new NameSet();
3687
3689
  /** Macros whose body is JavaScript source, kept verbatim. */
3688
3690
  var RAW_BODY_MACROS = /* @__PURE__ */ new Set(["do"]);
3689
3691
  /** Whether a macro's body is JavaScript, kept verbatim (`{do}`). */
3690
- function isRawMacro(name) {
3691
- return RAW_BODY_MACROS.has(name);
3692
+ function isRawMacro(name, widget = WIDGETS.has(name)) {
3693
+ return RAW_BODY_MACROS.has(name.toLowerCase()) && !widget;
3692
3694
  }
3693
3695
  /** Whether a macro takes a body closed by `{/name}`. */
3694
3696
  function isBlockMacro(name) {
@@ -3747,7 +3749,8 @@ function astNode({ token, body }) {
3747
3749
  };
3748
3750
  if (!body) return withSelectors$1(node, token);
3749
3751
  const children = buildAst(body.children);
3750
- if (!BRANCHING.has(name) && body.branches.length === 0) {
3752
+ const branching = BRANCHING.has(name) && !WIDGETS.has(name);
3753
+ if (!branching && body.branches.length === 0) {
3751
3754
  node.children = children;
3752
3755
  return withSelectors$1(node, token);
3753
3756
  }
@@ -3755,9 +3758,9 @@ function astNode({ token, body }) {
3755
3758
  rawArgs: tag.rawArgs,
3756
3759
  children: branchChildren
3757
3760
  }, tag);
3758
- if (!BRANCHING.has(name)) node.children = children;
3759
- node.branches = [...BRANCHING.has(name) ? [branch(token, children)] : [], ...body.branches.map(({ tag, children: c }) => branch(tag, buildAst(c)))];
3760
- return BRANCHING.has(name) ? node : withSelectors$1(node, token);
3761
+ if (!branching) node.children = children;
3762
+ node.branches = [...branching ? [branch(token, children)] : [], ...body.branches.map(({ tag, children: c }) => branch(tag, buildAst(c)))];
3763
+ return branching ? node : withSelectors$1(node, token);
3761
3764
  }
3762
3765
  }
3763
3766
  }
@@ -3777,6 +3780,25 @@ function lineColumn(text, offset) {
3777
3780
  column: offset - lineStart + 1
3778
3781
  };
3779
3782
  }
3783
+ /** Index one source once; offsets and columns count UTF-16 code units. */
3784
+ function sourcePositions(text) {
3785
+ const starts = [0];
3786
+ for (let i = 0; i < text.length; i++) if (text[i] === "\n") starts.push(i + 1);
3787
+ return (offset) => {
3788
+ let low = 0;
3789
+ let high = starts.length;
3790
+ while (low < high) {
3791
+ const mid = low + high >>> 1;
3792
+ if (starts[mid] <= offset) low = mid + 1;
3793
+ else high = mid;
3794
+ }
3795
+ const line = Math.max(1, low);
3796
+ return {
3797
+ line,
3798
+ column: offset - starts[line - 1] + 1
3799
+ };
3800
+ };
3801
+ }
3780
3802
  //#endregion
3781
3803
  //#region src/markup/pair.ts
3782
3804
  /**
@@ -3828,9 +3850,11 @@ function pairMarkup(tokens, options = {}) {
3828
3850
  };
3829
3851
  const errors = [];
3830
3852
  const noticedAtEnd = (tokens[tokens.length - 1]?.end ?? 0) + 1;
3853
+ let position;
3831
3854
  const where = (offset) => {
3832
3855
  if (options.source === void 0) return `offset ${offset}`;
3833
- const { line, column } = lineColumn(options.source, offset);
3856
+ position ?? (position = sourcePositions(options.source));
3857
+ const { line, column } = position(offset);
3834
3858
  return `line ${line}, column ${column}`;
3835
3859
  };
3836
3860
  const report = (code, token, message, noticedAt, data) => {
@@ -10243,7 +10267,8 @@ function analyzeMarkup(source, options = {}) {
10243
10267
  };
10244
10268
  const inDamage = (start) => errors.some((e, i) => start >= damage[i] && start <= e.offset);
10245
10269
  const noticed = errors.map((e, i) => [damage[i] + .5, e]);
10246
- for (const error of paired.errors) if (!inDamage(error.start)) noticed.push([error.noticedAt, pairingError(source, error)]);
10270
+ const position = paired.errors.length ? sourcePositions(source) : void 0;
10271
+ for (const error of paired.errors) if (!inDamage(error.start)) noticed.push([error.noticedAt, pairingError(position, error)]);
10247
10272
  noticed.sort((a, b) => a[0] - b[0]);
10248
10273
  return {
10249
10274
  tokens,
@@ -10262,8 +10287,8 @@ function parseMarkup(source, options = {}) {
10262
10287
  return buildAst(nodes);
10263
10288
  }
10264
10289
  /** A pairing problem as the MarkupError it is for `source`. */
10265
- function pairingError(source, error) {
10266
- const { line, column } = lineColumn(source, error.start);
10290
+ function pairingError(position, error) {
10291
+ const { line, column } = position(error.start);
10267
10292
  return new MarkupError(error.message, error.start, line, column, error.code, error.end, error.data);
10268
10293
  }
10269
10294
  /**
@@ -10310,6 +10335,7 @@ function scanMarkupTolerant(source, options = {}) {
10310
10335
  const tokens = [];
10311
10336
  const errors = [];
10312
10337
  const damage = [];
10338
+ let position;
10313
10339
  const lastBrace = source.lastIndexOf("}");
10314
10340
  const { closeBrace } = {
10315
10341
  ...defaultHooks,
@@ -10340,7 +10366,8 @@ function scanMarkupTolerant(source, options = {}) {
10340
10366
  break;
10341
10367
  }
10342
10368
  const at = base + result.offset;
10343
- const { line, column } = lineColumn(source, at);
10369
+ position ?? (position = sourcePositions(source));
10370
+ const { line, column } = position(at);
10344
10371
  errors.push(new MarkupError(result.reason, at, line, column, result.code, base + result.end));
10345
10372
  let cut = result.offset;
10346
10373
  let prefix = attempt(rest.slice(0, cut), base);
@@ -11087,10 +11114,10 @@ function parameterLookup(macros) {
11087
11114
  const widgets = new NameMap();
11088
11115
  for (const { name, parameters: params, interpolate, widget } of macros) {
11089
11116
  if (params) parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
11090
- const declared = widget && widgetParameters(widget.params, widget.holds);
11091
- if (declared) widgets.set(name, declared);
11117
+ if (widget) widgets.set(name, widgetParameters(widget.params, widget.holds) ?? []);
11092
11118
  }
11093
11119
  const lookup = (name) => {
11120
+ if (widgets.has(name)) return void 0;
11094
11121
  let params = parameters.get(name);
11095
11122
  if (!params) {
11096
11123
  const sub = subMacroParameters(name);
@@ -11163,7 +11190,8 @@ function* codeAndText(src, tokens, parametersOf) {
11163
11190
  }
11164
11191
  else if (token.type === "macro" && !token.isClose) {
11165
11192
  const name = token.name.toLowerCase();
11166
- if (name === "do") {
11193
+ const widget = parametersOf.widget?.(name);
11194
+ if (name === "do" && !widget) {
11167
11195
  const close = closeOfTextBody(t, name);
11168
11196
  if (close < 0) continue;
11169
11197
  yield {
@@ -11177,7 +11205,7 @@ function* codeAndText(src, tokens, parametersOf) {
11177
11205
  continue;
11178
11206
  }
11179
11207
  const args = token.rawArgs;
11180
- if (PASSAGE_BODIES.has(name)) {
11208
+ if (PASSAGE_BODIES.has(name) && !widget) {
11181
11209
  const close = closeOfTextBody(t, name);
11182
11210
  if (close > t + 1) {
11183
11211
  const text = src.slice(token.end, tokens[close].start);
@@ -11195,7 +11223,7 @@ function* codeAndText(src, tokens, parametersOf) {
11195
11223
  if (!args) continue;
11196
11224
  const label = `{${token.name} ${args}}`;
11197
11225
  const argsAt = token.argsStart;
11198
- if (CONDITION_MACROS.has(name)) {
11226
+ if (CONDITION_MACROS.has(name) && !widget) {
11199
11227
  yield {
11200
11228
  kind: "code",
11201
11229
  code: args,
@@ -11207,7 +11235,6 @@ function* codeAndText(src, tokens, parametersOf) {
11207
11235
  }
11208
11236
  const params = parametersOf(name);
11209
11237
  if (params) yield* argPieces(args, argsAt, params, token.name, label);
11210
- const widget = parametersOf.widget?.(name);
11211
11238
  if (widget) yield* widgetPieces(args, argsAt, widget, token.name, label);
11212
11239
  }
11213
11240
  }
@@ -11219,14 +11246,16 @@ function* codeAndText(src, tokens, parametersOf) {
11219
11246
  * `src`. In source order, a nested piece after the text it is in.
11220
11247
  */
11221
11248
  function* passagePiecesOf(src, tokens, parametersOf, options = {}) {
11222
- yield* expand(src, src, tokens, parametersOf, options, (i) => i, void 0);
11249
+ let position;
11250
+ const locate = (offset) => (position ?? (position = sourcePositions(src)))(offset);
11251
+ yield* expand(src, src, tokens, parametersOf, options, (i) => i, void 0, locate);
11223
11252
  }
11224
11253
  /**
11225
11254
  * The pieces of `tokens`, the tokens of `src`, which is the text described by
11226
11255
  * `where` (none for `root`, the markup of the whole passage), and whose
11227
11256
  * offsets `toRoot` turns into offsets in `root`.
11228
11257
  */
11229
- function* expand(root, src, tokens, parametersOf, options, toRoot, where) {
11258
+ function* expand(root, src, tokens, parametersOf, options, toRoot, where, locate) {
11230
11259
  for (const flat of codeAndText(src, tokens, parametersOf)) {
11231
11260
  const piece = where ? nestedPiece(flat, toRoot, where) : flat;
11232
11261
  if (flat.kind !== "text" || !flat.text.includes("{")) {
@@ -11236,17 +11265,20 @@ function* expand(root, src, tokens, parametersOf, options, toRoot, where) {
11236
11265
  const toText = (i) => toRoot(pieceOffset(flat, i));
11237
11266
  const inner = analyzeMarkup(flat.text, {
11238
11267
  text: true,
11239
- hooks: options.isBlock && { isBlock: options.isBlock }
11268
+ hooks: {
11269
+ ...options.isBlock && { isBlock: options.isBlock },
11270
+ isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0)
11271
+ }
11240
11272
  });
11241
11273
  yield {
11242
11274
  ...piece,
11243
11275
  tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
11244
11276
  errors: inner.errors.map((e) => {
11245
- const { line, column } = lineColumn(root, toText(e.offset));
11277
+ const { line, column } = locate(toText(e.offset));
11246
11278
  return new MarkupError(e.reason, toText(e.offset), line, column, e.code, toText(e.end), e.data);
11247
11279
  })
11248
11280
  };
11249
- yield* expand(root, flat.text, inner.tokens, parametersOf, options, toText, flat.where);
11281
+ yield* expand(root, flat.text, inner.tokens, parametersOf, options, toText, flat.where, locate);
11250
11282
  }
11251
11283
  }
11252
11284
  /** `piece`, of a text in another, with its offsets turned by `toRoot`. */
@@ -11774,14 +11806,23 @@ function distance(a, b) {
11774
11806
  }
11775
11807
  /** The known name closest to `name`, if one is close. */
11776
11808
  function closestName(name, names) {
11809
+ if (name.length > 256) return void 0;
11777
11810
  const lower = name.toLowerCase();
11778
11811
  let best;
11779
11812
  let bestDistance = Math.max(2, Math.floor(lower.length / 3)) + 1;
11813
+ let budget = 1e5;
11814
+ let candidates = 1e3;
11780
11815
  for (const candidate of names) {
11816
+ if (--candidates < 0) break;
11817
+ if (candidate.length > 256) continue;
11818
+ if (Math.abs(candidate.length - lower.length) >= bestDistance) continue;
11819
+ budget -= lower.length * candidate.length;
11820
+ if (budget < 0) break;
11781
11821
  const d = distance(lower, candidate.toLowerCase());
11782
11822
  if (d < bestDistance) {
11783
11823
  best = candidate;
11784
11824
  bestDistance = d;
11825
+ if (d === 0) break;
11785
11826
  }
11786
11827
  }
11787
11828
  return best;
@@ -11806,12 +11847,19 @@ function widgetName(rawArgs) {
11806
11847
  */
11807
11848
  function validateMarkup(passages, options) {
11808
11849
  const diagnostics = [];
11850
+ const positions = /* @__PURE__ */ new Map();
11809
11851
  const hooks = {
11810
11852
  ...options.isBlockMacro && { isBlock: options.isBlockMacro },
11811
- ...options.branchParents && { branchParents: options.branchParents }
11853
+ ...options.branchParents && { branchParents: options.branchParents },
11854
+ isRaw: (name) => isRawMacro(name, options.parametersOf ? options.parametersOf.widget?.(name) !== void 0 : void 0)
11812
11855
  };
11813
11856
  const report = (passage, start, end, code, message, data) => {
11814
- const { line, column } = lineColumn(passage.content, start);
11857
+ let position = positions.get(passage);
11858
+ if (!position) {
11859
+ position = sourcePositions(passage.content);
11860
+ positions.set(passage, position);
11861
+ }
11862
+ const { line, column } = position(start);
11815
11863
  const d = {
11816
11864
  passage: passage.name,
11817
11865
  line,
@@ -11857,7 +11905,7 @@ function validateMarkup(passages, options) {
11857
11905
  continue;
11858
11906
  }
11859
11907
  try {
11860
- const tokens = tokenizeMarkup(passage.content);
11908
+ const tokens = tokenizeMarkup(passage.content, { hooks });
11861
11909
  addWidgets(tokens);
11862
11910
  if (!reported) continue;
11863
11911
  parseMarkup(passage.content, { hooks });
@@ -12356,10 +12404,14 @@ var Reader = class {
12356
12404
  * The tokens of markup, or none if it is malformed (validateMarkup reports
12357
12405
  * that, with its position); in tolerant mode, those of the well-formed parts.
12358
12406
  */
12359
- function tokensOf(text, textMode, { tolerant } = {}) {
12360
- if (tolerant) return tokenizeMarkupTolerant(text, { text: textMode }).tokens;
12407
+ function tokensOf(text, textMode, { tolerant, parametersOf } = {}) {
12408
+ const options = {
12409
+ text: textMode,
12410
+ hooks: parametersOf && { isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0) }
12411
+ };
12412
+ if (tolerant) return tokenizeMarkupTolerant(text, options).tokens;
12361
12413
  try {
12362
- return tokenizeMarkup(text, { text: textMode });
12414
+ return tokenizeMarkup(text, options);
12363
12415
  } catch (err) {
12364
12416
  if (err instanceof MarkupError) return [];
12365
12417
  throw err;
@@ -12427,7 +12479,7 @@ function shapeSchema(shape) {
12427
12479
  function initializerSyntaxError(expr) {
12428
12480
  const prefix = "return (";
12429
12481
  try {
12430
- parse$1(prefix + expr + ")", {
12482
+ parse$1(prefix + expr + "\n)", {
12431
12483
  ecmaVersion: "latest",
12432
12484
  allowReturnOutsideFunction: true
12433
12485
  });
@@ -12536,7 +12588,7 @@ function parseStoryVariables(content, sigil = "$") {
12536
12588
  const expr = content.slice(valueStart, valueEnd);
12537
12589
  let value;
12538
12590
  try {
12539
- value = new Function("return (" + expr + ")")();
12591
+ value = new Function("return (" + expr + "\n)")();
12540
12592
  } catch (err) {
12541
12593
  throw new Error(`${passageName}: Failed to evaluate "${sigil}${name} = ${expr}": ${errorMessage(err)}`);
12542
12594
  }
@@ -12769,7 +12821,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
12769
12821
  else if (token.type === "macro" && !token.isClose) {
12770
12822
  scanArgs(token, parametersOf, at, emit, options);
12771
12823
  scanSelectors(content, token, at, emit, options);
12772
- if (storeVarMacros.has(token.name.toLowerCase())) {
12824
+ if (storeVarMacros.has(token.name.toLowerCase()) && !parametersOf.widget?.(token.name)) {
12773
12825
  const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
12774
12826
  const first = token.rawArgs.trim().split(/\s+/)[0] ?? "";
12775
12827
  const quoted = QUOTED_VAR_ARG_RE.exec(first);
@@ -12785,7 +12837,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
12785
12837
  });
12786
12838
  } else if (!/^["'`]/.test(first)) scanCode(first, (i) => at(token.argsStart + lead + i), emit);
12787
12839
  }
12788
- if (token.name.toLowerCase() === "do") {
12840
+ if (token.name.toLowerCase() === "do" && !parametersOf.widget?.(token.name)) {
12789
12841
  let close = t + 1;
12790
12842
  while (close < tokens.length) {
12791
12843
  const c = tokens[close];
@@ -12895,6 +12947,8 @@ var Bindings = class {
12895
12947
  this.byOpen = /* @__PURE__ */ new Map();
12896
12948
  this.byClose = /* @__PURE__ */ new Map();
12897
12949
  this.functions = /* @__PURE__ */ new Map();
12950
+ this.functionStarts = /* @__PURE__ */ new Map();
12951
+ this.facts = /* @__PURE__ */ new Map();
12898
12952
  this.top = {
12899
12953
  start: -1,
12900
12954
  end: Infinity
@@ -12910,6 +12964,18 @@ var Bindings = class {
12910
12964
  * (given another, or one of its `properties` set) where the use can follow.
12911
12965
  */
12912
12966
  objectOf(name, at, properties) {
12967
+ let names = this.facts.get(properties);
12968
+ if (!names) this.facts.set(properties, names = /* @__PURE__ */ new Map());
12969
+ let bindings = names.get(name);
12970
+ if (!bindings) {
12971
+ bindings = this.readBindings(name, properties);
12972
+ names.set(name, bindings);
12973
+ }
12974
+ const found = this.innermostVisible(bindings, at);
12975
+ return found.length === 1 ? found[0].object : void 0;
12976
+ }
12977
+ /** Declaration and write facts are immutable for this source and property set. */
12978
+ readBindings(name, properties) {
12913
12979
  const { code } = this;
12914
12980
  const escaped = name.replace(/\$/g, "\\$");
12915
12981
  const bindings = [];
@@ -12919,8 +12985,7 @@ var Bindings = class {
12919
12985
  }
12920
12986
  const declarations = bindings.filter((b) => !b.write);
12921
12987
  for (const b of bindings) if (b.write) b.scope = this.innermostVisible(declarations, b.at)[0]?.scope ?? this.top;
12922
- const found = this.innermostVisible(bindings, at);
12923
- return found.length === 1 ? found[0].object : void 0;
12988
+ return bindings;
12924
12989
  }
12925
12990
  /**
12926
12991
  * Of the `bindings` the use at `at` can see, those in the innermost scope:
@@ -12997,7 +13062,13 @@ var Bindings = class {
12997
13062
  }
12998
13063
  /** The start of the function that has `index` in its body, or -1. */
12999
13064
  functionStart(index) {
13000
- for (let g = this.innermost(index, "{"); g; g = g.parent) if (g.kind === "{" && this.isFunctionBody(g)) return g.open;
13065
+ const known = this.functionStarts.get(index);
13066
+ if (known !== void 0) return known;
13067
+ for (let g = this.innermost(index, "{"); g; g = g.parent) if (g.kind === "{" && this.isFunctionBody(g)) {
13068
+ this.functionStarts.set(index, g.open);
13069
+ return g.open;
13070
+ }
13071
+ this.functionStarts.set(index, -1);
13001
13072
  return -1;
13002
13073
  }
13003
13074
  scopeOf(group) {
@@ -13564,6 +13635,7 @@ function macroOf(config) {
13564
13635
  function discoverMacros(source) {
13565
13636
  const { code, regexes } = codeOnly(source);
13566
13637
  const found = [];
13638
+ const configs = /* @__PURE__ */ new Map();
13567
13639
  let bindings;
13568
13640
  for (const call of code.matchAll(CALL_RE)) {
13569
13641
  let at = call.index + call[0].length;
@@ -13575,12 +13647,15 @@ function discoverMacros(source) {
13575
13647
  if (object === void 0) continue;
13576
13648
  at = object;
13577
13649
  }
13578
- const reader = new ConfigReader(source, {
13579
- goal: "statements",
13580
- regexes
13581
- });
13582
- reader.i = at;
13583
- const config = reader.datum();
13650
+ if (!configs.has(at)) {
13651
+ const reader = new ConfigReader(source, {
13652
+ goal: "statements",
13653
+ regexes
13654
+ });
13655
+ reader.i = at;
13656
+ configs.set(at, reader.datum());
13657
+ }
13658
+ const config = configs.get(at);
13584
13659
  const macro = config && macroOf(config);
13585
13660
  if (macro) found.push(macro);
13586
13661
  }
@@ -24447,18 +24522,8 @@ function markdownOptions(options) {
24447
24522
  //#region src/format/source-lines.ts
24448
24523
  /** Index a source once; locate zero-based lines without rescanning its prefixes. */
24449
24524
  function sourceLines(source) {
24450
- const starts = [0];
24451
- for (let i = 0; i < source.length; i++) if (source[i] === "\n") starts.push(i + 1);
24452
- return (offset) => {
24453
- let low = 0;
24454
- let high = starts.length;
24455
- while (low < high) {
24456
- const middle = low + high >>> 1;
24457
- if (starts[middle] <= offset) low = middle + 1;
24458
- else high = middle;
24459
- }
24460
- return Math.max(0, low - 1);
24461
- };
24525
+ const position = sourcePositions(source);
24526
+ return (offset) => position(offset).line - 1;
24462
24527
  }
24463
24528
  //#endregion
24464
24529
  //#region src/format/markdown-lines.ts
@@ -25361,7 +25426,9 @@ function blockLookup(macros) {
25361
25426
  * The macros are those the markup may use, built-in and user-defined.
25362
25427
  */
25363
25428
  function passagePieces(source, macros = []) {
25364
- return passagePiecesOfTokens(source, macros, tokenizeMarkupTolerant(source).tokens);
25429
+ const all = [...macros];
25430
+ const parametersOf = parameterLookup(all);
25431
+ return passagePiecesOfTokens(source, all, tokenizeMarkupTolerant(source, { hooks: { isRaw: (name) => isRawMacro(name, parametersOf.widget?.(name) !== void 0) } }).tokens);
25365
25432
  }
25366
25433
  /**
25367
25434
  * `passagePieces` for a caller that has the tokens of
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.62.0",
3
+ "version": "0.62.2",
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
@@ -28,12 +28,7 @@
28
28
  */
29
29
  import type { HtmlToken, Token } from './markup/tokens';
30
30
  import { isCodeAttribute, splitSigilTemplate } from './markup/code-attributes';
31
- import {
32
- analyzeMarkup,
33
- lineColumn,
34
- MarkupError,
35
- mapOffsets,
36
- } from './markup/parse';
31
+ import { analyzeMarkup, MarkupError, mapOffsets } from './markup/parse';
37
32
  import {
38
33
  CodeSyntaxError,
39
34
  parseCode,
@@ -53,6 +48,8 @@ import { subMacroParameters } from './components/macros/option-utils';
53
48
  import { splitArgSpans } from './components/macros/arg-utils';
54
49
  import { NameMap } from './utils/macro-names';
55
50
  import { hasOwn } from './utils/namespace';
51
+ import { isRawMacro } from './markup/ast';
52
+ import { sourcePositions } from './markup/line-column';
56
53
 
57
54
  /** While a pass runs: the code it parsed so far, by goal and source. */
58
55
  let parses: Map<string, ParsedCode | CodeSyntaxError> | null = null;
@@ -226,9 +223,10 @@ export function widgetParameters(
226
223
  export interface ParametersOf {
227
224
  (macro: string): readonly ParameterDef[] | undefined;
228
225
  /**
229
- * The parameters of the widget `name` if it declares what some argument
230
- * holds. Its arguments are read as a widget call reads them (separated by
231
- * commas or spaces, see splitArgs), not by parseMacroArgs.
226
+ * The parameters of the widget `name`, or an empty array if it declares
227
+ * no holds. Its presence identifies a widget even without holds, so a
228
+ * shadowed macro's metadata cannot apply. Arguments are separated by
229
+ * commas or spaces (see splitArgs), not by parseMacroArgs.
232
230
  */
233
231
  widget?(name: string): readonly WidgetParameter[] | undefined;
234
232
  }
@@ -278,10 +276,11 @@ export function parameterLookup(
278
276
  for (const { name, parameters: params, interpolate, widget } of macros) {
279
277
  if (params)
280
278
  parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
281
- const declared = widget && widgetParameters(widget.params, widget.holds);
282
- if (declared) widgets.set(name, declared);
279
+ if (widget)
280
+ widgets.set(name, widgetParameters(widget.params, widget.holds) ?? []);
283
281
  }
284
282
  const lookup: ParametersOf = (name) => {
283
+ if (widgets.has(name)) return undefined;
285
284
  let params = parameters.get(name);
286
285
  if (!params) {
287
286
  const sub = subMacroParameters(name);
@@ -396,7 +395,8 @@ export function* codeAndText(
396
395
  }
397
396
  } else if (token.type === 'macro' && !token.isClose) {
398
397
  const name = token.name.toLowerCase();
399
- if (name === 'do') {
398
+ const widget = parametersOf.widget?.(name);
399
+ if (name === 'do' && !widget) {
400
400
  const close = closeOfTextBody(t, name);
401
401
  if (close < 0) continue;
402
402
  const body = src.slice(token.end, tokens[close]!.start);
@@ -411,7 +411,7 @@ export function* codeAndText(
411
411
  continue;
412
412
  }
413
413
  const args = token.rawArgs;
414
- if (PASSAGE_BODIES.has(name)) {
414
+ if (PASSAGE_BODIES.has(name) && !widget) {
415
415
  // The body names the passage when it is only text
416
416
  const close = closeOfTextBody(t, name);
417
417
  if (close > t + 1) {
@@ -430,7 +430,7 @@ export function* codeAndText(
430
430
  if (!args) continue;
431
431
  const label = `{${token.name} ${args}}`;
432
432
  const argsAt = token.argsStart;
433
- if (CONDITION_MACROS.has(name)) {
433
+ if (CONDITION_MACROS.has(name) && !widget) {
434
434
  yield {
435
435
  kind: 'code',
436
436
  code: args,
@@ -442,7 +442,6 @@ export function* codeAndText(
442
442
  }
443
443
  const params = parametersOf(name);
444
444
  if (params) yield* argPieces(args, argsAt, params, token.name, label);
445
- const widget = parametersOf.widget?.(name);
446
445
  if (widget) yield* widgetPieces(args, argsAt, widget, token.name, label);
447
446
  }
448
447
  }
@@ -469,7 +468,19 @@ export function* passagePiecesOf(
469
468
  parametersOf: ParametersOf,
470
469
  options: PieceOptions = {},
471
470
  ): Generator<Piece> {
472
- yield* expand(src, src, tokens, parametersOf, options, (i) => i, undefined);
471
+ let position: ReturnType<typeof sourcePositions> | undefined;
472
+ const locate = (offset: number) =>
473
+ (position ??= sourcePositions(src))(offset);
474
+ yield* expand(
475
+ src,
476
+ src,
477
+ tokens,
478
+ parametersOf,
479
+ options,
480
+ (i) => i,
481
+ undefined,
482
+ locate,
483
+ );
473
484
  }
474
485
 
475
486
  /**
@@ -485,6 +496,7 @@ function* expand(
485
496
  options: PieceOptions,
486
497
  toRoot: (offset: number) => number,
487
498
  where: string | undefined,
499
+ locate: ReturnType<typeof sourcePositions>,
488
500
  ): Generator<Piece> {
489
501
  for (const flat of codeAndText(src, tokens, parametersOf)) {
490
502
  const piece = where ? nestedPiece(flat, toRoot, where) : flat;
@@ -496,13 +508,17 @@ function* expand(
496
508
  const toText = (i: number) => toRoot(pieceOffset(flat, i));
497
509
  const inner = analyzeMarkup(flat.text, {
498
510
  text: true,
499
- hooks: options.isBlock && { isBlock: options.isBlock },
511
+ hooks: {
512
+ ...(options.isBlock && { isBlock: options.isBlock }),
513
+ isRaw: (name) =>
514
+ isRawMacro(name, parametersOf.widget?.(name) !== undefined),
515
+ },
500
516
  });
501
517
  yield {
502
518
  ...(piece as TextPiece),
503
519
  tokens: inner.tokens.map((t) => mapOffsets(t, toText)),
504
520
  errors: inner.errors.map((e) => {
505
- const { line, column } = lineColumn(root, toText(e.offset));
521
+ const { line, column } = locate(toText(e.offset));
506
522
  return new MarkupError(
507
523
  e.reason,
508
524
  toText(e.offset),
@@ -522,6 +538,7 @@ function* expand(
522
538
  options,
523
539
  toText,
524
540
  flat.where,
541
+ locate,
525
542
  );
526
543
  }
527
544
  }