@rohal12/spindle 0.59.29 → 0.59.31

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.
Files changed (62) hide show
  1. package/README.md +1 -0
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +947 -351
  4. package/dist/pkg/macro-registry.js +19 -0
  5. package/dist/pkg/macro-registry.json +19 -0
  6. package/dist/pkg/story-variables.js +780 -107
  7. package/package.json +1 -1
  8. package/src/action-registry.ts +59 -5
  9. package/src/automation/load-yaml.ts +111 -20
  10. package/src/automation/runner.ts +19 -13
  11. package/src/automation/types.ts +7 -5
  12. package/src/class-registry.ts +8 -5
  13. package/src/code-check.ts +87 -20
  14. package/src/components/macros/Checkbox.tsx +5 -2
  15. package/src/components/macros/Cycle.tsx +1 -0
  16. package/src/components/macros/For.tsx +1 -7
  17. package/src/components/macros/Listbox.tsx +1 -0
  18. package/src/components/macros/MenubarButtons.tsx +6 -1
  19. package/src/components/macros/Nobr.tsx +1 -0
  20. package/src/components/macros/PassageDisplay.tsx +136 -10
  21. package/src/components/macros/Radiobutton.tsx +1 -0
  22. package/src/components/macros/Repeat.tsx +4 -2
  23. package/src/components/macros/SaveManager.tsx +30 -8
  24. package/src/components/macros/SettingsControls.tsx +19 -4
  25. package/src/components/macros/Span.tsx +1 -0
  26. package/src/components/macros/StoryTitle.tsx +1 -0
  27. package/src/components/macros/Unset.tsx +26 -13
  28. package/src/components/macros/VarDisplay.tsx +2 -3
  29. package/src/components/macros/WidgetInvocation.tsx +5 -6
  30. package/src/components/macros/input-macro.ts +1 -0
  31. package/src/components/macros/locals-scope.tsx +19 -8
  32. package/src/components/macros/macro-args.ts +11 -3
  33. package/src/expression.ts +34 -18
  34. package/src/hooks/use-merged-locals.ts +17 -2
  35. package/src/hooks/use-modal-focus.ts +247 -133
  36. package/src/index.tsx +32 -21
  37. package/src/js-bindings.ts +594 -0
  38. package/src/js-lexer.ts +76 -14
  39. package/src/macro-discovery.ts +83 -32
  40. package/src/markup/ast.ts +22 -1
  41. package/src/markup/render.tsx +44 -15
  42. package/src/parser.ts +41 -10
  43. package/src/prng.ts +24 -1
  44. package/src/saves/save-manager.ts +36 -9
  45. package/src/static-literal.ts +87 -16
  46. package/src/store.ts +83 -6
  47. package/src/story-api.ts +23 -6
  48. package/src/story-variables.ts +91 -28
  49. package/src/structural.ts +26 -15
  50. package/src/tooling.ts +24 -10
  51. package/src/transform.ts +22 -7
  52. package/src/utils/macro-names.ts +4 -0
  53. package/src/utils/namespace.ts +15 -2
  54. package/src/utils/object-path.ts +2 -2
  55. package/src/utils/stable-key.ts +17 -6
  56. package/src/utils/value-kinds.ts +38 -1
  57. package/src/widgets/ast-scanner.ts +4 -1
  58. package/src/widgets/register-widget-def.ts +2 -3
  59. package/src/widgets/widget-def.ts +36 -6
  60. package/src/widgets/widget-registry.ts +6 -2
  61. package/types/index.d.ts +12 -5
  62. package/types/tooling.d.ts +12 -2
@@ -0,0 +1,594 @@
1
+ /**
2
+ * Which declaration a variable names where it is used in JavaScript, read
3
+ * from the text without running it (see discoverMacros): the scope the use is
4
+ * in, the declarations of the name that scope can see, and the innermost one.
5
+ *
6
+ * It reads the shape of the code (brackets, and the words before and after a
7
+ * name) in text whose strings, comments and regexes are blanked, so it needs
8
+ * no syntax tree and goes on through code that is not complete. What it
9
+ * cannot place, it counts as a declaration of unknown value: a parameter, a
10
+ * pattern, an assignment. Better no answer than another declaration's.
11
+ */
12
+
13
+ type Kind = '{' | '(' | '[';
14
+
15
+ interface Group {
16
+ kind: Kind;
17
+ open: number;
18
+ /** The closing bracket, or the end of the text if there is none. */
19
+ close: number;
20
+ parent: Group | undefined;
21
+ }
22
+
23
+ /** The text a name is visible in: `[start, end)`. */
24
+ interface Scope {
25
+ start: number;
26
+ end: number;
27
+ }
28
+
29
+ interface Binding {
30
+ scope: Scope;
31
+ /** Where the name is declared. */
32
+ at: number;
33
+ /** Whether it must come before a use in the same function. */
34
+ ordered: boolean;
35
+ /** The `{` of the object literal it is declared as, if it is. */
36
+ object?: number;
37
+ /**
38
+ * Not a declaration but a write to the value of one (an assignment, a
39
+ * property of it set): `scope` is then that of the declaration it writes to.
40
+ */
41
+ write?: true;
42
+ }
43
+
44
+ const CLOSERS: Record<string, Kind> = { '}': '{', ')': '(', ']': '[' };
45
+ /** What `(…) {` is when a word like this is before the `(`: a block. */
46
+ const BLOCK_WORDS = new Set(['if', 'for', 'while', 'switch', 'with', 'catch']);
47
+ const NOT_PARAMETERS = new Set(['if', 'for', 'while', 'switch', 'with']);
48
+ const DECLARATIONS = new Set(['const', 'let', 'var']);
49
+ /** After a name: `=`, `+=`, `&&=`, `++` and the other ways to give it a value. */
50
+ const WRITE_RE =
51
+ /(?:(?:\*\*|<<|>>>?|&&|\|\||\?\?|[-+*/%&|^])=(?!=)|=(?![=>])|\+\+|--)/y;
52
+ /** A call of these on `x.list` changes `x`; as does one of these on `x` itself. */
53
+ const MUTATORS = new Set([
54
+ 'push',
55
+ 'pop',
56
+ 'shift',
57
+ 'unshift',
58
+ 'splice',
59
+ 'sort',
60
+ 'reverse',
61
+ 'fill',
62
+ 'copyWithin',
63
+ ]);
64
+ const MUTATING_CALL_RE =
65
+ /(?:Object|Reflect)\s*\.\s*(?:assign|defineProperty|defineProperties|setPrototypeOf|set|deleteProperty)\s*$/;
66
+ /** Before a name in a pattern or parameter list, by the group around it. */
67
+ const BEFORE_BINDING: Record<Kind, string> = {
68
+ '{': '{,:',
69
+ '[': '[,',
70
+ '(': '(,',
71
+ };
72
+
73
+ const isWordChar = (c: string | undefined) => !!c && /[\w$]/.test(c);
74
+
75
+ /** Resolve the declaration of variables in `code` (see blankedCode in macro-discovery). */
76
+ export class Bindings {
77
+ private readonly groups: Group[] = [];
78
+ private readonly byOpen = new Map<number, Group>();
79
+ private readonly byClose = new Map<number, Group>();
80
+ private readonly functions = new Map<Group, boolean>();
81
+ private readonly top: Scope = { start: -1, end: Infinity };
82
+
83
+ constructor(private readonly code: string) {
84
+ this.readGroups();
85
+ }
86
+
87
+ /**
88
+ * The `{` of the object literal that `name`, used at `at`, is declared as
89
+ * (`const`, `let` or `var`), when that is the declaration it names: the
90
+ * innermost one in the scope of the use, that comes before it unless the
91
+ * use is in a function of its own. `undefined` if it names another value,
92
+ * more than one declaration is the innermost, or the value is written to
93
+ * (given another, or one of its `properties` set) where the use can follow.
94
+ */
95
+ objectOf(
96
+ name: string,
97
+ at: number,
98
+ properties: ReadonlySet<string>,
99
+ ): number | undefined {
100
+ const { code } = this;
101
+ const escaped = name.replace(/\$/g, '\\$');
102
+ const bindings: Binding[] = [];
103
+ for (const m of code.matchAll(
104
+ new RegExp(`(?<![\\w$])${escaped}(?![\\w$])`, 'g'),
105
+ )) {
106
+ const binding = this.bindingAt(m.index, name.length, properties);
107
+ if (binding) bindings.push(binding);
108
+ }
109
+ // A write is to the declaration it sees: in the scope of that one
110
+ const declarations = bindings.filter((b) => !b.write);
111
+ for (const b of bindings) {
112
+ if (b.write) {
113
+ b.scope =
114
+ this.innermostVisible(declarations, b.at)[0]?.scope ?? this.top;
115
+ }
116
+ }
117
+ const found = this.innermostVisible(bindings, at);
118
+ return found.length === 1 ? found[0]!.object : undefined;
119
+ }
120
+
121
+ /**
122
+ * Of the `bindings` the use at `at` can see, those in the innermost scope:
123
+ * the scope is the use's, and a binding comes before it, unless the use is
124
+ * in a function of its own.
125
+ */
126
+ private innermostVisible(bindings: Binding[], at: number): Binding[] {
127
+ const useFunction = this.functionStart(at);
128
+ const visible = bindings.filter(
129
+ (b) =>
130
+ b.scope.start <= at &&
131
+ at < b.scope.end &&
132
+ (!b.ordered || b.at < at || this.functionStart(b.at) !== useFunction),
133
+ );
134
+ const innermost = Math.max(...visible.map((b) => b.scope.start));
135
+ return visible.filter((b) => b.scope.start === innermost);
136
+ }
137
+
138
+ // -- the brackets ---------------------------------------------------------
139
+
140
+ private readGroups(): void {
141
+ const { code, groups } = this;
142
+ const stack: Group[] = [];
143
+ for (let i = 0; i < code.length; i++) {
144
+ const c = code.charAt(i);
145
+ if (c === '{' || c === '(' || c === '[') {
146
+ const group: Group = {
147
+ kind: c,
148
+ open: i,
149
+ close: code.length,
150
+ parent: stack[stack.length - 1],
151
+ };
152
+ groups.push(group);
153
+ stack.push(group);
154
+ this.byOpen.set(i, group);
155
+ } else if (CLOSERS[c]) {
156
+ // Tolerate a closer with no opener: the innermost of its kind closes
157
+ let k = stack.length - 1;
158
+ while (k >= 0 && stack[k]!.kind !== CLOSERS[c]) k--;
159
+ if (k >= 0) {
160
+ stack[k]!.close = i;
161
+ this.byClose.set(i, stack[k]!);
162
+ stack.length = k;
163
+ }
164
+ }
165
+ }
166
+ }
167
+
168
+ /** The innermost group that has `index` inside it, of this kind if given. */
169
+ private innermost(index: number, kind?: Kind): Group | undefined {
170
+ const { groups } = this;
171
+ for (let k = groups.length - 1; k >= 0; k--) {
172
+ const g = groups[k]!;
173
+ if (g.open < index && index < g.close && (!kind || g.kind === kind)) {
174
+ return g;
175
+ }
176
+ }
177
+ return undefined;
178
+ }
179
+
180
+ /**
181
+ * The word before a `(` group (`if`, `for`, `catch`, a function's name…);
182
+ * `for await` is `for`.
183
+ */
184
+ private ownerWord(paren: Group): string {
185
+ const word = this.wordBefore(this.backFrom(paren.open) + 1);
186
+ if (word.text !== 'await') return word.text;
187
+ const before = this.wordBefore(this.backFrom(word.start) + 1).text;
188
+ return before === 'for' ? before : word.text;
189
+ }
190
+
191
+ /**
192
+ * Whether the `{` group is the body of a function (or method), or of a
193
+ * class static block, which has the scope of a `var` of its own.
194
+ */
195
+ private isFunctionBody(group: Group): boolean {
196
+ if (group.kind !== '{') return false;
197
+ let known = this.functions.get(group);
198
+ if (known === undefined) {
199
+ const before = this.backFrom(group.open);
200
+ const { code } = this;
201
+ if (code.charAt(before) === ')') {
202
+ const params = this.byClose.get(before);
203
+ known = !!params && !BLOCK_WORDS.has(this.ownerWord(params));
204
+ } else {
205
+ known =
206
+ code.slice(before - 1, before + 1) === '=>' ||
207
+ this.wordBefore(before + 1).text === 'static';
208
+ }
209
+ this.functions.set(group, known);
210
+ }
211
+ return known;
212
+ }
213
+
214
+ /** The start of the function that has `index` in its body, or -1. */
215
+ private functionStart(index: number): number {
216
+ for (let g = this.innermost(index, '{'); g; g = g.parent) {
217
+ if (g.kind === '{' && this.isFunctionBody(g)) return g.open;
218
+ }
219
+ return -1;
220
+ }
221
+
222
+ // -- the scopes -----------------------------------------------------------
223
+
224
+ private scopeOf(group: Group | undefined): Scope {
225
+ return group ? { start: group.open, end: group.close } : this.top;
226
+ }
227
+
228
+ /** The block `index` is in: what `let` and `const` declare for. */
229
+ private blockAt(index: number): Scope {
230
+ return this.scopeOf(this.innermost(index, '{'));
231
+ }
232
+
233
+ /** The function (or the whole text) `index` is in: what `var` declares for. */
234
+ private functionAt(index: number): Scope {
235
+ const start = this.functionStart(index);
236
+ return start < 0 ? this.top : this.scopeOf(this.byOpen.get(start));
237
+ }
238
+
239
+ /**
240
+ * What the declaration keyword `word` (`var`, `let`, `const`) declares for:
241
+ * the function for `var`, the block for the others, or the `for` statement,
242
+ * header and body, when the declaration is in its header.
243
+ */
244
+ private declaredIn(word: { text: string; start: number }): Scope {
245
+ if (word.text === 'var') return this.functionAt(word.start);
246
+ const group = this.innermost(word.start);
247
+ if (group?.kind === '(' && this.ownerWord(group) === 'for') {
248
+ return { start: group.open, end: this.statementEnd(group.close + 1) };
249
+ }
250
+ return this.blockAt(word.start);
251
+ }
252
+
253
+ /**
254
+ * Where the statement that starts at `from` ends: a block, the body of an
255
+ * `if`, `for`, `while` or `with` (and the `else` of an `if`), or else up to
256
+ * a `;`, the closer of the group it is in, or a line break that is followed
257
+ * by a statement of its own.
258
+ */
259
+ private statementEnd(from: number): number {
260
+ const { code } = this;
261
+ const start = this.forward(from);
262
+ const block = this.byOpen.get(start);
263
+ if (block?.kind === '{') return Math.min(block.close + 1, code.length);
264
+ const word = this.wordAt(start);
265
+ if (/^(?:if|for|while|with)$/.test(word)) {
266
+ let paren = this.forward(start + word.length);
267
+ if (word === 'for' && this.wordAt(paren) === 'await') {
268
+ paren = this.forward(paren + 5);
269
+ }
270
+ const header = this.byOpen.get(paren);
271
+ if (header) {
272
+ const end = this.statementEnd(header.close + 1);
273
+ const next = this.forward(end);
274
+ return word === 'if' && this.wordAt(next) === 'else'
275
+ ? this.statementEnd(next + 4)
276
+ : end;
277
+ }
278
+ }
279
+ for (let end = start; end < code.length; end++) {
280
+ const c = code.charAt(end);
281
+ if (c === ';') return end + 1;
282
+ if (CLOSERS[c]) return end;
283
+ const group = this.byOpen.get(end);
284
+ if (group) end = group.close;
285
+ else if (c === '\n' && this.startsStatement(end)) return end;
286
+ }
287
+ return code.length;
288
+ }
289
+
290
+ /** Whether the line break at `index` ends a statement, and one follows. */
291
+ private startsStatement(index: number): boolean {
292
+ const next = this.forward(index);
293
+ return (
294
+ /[\w$)\]}]/.test(this.code.charAt(this.backFrom(index))) &&
295
+ isWordChar(this.code.charAt(next)) &&
296
+ !/^(?:in|of|instanceof|else)$/.test(this.wordAt(next))
297
+ );
298
+ }
299
+
300
+ /** What a parameter list, whose `)` is `close`, is the scope of: the body. */
301
+ private bodyAfter(close: number): Scope | undefined {
302
+ const next = this.forward(close + 1);
303
+ if (this.code.charAt(next) === '{')
304
+ return this.scopeOf(this.byOpen.get(next));
305
+ return this.code.startsWith('=>', next)
306
+ ? this.arrowBody(next + 2)
307
+ : undefined;
308
+ }
309
+
310
+ /** The body of an arrow function, whose `=>` ends before `from`. */
311
+ private arrowBody(from: number): Scope {
312
+ const { code } = this;
313
+ const start = this.forward(from);
314
+ if (code.charAt(start) === '{') return this.scopeOf(this.byOpen.get(start));
315
+ let end = start;
316
+ while (end < code.length && !',;)]}'.includes(code.charAt(end))) {
317
+ end = this.byOpen.get(end)?.close ?? end;
318
+ end++;
319
+ }
320
+ return { start, end };
321
+ }
322
+
323
+ // -- the text -------------------------------------------------------------
324
+
325
+ /** The index of the last character that is no space before `index`, or -1. */
326
+ private backFrom(index: number): number {
327
+ let i = index - 1;
328
+ while (i >= 0 && /\s/.test(this.code.charAt(i))) i--;
329
+ return i;
330
+ }
331
+
332
+ /** The index of the first character that is no space from `index` on. */
333
+ private forward(index: number): number {
334
+ let i = index;
335
+ while (i < this.code.length && /\s/.test(this.code.charAt(i))) i++;
336
+ return i;
337
+ }
338
+
339
+ /** The word that starts at `index` (empty if there is none). */
340
+ private wordAt(index: number): string {
341
+ return this.code.slice(index, this.nameEnd(index));
342
+ }
343
+
344
+ /** The word that ends before `end`, and where it starts. */
345
+ private wordBefore(end: number): { text: string; start: number } {
346
+ let start = end;
347
+ while (start > 0 && isWordChar(this.code.charAt(start - 1))) start--;
348
+ return { text: this.code.slice(start, end), start };
349
+ }
350
+
351
+ // -- the declarations -----------------------------------------------------
352
+
353
+ /**
354
+ * What the name of `length` characters at `at` declares, or writes to, if it
355
+ * does. A write to a `properties` of it counts, one to another does not.
356
+ */
357
+ private bindingAt(
358
+ at: number,
359
+ length: number,
360
+ properties: ReadonlySet<string>,
361
+ ): Binding | undefined {
362
+ const { code } = this;
363
+ let before = this.backFrom(at);
364
+ const spread = code.slice(before - 2, before + 1) === '...';
365
+ if (code.charAt(before) === '.' && !spread) return undefined; // a property
366
+ if (spread) before = this.backFrom(before - 2);
367
+ const after = this.forward(at + length);
368
+ return (
369
+ this.declarationAt(at, before, spread) ??
370
+ this.patternAt(at, before, after) ??
371
+ this.arrowParameterAt(at, after) ??
372
+ (spread ? undefined : this.writeAt(at, before, after, properties))
373
+ );
374
+ }
375
+
376
+ /** `const x`, `let x`, `var x`, a later `y` of `let x, y`, `function x`, `class x`. */
377
+ private declarationAt(
378
+ at: number,
379
+ before: number,
380
+ spread: boolean,
381
+ ): Binding | undefined {
382
+ if (spread) return undefined;
383
+ const word =
384
+ this.code.charAt(before) === ','
385
+ ? this.listKeyword(before)
386
+ : this.wordBefore(before + 1);
387
+ if (!word || this.code.charAt(word.start - 1) === '.') return undefined;
388
+ if (DECLARATIONS.has(word.text)) {
389
+ const scope = this.declaredIn(word);
390
+ const init = /\s*=\s*(?=\{)/y;
391
+ init.lastIndex = this.nameEnd(at);
392
+ const object = init.test(this.code) ? init.lastIndex : undefined;
393
+ return { scope, at, ordered: true, object };
394
+ }
395
+ if (word.text === 'function' || word.text === 'class') {
396
+ return {
397
+ scope: this.blockAt(word.start),
398
+ at,
399
+ ordered: word.text === 'class',
400
+ };
401
+ }
402
+ return undefined;
403
+ }
404
+
405
+ /**
406
+ * The `const`, `let` or `var` of the declaration list that the `,` at
407
+ * `comma` is in (`let a = 1, b`, also in a `for` header): the nearest one
408
+ * before it in the same brackets, that no `;` is between.
409
+ */
410
+ private listKeyword(
411
+ comma: number,
412
+ ): { text: string; start: number } | undefined {
413
+ const { code } = this;
414
+ const floor = this.innermost(comma)?.open ?? -1;
415
+ for (let i = comma - 1; i > floor; i--) {
416
+ const c = code.charAt(i);
417
+ if (c === ';') return undefined;
418
+ const group = CLOSERS[c] ? this.byClose.get(i) : undefined;
419
+ if (group) i = group.open;
420
+ else if (isWordChar(c)) {
421
+ const word = this.wordBefore(i + 1);
422
+ if (
423
+ DECLARATIONS.has(word.text) &&
424
+ code.charAt(word.start - 1) !== '.'
425
+ ) {
426
+ return word;
427
+ }
428
+ i = word.start;
429
+ }
430
+ }
431
+ return undefined;
432
+ }
433
+
434
+ private nameEnd(at: number): number {
435
+ let end = at;
436
+ while (isWordChar(this.code.charAt(end))) end++;
437
+ return end;
438
+ }
439
+
440
+ /**
441
+ * A name in a pattern (`const { x } = …`) or a parameter list; or one a
442
+ * pattern assigns to (`({ x } = …)`).
443
+ */
444
+ private patternAt(
445
+ at: number,
446
+ before: number,
447
+ after: number,
448
+ ): Binding | undefined {
449
+ const { code } = this;
450
+ const inner = this.innermost(at);
451
+ if (!inner || !BEFORE_BINDING[inner.kind].includes(code.charAt(before))) {
452
+ return undefined;
453
+ }
454
+ if (inner.kind === '{' && code.charAt(after) === ':') return undefined; // a key
455
+ // The outermost pattern, to see whether it is assigned to
456
+ let pattern: Group | undefined;
457
+ for (let group: Group | undefined = inner; group; group = group.parent) {
458
+ if (group.kind === '(') {
459
+ const scope = NOT_PARAMETERS.has(this.ownerWord(group))
460
+ ? undefined
461
+ : this.bodyAfter(group.close);
462
+ return scope
463
+ ? { scope, at, ordered: false }
464
+ : this.patternWriteAt(at, pattern);
465
+ }
466
+ pattern = group;
467
+ const open = this.backFrom(group.open);
468
+ const word =
469
+ code.charAt(open) === ','
470
+ ? this.listKeyword(open)
471
+ : this.wordBefore(open + 1);
472
+ if (word && DECLARATIONS.has(word.text)) {
473
+ return { scope: this.declaredIn(word), at, ordered: true };
474
+ }
475
+ // Inside another pattern or list
476
+ if (!'({[,:'.includes(code.charAt(open))) break;
477
+ }
478
+ return this.patternWriteAt(at, pattern);
479
+ }
480
+
481
+ /** `[x] = …`, `({ x } = …)`, `for ({ x } of …)`: a name that is assigned to. */
482
+ private patternWriteAt(
483
+ at: number,
484
+ pattern: Group | undefined,
485
+ ): Binding | undefined {
486
+ if (!pattern) return undefined;
487
+ const { code } = this;
488
+ const open = this.backFrom(pattern.open);
489
+ if (/[\w$)\]]/.test(code.charAt(open))) return undefined; // `a[x] = …`
490
+ const next = this.forward(pattern.close + 1);
491
+ const inForHead =
492
+ pattern.parent?.kind === '(' &&
493
+ this.ownerWord(pattern.parent) === 'for' &&
494
+ /^(?:of|in)(?![\w$])/.test(code.slice(next));
495
+ return inForHead || this.isWriteOperator(next)
496
+ ? { scope: this.top, at, ordered: true, write: true }
497
+ : undefined;
498
+ }
499
+
500
+ /** `x => …`. */
501
+ private arrowParameterAt(at: number, after: number): Binding | undefined {
502
+ return this.code.startsWith('=>', after)
503
+ ? { scope: this.arrowBody(after + 2), at, ordered: false }
504
+ : undefined;
505
+ }
506
+
507
+ /** Whether an assignment, `++` or `--` operator is at `index`. */
508
+ private isWriteOperator(index: number): boolean {
509
+ WRITE_RE.lastIndex = index;
510
+ return WRITE_RE.test(this.code);
511
+ }
512
+
513
+ /**
514
+ * `x = …`, `x += …`, `x++`, `for (x of …)`, and the writes to what it
515
+ * holds that change the config it is (`x.name = …`, `delete x.name`,
516
+ * `x.parameters.push(…)`, `Object.assign(x, …)`): a value not known.
517
+ */
518
+ private writeAt(
519
+ at: number,
520
+ before: number,
521
+ after: number,
522
+ properties: ReadonlySet<string>,
523
+ ): Binding | undefined {
524
+ const { code } = this;
525
+ if (this.isClassBody(this.innermost(at))) return undefined; // a field
526
+ const { keys, end } = this.memberChain(after);
527
+ const prefix = ['++', '--'].includes(code.slice(before - 1, before + 1));
528
+ const written =
529
+ prefix ||
530
+ this.isWriteOperator(end) ||
531
+ (keys.length > 0 &&
532
+ (this.wordBefore(before + 1).text === 'delete' ||
533
+ (keys.length > 1 &&
534
+ code.charAt(end) === '(' &&
535
+ MUTATORS.has(keys[keys.length - 1]!)))) ||
536
+ (keys.length === 0 && this.isForTarget(before, end)) ||
537
+ (keys.length === 0 && this.isMutatedArgument(before, end));
538
+ // A property that is not a part of the macro's config does not matter
539
+ const first = keys[0];
540
+ if (!written || (first && !properties.has(first))) return undefined;
541
+ return { scope: this.top, at, ordered: true, write: true };
542
+ }
543
+
544
+ /** Whether the group is the body of a class: its members are its own. */
545
+ private isClassBody(group: Group | undefined): boolean {
546
+ if (group?.kind !== '{') return false;
547
+ let start = group.open;
548
+ while (start > 0 && !'{};'.includes(this.code.charAt(start - 1))) start--;
549
+ return /(?<![\w$.])class(?![\w$])/.test(this.code.slice(start, group.open));
550
+ }
551
+
552
+ /**
553
+ * The properties read from a name at `from` (`.a.b[c]`, a key is null if
554
+ * computed), and where the chain ends.
555
+ */
556
+ private memberChain(from: number): { keys: (string | null)[]; end: number } {
557
+ const { code } = this;
558
+ const keys: (string | null)[] = [];
559
+ let end = from;
560
+ for (;;) {
561
+ let i = end;
562
+ if (code.startsWith('?.', i)) i += 2;
563
+ else if (code.charAt(i) === '.' && code.charAt(i + 1) !== '.') i++;
564
+ else if (code.charAt(i) !== '[') break;
565
+ i = this.forward(i);
566
+ const bracket = code.charAt(i) === '[' ? this.byOpen.get(i) : undefined;
567
+ const key = bracket ? '' : this.wordAt(i);
568
+ if (!bracket && !key) break;
569
+ keys.push(bracket ? null : key);
570
+ end = this.forward(bracket ? bracket.close + 1 : i + key.length);
571
+ }
572
+ return { keys, end };
573
+ }
574
+
575
+ /** `for (x of …)`: the name is assigned each item. */
576
+ private isForTarget(before: number, end: number): boolean {
577
+ const group = this.byOpen.get(before);
578
+ return (
579
+ group?.kind === '(' &&
580
+ this.ownerWord(group) === 'for' &&
581
+ /^(?:of|in)(?![\w$])/.test(this.code.slice(end))
582
+ );
583
+ }
584
+
585
+ /** `Object.assign(x, …)` and the like: the name is the first argument. */
586
+ private isMutatedArgument(before: number, end: number): boolean {
587
+ const group = this.byOpen.get(before);
588
+ return (
589
+ group?.kind === '(' &&
590
+ ',)'.includes(this.code.charAt(end)) &&
591
+ MUTATING_CALL_RE.test(this.code.slice(0, group.open))
592
+ );
593
+ }
594
+ }