@rohal12/spindle 0.59.22 → 0.59.25

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.
@@ -1,7 +1,11 @@
1
1
  import type { Passage } from './parser';
2
- import type { Token } from './markup/tokens';
3
- import { MarkupError, tokenizeMarkup } from './markup/parse';
4
- import { isCodeAttribute, splitSigilTemplate } from './markup/code-attributes';
2
+ import type { Spans, Token } from './markup/tokens';
3
+ import {
4
+ MarkupError,
5
+ tokenizeMarkup,
6
+ tokenizeMarkupTolerant,
7
+ } from './markup/parse';
8
+ import { isCodeAttribute } from './markup/code-attributes';
5
9
  import { errorMessage } from './utils/error-message';
6
10
  import {
7
11
  CodeSyntaxError,
@@ -11,19 +15,28 @@ import {
11
15
  } from './js-lexer';
12
16
  import {
13
17
  argPieces,
18
+ attributeValues,
19
+ sigilExpressions,
14
20
  parseOrError,
21
+ pieceOffset,
15
22
  withParseCache,
16
23
  type ParametersOf,
17
24
  } from './code-check';
18
25
  import { getMacroParameters, type ParameterDef } from './registry';
19
26
  import { NOT_MARKUP } from './markup/validate';
20
27
  import { createNamespace, variableNameError } from './utils/namespace';
28
+ import { staticLiteral, type LiteralShape } from './static-literal';
21
29
 
22
30
  /**
23
- * The tokens of markup, or none if it is malformed: validateMarkup reports
24
- * that, with its position.
31
+ * The tokens of markup, or none if it is malformed (validateMarkup reports
32
+ * that, with its position); in tolerant mode, those of the well-formed parts.
25
33
  */
26
- function tokensOf(text: string, textMode: boolean): Token[] {
34
+ function tokensOf(
35
+ text: string,
36
+ textMode: boolean,
37
+ { tolerant }: { tolerant?: boolean } = {},
38
+ ): Token[] {
39
+ if (tolerant) return tokenizeMarkupTolerant(text, { text: textMode }).tokens;
27
40
  try {
28
41
  return tokenizeMarkup(text, { text: textMode });
29
42
  } catch (err) {
@@ -54,8 +67,8 @@ function declarationRegex(sigil: string): RegExp {
54
67
  const escaped = sigil.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
55
68
  return new RegExp(`^${escaped}(\\w+)\\s*=\\s*(.+)$`);
56
69
  }
57
- /** A `$name` reference with its dot path, at a `$` the lexer found. */
58
- const VAR_PATH_RE = /\$(\w+(?:\.\w+)*)/y;
70
+ /** A `$name` or `%name` reference with its dot path, at a sigil the lexer found. */
71
+ const VAR_PATH_RE = /([$%])(\w+(?:\.\w+)*)/y;
59
72
  /** Quoted first argument of an input macro naming a story variable. */
60
73
  const QUOTED_VAR_ARG_RE = /^["']\$(\w+(?:\.\w+)*)["']?$/;
61
74
 
@@ -102,32 +115,169 @@ function inferSchema(
102
115
  return { type: jsType as VarType };
103
116
  }
104
117
 
118
+ /** What is wrong with a declaration (see DeclarationError). */
119
+ export type DeclarationErrorCode =
120
+ | 'invalid-declaration'
121
+ | 'invalid-name'
122
+ | 'duplicate-declaration'
123
+ | 'unsupported-value';
124
+
105
125
  /**
106
- * Parse a StoryVariables or StoryTransients passage content into a schema map.
107
- * Each line: `$varName = expression` (or `%varName = expression` for transients)
126
+ * A declaration of a StoryVariables or StoryTransients passage: the name
127
+ * (without the sigil) and the initializer expression (without surrounding
128
+ * space) are written from `nameStart` to `nameEnd` and from `valueStart` to
129
+ * `valueEnd` (UTF-16 offsets).
108
130
  */
109
- export function parseStoryVariables(
131
+ export interface Declaration extends Spans<'name'>, Spans<'value'> {
132
+ name: string;
133
+ /**
134
+ * The shape of the initializer when it is static: a literal, or an array or
135
+ * object literal of them (an object has the members that are static).
136
+ * Absent when it is not.
137
+ */
138
+ schema?: FieldSchema;
139
+ }
140
+
141
+ /**
142
+ * An invalid line of a StoryVariables or StoryTransients passage, from
143
+ * `offset` up to `end` (UTF-16 offsets into the content).
144
+ */
145
+ export interface DeclarationError extends Record<'offset' | 'end', number> {
146
+ code: DeclarationErrorCode;
147
+ /** What is wrong, as parseStoryVariables throws it after the passage name. */
148
+ message: string;
149
+ }
150
+
151
+ const UNSUPPORTED_TYPE = 'Expected number, string, boolean, array, or object.';
152
+
153
+ /** The schema of a literal shape (see staticLiteral). */
154
+ function shapeSchema(shape: LiteralShape): FieldSchema {
155
+ if (!shape.fields) return { type: shape.type };
156
+ const fields = new Map<string, FieldSchema>();
157
+ for (const [key, member] of shape.fields)
158
+ fields.set(key, shapeSchema(member));
159
+ return { type: shape.type, fields };
160
+ }
161
+
162
+ /**
163
+ * Read the declarations of a StoryVariables (`$name = value`) or
164
+ * StoryTransients (`%name = value`) passage, without evaluating them and
165
+ * without throwing: every valid declaration, and every invalid line as an
166
+ * error. It is the grammar parseStoryVariables reads with.
167
+ *
168
+ * A declaration is a line of the form `$name = expression`; blank lines are
169
+ * skipped. A line that is not, and a name that cannot be a variable, are
170
+ * errors. So is an initializer that no variable can hold (a function,
171
+ * `undefined`), when it is a literal; whether any other initializer can only
172
+ * be known by running it. A name declared again is an error too, but both
173
+ * declarations are returned (the later wins when evaluated).
174
+ */
175
+ export function parseDeclarations(
110
176
  content: string,
111
177
  sigil: '$' | '%' = '$',
112
- ): Map<string, VariableSchema> {
113
- const schema = new Map<string, VariableSchema>();
178
+ ): { declarations: Declaration[]; errors: DeclarationError[] } {
179
+ const declarations: Declaration[] = [];
180
+ const errors: DeclarationError[] = [];
114
181
  const DECLARATION_RE = declarationRegex(sigil);
115
- const passageName = sigil === '%' ? 'StoryTransients' : 'StoryVariables';
182
+ const seen = new Set<string>();
116
183
 
184
+ let lineStart = 0;
117
185
  for (const rawLine of content.split('\n')) {
186
+ const at = lineStart + rawLine.length - rawLine.trimStart().length;
187
+ lineStart += rawLine.length + 1;
118
188
  const line = rawLine.trim();
119
189
  if (!line) continue;
120
190
 
121
191
  const match = line.match(DECLARATION_RE);
192
+ const error = (
193
+ code: DeclarationErrorCode,
194
+ start: number,
195
+ end: number,
196
+ message: string,
197
+ ) => errors.push({ code, offset: start, end, message });
122
198
  if (!match) {
123
- throw new Error(
124
- `${passageName}: Invalid declaration: "${line}". Expected: ${sigil}name = value`,
199
+ error(
200
+ 'invalid-declaration',
201
+ at,
202
+ at + line.length,
203
+ `Invalid declaration: "${line}". Expected: ${sigil}name = value`,
125
204
  );
205
+ continue;
126
206
  }
127
207
 
128
208
  const [, name, expr] = match as [string, string, string];
209
+ const nameStart = at + sigil.length;
210
+ const nameEnd = nameStart + name.length;
129
211
  const nameError = variableNameError(name, sigil + name);
130
- if (nameError) throw new Error(`${passageName}: ${nameError}`);
212
+ if (nameError) {
213
+ error('invalid-name', nameStart, nameEnd, nameError);
214
+ continue;
215
+ }
216
+ const valueEnd = at + line.length;
217
+ const declaration: Declaration = {
218
+ name,
219
+ nameStart,
220
+ nameEnd,
221
+ valueStart: valueEnd - expr.length,
222
+ valueEnd,
223
+ };
224
+ if (seen.has(name)) {
225
+ error(
226
+ 'duplicate-declaration',
227
+ nameStart,
228
+ nameEnd,
229
+ `Duplicate declaration of ${sigil}${name}`,
230
+ );
231
+ }
232
+ seen.add(name);
233
+ const literal = staticLiteral(expr);
234
+ if (literal && 'shape' in literal) {
235
+ declaration.schema = shapeSchema(literal.shape);
236
+ } else if (literal) {
237
+ error(
238
+ 'unsupported-value',
239
+ declaration.valueStart,
240
+ valueEnd,
241
+ `Unsupported type "${literal.unsupported}" for value ${expr}. ${UNSUPPORTED_TYPE}`,
242
+ );
243
+ }
244
+ declarations.push(declaration);
245
+ }
246
+ return { declarations, errors };
247
+ }
248
+
249
+ /**
250
+ * Parse a StoryVariables or StoryTransients passage content into a schema map.
251
+ * Each line: `$varName = expression` (or `%varName = expression` for transients)
252
+ * The expressions are evaluated; parseDeclarations reads the same lines
253
+ * without.
254
+ */
255
+ export function parseStoryVariables(
256
+ content: string,
257
+ sigil: '$' | '%' = '$',
258
+ ): Map<string, VariableSchema> {
259
+ const schema = new Map<string, VariableSchema>();
260
+ const passageName = sigil === '%' ? 'StoryTransients' : 'StoryVariables';
261
+ const { declarations, errors } = parseDeclarations(content, sigil);
262
+
263
+ // Lines in order: the first that is invalid, or that cannot be evaluated,
264
+ // is the error. What parseDeclarations reports about a value that is
265
+ // evaluated here is left to the evaluation (its wording is the runtime's).
266
+ const lines = [
267
+ ...errors
268
+ .filter(
269
+ (e) => e.code === 'invalid-declaration' || e.code === 'invalid-name',
270
+ )
271
+ .map((e) => ({ at: e.offset, error: e })),
272
+ ...declarations.map((d) => ({ at: d.nameStart, declaration: d })),
273
+ ].sort((a, b) => a.at - b.at);
274
+
275
+ for (const line of lines) {
276
+ if ('error' in line) {
277
+ throw new Error(`${passageName}: ${line.error.message}`);
278
+ }
279
+ const { name, valueStart, valueEnd } = line.declaration;
280
+ const expr = content.slice(valueStart, valueEnd);
131
281
  let value: unknown;
132
282
  try {
133
283
  value = new Function('return (' + expr + ')')();
@@ -149,29 +299,86 @@ export function parseStoryVariables(
149
299
  return schema;
150
300
  }
151
301
 
302
+ /** A reference to a story (`$`) or transient (`%`) variable in markup. */
303
+ export interface VariableReference {
304
+ sigil: '$' | '%';
305
+ /** The variable, without the sigil. */
306
+ name: string;
307
+ /** The fields accessed with dots (`$a.b.c`: `['b', 'c']`). */
308
+ path: string[];
309
+ /** Where `$a.b.c` is written in the markup, as `[start, end)` UTF-16 offsets. */
310
+ start: number;
311
+ end: number;
312
+ }
313
+
314
+ /** What a check of a variable reference found wrong with it. */
315
+ export type VariableDiagnosticCode =
316
+ | 'undeclared-variable'
317
+ | 'undeclared-transient'
318
+ | 'reserved-name'
319
+ | 'primitive-field';
320
+
321
+ /** A variable reference that is not valid against the declarations. */
322
+ export interface VariableDiagnostic {
323
+ passage: string;
324
+ code: VariableDiagnosticCode;
325
+ /** The variable, without the sigil. */
326
+ name: string;
327
+ /** The fields accessed with dots. */
328
+ path?: string[];
329
+ /** The reference, as offsets into the passage content. */
330
+ start: number;
331
+ end: number;
332
+ message: string;
333
+ }
334
+
152
335
  /**
153
- * Validate a single variable reference path (e.g. "player.health") against
154
- * the schema. Returns an error message or null if valid.
336
+ * What is declared: the schema of each variable, which is absent for one
337
+ * whose initializer is not static (`parseDeclarations`): it is declared, but
338
+ * its fields are not checked.
155
339
  */
156
- function validateRef(
157
- ref: string,
158
- schema: Map<string, VariableSchema>,
159
- ): string | null {
160
- const parts = ref.split('.');
161
- const rootName = parts[0]!;
162
-
163
- const nameError = variableNameError(rootName, '$' + rootName);
164
- if (nameError) return nameError;
340
+ export interface VariableDeclarations {
341
+ variables: ReadonlyMap<string, FieldSchema | undefined>;
342
+ /**
343
+ * The transients (`%`). They are not checked when absent, as the story
344
+ * start does not check them.
345
+ */
346
+ transients?: ReadonlyMap<string, FieldSchema | undefined>;
347
+ }
165
348
 
166
- const rootSchema = schema.get(rootName);
167
- if (!rootSchema) {
168
- return `Undeclared variable: $${ref}`;
349
+ /**
350
+ * Check a reference against the declarations: the error code and message, or
351
+ * null if it is valid. (Unknown fields of objects are valid: classes
352
+ * registered with Story.registerClass() can add members that are not in the
353
+ * defaults.)
354
+ */
355
+ function checkReference(
356
+ ref: VariableReference,
357
+ declared: VariableDeclarations,
358
+ ): { code: VariableDiagnosticCode; message: string } | null {
359
+ const label = (path: readonly string[]) =>
360
+ ref.sigil + [ref.name, ...path].join('.');
361
+ const nameError = variableNameError(ref.name, ref.sigil + ref.name);
362
+ if (nameError) return { code: 'reserved-name', message: nameError };
363
+
364
+ const schema = ref.sigil === '$' ? declared.variables : declared.transients;
365
+ if (!schema) return null;
366
+ if (!schema.has(ref.name)) {
367
+ return ref.sigil === '$'
368
+ ? {
369
+ code: 'undeclared-variable',
370
+ message: `Undeclared variable: ${label(ref.path)}`,
371
+ }
372
+ : {
373
+ code: 'undeclared-transient',
374
+ message: `Undeclared transient: ${label(ref.path)}`,
375
+ };
169
376
  }
170
377
 
171
- // Walk through field access path
172
- let current: FieldSchema = rootSchema;
173
- for (let i = 1; i < parts.length; i++) {
174
- const part = parts[i] as string;
378
+ // Walk through the field access path
379
+ let current = schema.get(ref.name);
380
+ for (let i = 0; current && i < ref.path.length; i++) {
381
+ const part = ref.path[i]!;
175
382
 
176
383
  // Arrays have built-in methods/properties (push, find, length, etc.)
177
384
  // so any field access on an array is allowed.
@@ -191,15 +398,12 @@ function validateRef(
191
398
  }
192
399
 
193
400
  if (current.type !== 'object' || !current.fields) {
194
- return `Cannot access field "${part}" on $${parts.slice(0, i).join('.')} (type: ${current.type})`;
195
- }
196
- const fieldSchema = current.fields.get(part);
197
- if (!fieldSchema) {
198
- // Unknown fields on objects are allowed — classes registered via
199
- // Story.registerClass() can add methods/getters not in the defaults.
200
- return null;
401
+ return {
402
+ code: 'primitive-field',
403
+ message: `Cannot access field "${part}" on ${label(ref.path.slice(0, i))} (type: ${current.type})`,
404
+ };
201
405
  }
202
- current = fieldSchema;
406
+ current = current.fields.get(part);
203
407
  }
204
408
 
205
409
  return null;
@@ -219,17 +423,49 @@ const BUILTIN_STORE_VAR_MACROS: readonly string[] = [
219
423
  'textbox',
220
424
  ];
221
425
 
222
- type RefCallback = (ref: string) => void;
426
+ /** What reading the variable references of markup depends on. */
427
+ interface ReferenceOptions {
428
+ /** The (lowercase) names of the input macros that bind a variable. */
429
+ storeVarMacros: ReadonlySet<string>;
430
+ parametersOf: ParametersOf;
431
+ /** Read half-typed markup: skip its malformed tags (default: none read). */
432
+ tolerant?: boolean;
433
+ }
434
+
435
+ /** Where index `i` of a text is in the markup being read. */
436
+ type At = (i: number) => number;
437
+
438
+ type Emit = (ref: VariableReference) => void;
223
439
 
224
440
  const NO_STORE_VAR_MACROS: ReadonlySet<string> = new Set();
225
441
 
442
+ /** A reference written at `index` of `code`, with its dot path. */
443
+ function referenceAt(
444
+ code: string,
445
+ index: number,
446
+ at: At,
447
+ ): VariableReference | undefined {
448
+ VAR_PATH_RE.lastIndex = index;
449
+ const match = VAR_PATH_RE.exec(code);
450
+ if (!match) return undefined;
451
+ const [name, ...path] = match[2]!.split('.');
452
+ return {
453
+ sigil: match[1] as '$' | '%',
454
+ name: name!,
455
+ path,
456
+ start: at(index),
457
+ end: at(index + match[0].length),
458
+ };
459
+ }
460
+
226
461
  /**
227
462
  * Scan the value of a code attribute (`onclick`, see isCodeAttribute) for
228
- * the `{$…}` references resolved in it; its other braces are code.
463
+ * the `{$…}` references resolved in it; its other braces are code. `at` is
464
+ * where the value is.
229
465
  */
230
- function scanSigilReferences(value: string, onRef: RefCallback): void {
231
- for (const part of splitSigilTemplate(value)) {
232
- if ('expr' in part) scanCode(part.expr, onRef);
466
+ function scanSigilReferences(value: string, at: At, emit: Emit): void {
467
+ for (const { expr, at: k } of sigilExpressions(value)) {
468
+ scanCode(expr, (i) => at(k + i), emit);
233
469
  }
234
470
  }
235
471
 
@@ -241,11 +477,12 @@ function scanSigilReferences(value: string, onRef: RefCallback): void {
241
477
  */
242
478
  function scanInterpolations(
243
479
  text: string,
244
- onRef: RefCallback,
245
- storeVarMacros: ReadonlySet<string> = NO_STORE_VAR_MACROS,
480
+ at: At,
481
+ emit: Emit,
482
+ options: ReferenceOptions,
246
483
  ): void {
247
484
  if (!text.includes('{')) return;
248
- collectTokenRefs(text, tokensOf(text, true), storeVarMacros, onRef);
485
+ collectTokenRefs(text, tokensOf(text, true, options), at, emit, options);
249
486
  }
250
487
 
251
488
  /**
@@ -258,34 +495,36 @@ function scanInterpolations(
258
495
  */
259
496
  function scanCode(
260
497
  code: string,
261
- onRef: RefCallback,
498
+ at: At,
499
+ emit: Emit,
262
500
  goal: JsGoal = 'expression',
263
501
  ): void {
264
502
  const parsed = parseOrError(code, goal);
265
503
  if (parsed instanceof CodeSyntaxError) {
266
- scanCodeLeniently(code, onRef, goal);
504
+ scanCodeLeniently(code, at, emit, goal);
267
505
  return;
268
506
  }
269
507
  for (const ref of parsed.refs) {
270
- if (ref.sigil !== '$') continue;
271
- VAR_PATH_RE.lastIndex = ref.start;
272
- onRef(VAR_PATH_RE.exec(code)![1]!);
508
+ if (ref.sigil !== '$' && ref.sigil !== '%') continue;
509
+ const found = referenceAt(code, ref.start, at);
510
+ if (found) emit(found);
273
511
  }
274
512
  }
275
513
 
276
514
  /** `scanCode` for code acorn can't parse: lexed leniently. */
277
515
  function scanCodeLeniently(
278
516
  code: string,
279
- onRef: RefCallback,
517
+ at: At,
518
+ emit: Emit,
280
519
  goal: JsGoal,
281
520
  ): void {
282
521
  lexJs(
283
522
  code,
284
523
  {
285
524
  variable(sigil, _name, index) {
286
- if (sigil !== '$') return;
287
- VAR_PATH_RE.lastIndex = index;
288
- onRef(VAR_PATH_RE.exec(code)![1]!);
525
+ if (sigil !== '$' && sigil !== '%') return;
526
+ const found = referenceAt(code, index, at);
527
+ if (found) emit(found);
289
528
  },
290
529
  // Strings, regex literals and comments hold no references
291
530
  literal() {},
@@ -294,29 +533,6 @@ function scanCodeLeniently(
294
533
  );
295
534
  }
296
535
 
297
- /**
298
- * Report the `$var` references a passage evaluates at runtime: `{$var}`
299
- * displays, `{$expr}` expressions, macro arguments and `{do}` bodies (as
300
- * code), quoted variable names bound by input macros, and `{$…}`
301
- * interpolations in HTML attributes. Prose is literal text and not scanned.
302
- */
303
- function collectPassageRefs(
304
- content: string,
305
- storeVarMacros: ReadonlySet<string>,
306
- onRef: RefCallback,
307
- parametersOf: ParametersOf,
308
- ): void {
309
- withParseCache(() =>
310
- collectTokenRefs(
311
- content,
312
- tokensOf(content, false),
313
- storeVarMacros,
314
- onRef,
315
- parametersOf,
316
- ),
317
- );
318
- }
319
-
320
536
  /**
321
537
  * Report the references in the arguments of a macro by what its parameters
322
538
  * say each holds (see ParameterDef.holds): code is scanned as code and
@@ -327,55 +543,111 @@ function collectPassageRefs(
327
543
  function scanArgs(
328
544
  token: Extract<Token, { type: 'macro' }>,
329
545
  params: readonly ParameterDef[] | undefined,
330
- onRef: RefCallback,
546
+ at: At,
547
+ emit: Emit,
548
+ options: ReferenceOptions,
331
549
  ): void {
332
550
  if (!token.rawArgs) return;
333
551
  if (params) {
334
- const pieces = [...argPieces(token.rawArgs, 0, params, token.name, '')];
552
+ const pieces = [
553
+ ...argPieces(token.rawArgs, token.argsStart, params, token.name, ''),
554
+ ];
335
555
  if (!pieces.some((piece) => piece.kind === 'argument-error')) {
336
556
  for (const piece of pieces) {
337
- if (piece.kind === 'code') scanCode(piece.code, onRef, piece.goal);
338
- else if (piece.kind === 'text') scanInterpolations(piece.text, onRef);
557
+ const pieceAt: At = (i) => at(pieceOffset(piece, i));
558
+ if (piece.kind === 'code') {
559
+ scanCode(piece.code, pieceAt, emit, piece.goal);
560
+ } else if (piece.kind === 'text') {
561
+ scanInterpolations(piece.text, pieceAt, emit, {
562
+ ...options,
563
+ storeVarMacros: NO_STORE_VAR_MACROS,
564
+ });
565
+ }
339
566
  }
340
567
  return;
341
568
  }
342
569
  }
343
- scanCode(token.rawArgs, onRef);
570
+ scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
344
571
  }
345
572
 
346
573
  /** Report the `$var` references in the tokens of `content`. */
347
574
  function collectTokenRefs(
348
575
  content: string,
349
576
  tokens: Token[],
350
- storeVarMacros: ReadonlySet<string>,
351
- onRef: RefCallback,
352
- parametersOf: ParametersOf = () => undefined,
577
+ at: At,
578
+ emit: Emit,
579
+ options: ReferenceOptions,
353
580
  ): void {
581
+ const { storeVarMacros, parametersOf } = options;
354
582
  for (let t = 0; t < tokens.length; t++) {
355
583
  const token = tokens[t]!;
356
584
  if (token.type === 'variable') {
357
- if (token.scope === 'variable' && token.name) onRef(token.name);
585
+ if (
586
+ (token.scope === 'variable' || token.scope === 'transient') &&
587
+ token.name
588
+ ) {
589
+ const [name, ...path] = token.name.split('.');
590
+ emit({
591
+ sigil: token.scope === 'variable' ? '$' : '%',
592
+ name: name!,
593
+ path,
594
+ start: at(token.nameStart - 1),
595
+ end: at(token.nameEnd),
596
+ });
597
+ }
358
598
  } else if (token.type === 'link') {
359
- scanInterpolations(token.display, onRef);
599
+ scanInterpolations(
600
+ token.display,
601
+ (i) => at(token.displayStart + i),
602
+ emit,
603
+ { ...options, storeVarMacros: NO_STORE_VAR_MACROS },
604
+ );
360
605
  } else if (token.type === 'expression') {
361
- scanCode(token.expression, onRef);
606
+ scanCode(token.expression, (i) => at(token.expressionStart + i), emit);
362
607
  } else if (token.type === 'html') {
363
- for (const [name, value] of Object.entries(token.attributes)) {
364
- if (isCodeAttribute(name)) scanSigilReferences(value, onRef);
365
- else scanInterpolations(value, onRef, storeVarMacros);
608
+ for (const { name, value, at: valueAt } of attributeValues(
609
+ content,
610
+ token,
611
+ )) {
612
+ const valueIn: At = (i) => at(valueAt + i);
613
+ if (isCodeAttribute(name)) scanSigilReferences(value, valueIn, emit);
614
+ else scanInterpolations(value, valueIn, emit, options);
366
615
  }
367
616
  } else if (token.type === 'macro' && !token.isClose) {
368
- scanArgs(token, parametersOf(token.name), onRef);
617
+ scanArgs(token, parametersOf(token.name), at, emit, options);
369
618
  // Selectors (`{.{$cls} button}`) are interpolated when rendered
370
- if (token.className) scanInterpolations(token.className, onRef);
371
- if (token.id) scanInterpolations(token.id, onRef);
619
+ if (
620
+ token.selectorsStart !== undefined &&
621
+ token.selectorsEnd !== undefined
622
+ ) {
623
+ const from = token.selectorsStart;
624
+ scanInterpolations(
625
+ content.slice(from, token.selectorsEnd),
626
+ (i) => at(from + i),
627
+ emit,
628
+ { ...options, storeVarMacros: NO_STORE_VAR_MACROS },
629
+ );
630
+ }
372
631
 
373
632
  if (storeVarMacros.has(token.name.toLowerCase())) {
633
+ const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
374
634
  const first = token.rawArgs.trim().split(/\s+/)[0] ?? '';
375
635
  const quoted = QUOTED_VAR_ARG_RE.exec(first);
376
- if (quoted) onRef(quoted[1]!);
636
+ if (quoted) {
637
+ const [name, ...path] = quoted[1]!.split('.');
638
+ const start = token.argsStart + lead + 1;
639
+ emit({
640
+ sigil: '$',
641
+ name: name!,
642
+ path,
643
+ start: at(start),
644
+ end: at(start + 1 + quoted[1]!.length),
645
+ });
646
+ }
377
647
  // Unquoted, the variable is an argument of no declared role
378
- else if (!/^["'`]/.test(first)) scanCode(first, onRef);
648
+ else if (!/^["'`]/.test(first)) {
649
+ scanCode(first, (i) => at(token.argsStart + lead + i), emit);
650
+ }
379
651
  }
380
652
 
381
653
  if (token.name.toLowerCase() === 'do') {
@@ -395,7 +667,7 @@ function collectTokenRefs(
395
667
  }
396
668
  if (close < tokens.length) {
397
669
  const body = content.slice(token.end, tokens[close]!.start);
398
- scanCode(body, onRef, 'statements');
670
+ scanCode(body, (i) => at(token.end + i), emit, 'statements');
399
671
  t = close;
400
672
  }
401
673
  }
@@ -403,6 +675,60 @@ function collectTokenRefs(
403
675
  }
404
676
  }
405
677
 
678
+ /**
679
+ * The `$` and `%` variable references a passage evaluates at runtime, in
680
+ * source order: `{$var}` displays, `{$expr}` expressions, macro arguments and
681
+ * `{do}` bodies (as code), quoted variable names bound by input macros, and
682
+ * `{$…}` interpolations in labels and HTML attributes. Prose is literal text
683
+ * and not scanned.
684
+ */
685
+ export function collectVariableReferences(
686
+ content: string,
687
+ options: ReferenceOptions,
688
+ ): VariableReference[] {
689
+ const found: VariableReference[] = [];
690
+ withParseCache(() =>
691
+ collectTokenRefs(
692
+ content,
693
+ tokensOf(content, false, options),
694
+ (i) => i,
695
+ (ref) => found.push(ref),
696
+ options,
697
+ ),
698
+ );
699
+ return found;
700
+ }
701
+
702
+ /**
703
+ * The invalid variable references of the passages, against what is declared,
704
+ * with their positions. The passages that hold no markup (the declarations
705
+ * themselves, SaveTitle) are skipped.
706
+ */
707
+ export function checkVariableReferences(
708
+ passages: Iterable<{ name: string; content: string }>,
709
+ declared: VariableDeclarations,
710
+ options: ReferenceOptions,
711
+ ): VariableDiagnostic[] {
712
+ const diagnostics: VariableDiagnostic[] = [];
713
+ for (const passage of passages) {
714
+ if (NOT_MARKUP.has(passage.name)) continue;
715
+ for (const ref of collectVariableReferences(passage.content, options)) {
716
+ const error = checkReference(ref, declared);
717
+ if (!error) continue;
718
+ diagnostics.push({
719
+ passage: passage.name,
720
+ code: error.code,
721
+ name: ref.name,
722
+ ...(ref.path.length > 0 ? { path: ref.path } : {}),
723
+ start: ref.start,
724
+ end: ref.end,
725
+ message: error.message,
726
+ });
727
+ }
728
+ }
729
+ return diagnostics;
730
+ }
731
+
406
732
  /**
407
733
  * Check the `$var` references of all passages against the schema, at story
408
734
  * start. Returns the error messages (empty = valid). (The syntax of their
@@ -417,29 +743,16 @@ export function validatePassages(
417
743
  storeVarMacros: Iterable<string> = BUILTIN_STORE_VAR_MACROS,
418
744
  parametersOf: ParametersOf = getMacroParameters,
419
745
  ): string[] {
420
- const errors: string[] = [];
421
- const storeVarSet = new Set(
422
- Array.from(storeVarMacros, (m) => m.toLowerCase()),
423
- );
424
-
425
- for (const [name, passage] of passages) {
426
- // Don't validate the declarations or the SaveTitle code themselves
427
- if (NOT_MARKUP.has(name)) continue;
428
-
429
- collectPassageRefs(
430
- passage.content,
431
- storeVarSet,
432
- (ref) => {
433
- const error = validateRef(ref, schema);
434
- if (error) {
435
- errors.push(`Passage "${name}": ${error}`);
436
- }
437
- },
746
+ return checkVariableReferences(
747
+ passages.values(),
748
+ { variables: schema },
749
+ {
750
+ storeVarMacros: new Set(
751
+ Array.from(storeVarMacros, (m) => m.toLowerCase()),
752
+ ),
438
753
  parametersOf,
439
- );
440
- }
441
-
442
- return errors;
754
+ },
755
+ ).map((d) => `Passage "${d.passage}": ${d.message}`);
443
756
  }
444
757
 
445
758
  /**