@barefootjs/jsx 0.39.8 → 0.39.9

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 (92) hide show
  1. package/dist/adapters/callback-method.d.ts +19 -7
  2. package/dist/adapters/callback-method.d.ts.map +1 -1
  3. package/dist/adapters/dsl-template-adapter.d.ts +2 -0
  4. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  5. package/dist/adapters/loop-plan.d.ts +133 -9
  6. package/dist/adapters/loop-plan.d.ts.map +1 -1
  7. package/dist/adapters/parsed-expr-emitter.d.ts +20 -3
  8. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  9. package/dist/analyzer.d.ts.map +1 -1
  10. package/dist/assignment-target.d.ts +26 -0
  11. package/dist/assignment-target.d.ts.map +1 -0
  12. package/dist/errors.d.ts +1 -0
  13. package/dist/errors.d.ts.map +1 -1
  14. package/dist/index.d.ts +4 -4
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +1913 -1457
  17. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  20. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  22. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  24. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  26. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/phases/props-extraction.d.ts +5 -3
  30. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  32. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  35. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  37. package/dist/jsx-to-ir.d.ts.map +1 -1
  38. package/dist/prop-rewrite.d.ts +17 -8
  39. package/dist/prop-rewrite.d.ts.map +1 -1
  40. package/dist/props-binding.d.ts +57 -0
  41. package/dist/props-binding.d.ts.map +1 -1
  42. package/dist/scope/binding-scope.d.ts +30 -2
  43. package/dist/scope/binding-scope.d.ts.map +1 -1
  44. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  45. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  46. package/dist/types.d.ts +25 -1
  47. package/dist/types.d.ts.map +1 -1
  48. package/package.json +2 -2
  49. package/src/__tests__/arithmetic-lowering.test.ts +5 -1
  50. package/src/__tests__/binding-scope.test.ts +29 -0
  51. package/src/__tests__/create-query.test.ts +1 -1
  52. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  53. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  54. package/src/__tests__/loop-plan.test.ts +131 -1
  55. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  56. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  57. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  58. package/src/__tests__/props-alias-const.test.ts +60 -1
  59. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  60. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  61. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  62. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  63. package/src/adapters/callback-method.ts +25 -10
  64. package/src/adapters/dsl-template-adapter.ts +11 -0
  65. package/src/adapters/loop-plan.ts +201 -13
  66. package/src/adapters/parsed-expr-emitter.ts +37 -4
  67. package/src/analyzer.ts +283 -2
  68. package/src/assignment-target.ts +79 -0
  69. package/src/errors.ts +11 -0
  70. package/src/index.ts +13 -2
  71. package/src/ir-to-client-js/compute-inlinability.ts +6 -3
  72. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  73. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  74. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  75. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  76. package/src/ir-to-client-js/csr-substitute.ts +70 -22
  77. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  78. package/src/ir-to-client-js/emit-registration.ts +6 -1
  79. package/src/ir-to-client-js/html-template.ts +18 -7
  80. package/src/ir-to-client-js/phases/props-extraction.ts +26 -5
  81. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  82. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  83. package/src/ir-to-client-js/rewrite-destructured-props.ts +2 -2
  84. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  85. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  86. package/src/ir-to-client-js/utils.ts +40 -96
  87. package/src/jsx-to-ir.ts +31 -12
  88. package/src/prop-rewrite.ts +31 -72
  89. package/src/props-binding.ts +73 -1
  90. package/src/scope/binding-scope.ts +34 -3
  91. package/src/scope/lexical-scope-walk.ts +167 -0
  92. package/src/types.ts +25 -1
@@ -4,19 +4,28 @@
4
4
  * Every DSL adapter decides the same things about a `.map()` loop before it
5
5
  * spells a line of template: whether its destructure pattern lowers (BF104),
6
6
  * whether the source is a static literal, whether it names a computed const
7
- * no template binds (BF101), how its `.sort` comparator lowers, and which
8
- * filter captures need an alias. {@link planLoop} makes those decisions once,
9
- * against the scope outside the loop. The adapter keeps the spelling: the
10
- * loop header, the row bindings, the diagnostics' wording, and the order it
11
- * emits them in.
7
+ * no template binds (BF101), how its `.sort` comparator lowers, which filter
8
+ * captures need an alias, how the filter predicate reads on the row, and
9
+ * which locals the row binds for its index and its destructure bindings.
10
+ * {@link planLoop} makes those decisions once, against the scope outside the
11
+ * loop. The adapter keeps the spelling:
12
+ * the loop header, the row bindings, the diagnostics' wording, and the order
13
+ * it emits them in.
12
14
  */
13
15
 
14
- import { parseExpression } from '../expression-parser.ts'
16
+ import { type ParsedExpr, parseExpression, renameFreeIdentifiers, type SortComparator } from '../expression-parser.ts'
15
17
  import { isLowerableLoopDestructure } from '../loop-destructure.ts'
16
18
  import type { BindingScope } from '../scope/binding-scope.ts'
17
19
  import { resolveStaticLoopSource } from '../static-literal.ts'
18
- import type { ConstantInfo, IRLoop } from '../types.ts'
19
- import { type CallbackLoweringOptions, type CallbackPlan, lowerCallbackMethod } from './callback-method.ts'
20
+ import type { ConstantInfo, IRLoop, LoopBindingPathSegment } from '../types.ts'
21
+ import {
22
+ type CallbackEvalSpelling,
23
+ type CallbackLoweringOptions,
24
+ emitCallbackEval,
25
+ lowerSortComparator,
26
+ missingFilterPredicateRefusal,
27
+ type SortPlan,
28
+ } from './callback-method.ts'
20
29
  import { filterCaptureCollisions } from './filter-capture-collisions.ts'
21
30
 
22
31
  export interface LoopPlanContext<Spelled> {
@@ -47,10 +56,169 @@ export interface LoopPlan<Spelled> {
47
56
  * name is the row's value, not the const (#3473).
48
57
  */
49
58
  unresolvableConst: ConstantInfo | null
50
- /** The `.sort` / `.toSorted` comparator's lowering, or `null` without one. */
51
- sort: CallbackPlan | null
59
+ /**
60
+ * The `.sort` / `.toSorted` comparator's lowering, or `null` without one:
61
+ * the evaluator, the structured `{keys: …}` descriptor, or BF101, the same
62
+ * chain as `.sort(cmp)` at an expression position.
63
+ */
64
+ sort: SortPlan | null
52
65
  /** The filter predicate's captures that a row binding would shadow, each with its alias. */
53
66
  captureAliases: Array<{ name: string; alias: string }>
67
+ /** The `.filter()` predicate of a `.filter().map()` loop, or `null` without one. */
68
+ filter: LoopFilterPlan | null
69
+ /**
70
+ * The for-target of an array iteration: the param itself, or the synthetic
71
+ * `__bf_item` when the param is not the item (a `.keys()` iteration, whose
72
+ * param is the index, or a lowered destructure, whose bindings read off it).
73
+ */
74
+ itemVar: string
75
+ /**
76
+ * The name a local binds to the row's 0-based index in an array iteration:
77
+ * a `.keys()` iteration's param, else the explicit index param. `null` for
78
+ * an object iteration, whose key the header binds.
79
+ */
80
+ indexLocal: string | null
81
+ /** One local per binding of a lowered destructure, in pattern order. */
82
+ destructureLocals: Array<{ name: string; value: DestructureValue }>
83
+ }
84
+
85
+ /**
86
+ * What a lowered destructure binding reads off the row item: the value at
87
+ * `segments`, or for a rest binding the residual of the value there (the
88
+ * array from `from` on, or the object without the `exclude` keys).
89
+ */
90
+ export type DestructureValue =
91
+ | { kind: 'path'; segments: readonly LoopBindingPathSegment[] }
92
+ | { kind: 'slice'; segments: readonly LoopBindingPathSegment[]; from: number }
93
+ | { kind: 'omit'; segments: readonly LoopBindingPathSegment[]; exclude: readonly string[] }
94
+
95
+ /** An adapter's spelling of a {@link DestructureValue}. */
96
+ export interface DestructureSpelling {
97
+ /** The value at `segments` off `item`. */
98
+ accessor(item: string, segments: readonly LoopBindingPathSegment[]): string
99
+ /** The array `parent` from index `from` on. */
100
+ slice(parent: string, from: number): string
101
+ /** The object `parent` without the `keys`. */
102
+ omit(parent: string, keys: readonly string[]): string
103
+ }
104
+
105
+ /** Spell each destructure local's value off the row item `item`. */
106
+ export function spellDestructureLocals(
107
+ plan: Pick<LoopPlan<unknown>, 'destructureLocals'>,
108
+ item: string,
109
+ spelling: DestructureSpelling,
110
+ ): Array<{ name: string; value: string }> {
111
+ return plan.destructureLocals.map(({ name, value }) => {
112
+ const parent = spelling.accessor(item, value.segments)
113
+ if (value.kind === 'slice') return { name, value: spelling.slice(parent, value.from) }
114
+ if (value.kind === 'omit') return { name, value: spelling.omit(parent, value.exclude) }
115
+ return { name, value: parent }
116
+ })
117
+ }
118
+
119
+ /** An adapter's spelling of a {@link SortPlan} over the loop source. */
120
+ export interface LoopSortSpelling {
121
+ /** A captured name's SSR value, for the evaluator's env. */
122
+ emit(e: ParsedExpr): string
123
+ /** The evaluator call. */
124
+ eval: CallbackEvalSpelling
125
+ /** The structured `bf.sort` call over `recv` with the `{keys: …}` descriptor. */
126
+ structured(recv: string, comparator: SortComparator): string
127
+ /** Record the refusal of a comparator neither form models (BF101). */
128
+ refuse(message: string, suggestion: string): void
129
+ }
130
+
131
+ /**
132
+ * The loop source `recv` sorted by the loop's comparator, or `recv` itself
133
+ * without one. A refused comparator is recorded and leaves `recv` unsorted,
134
+ * so the template stays valid.
135
+ */
136
+ export function spellSortedSource(sort: SortPlan | null, recv: string, spelling: LoopSortSpelling): string {
137
+ if (!sort) return recv
138
+ if (sort.kind === 'eval') return emitCallbackEval(sort, recv, spelling.emit, spelling.eval)
139
+ if (sort.kind === 'structured-sort') return spelling.structured(recv, sort.comparator)
140
+ spelling.refuse(sort.message, sort.suggestion)
141
+ return recv
142
+ }
143
+
144
+ /**
145
+ * The `.filter()` predicate a `.filter().map()` loop tests on each row: the
146
+ * predicate with the names it reads renamed for the row, or the refusal of a
147
+ * filter whose predicate never reached the IR (BF101, #3534).
148
+ */
149
+ export type LoopFilterPlan = LoopFilterPredicate | { kind: 'refuse'; message: string; suggestion: string }
150
+
151
+ export interface LoopFilterPredicate {
152
+ kind: 'predicate'
153
+ /** The filter callback's own param. */
154
+ param: string
155
+ /** The predicate as written. */
156
+ predicate: ParsedExpr
157
+ /**
158
+ * The predicate with each capture a row binding would shadow renamed to
159
+ * its alias (`captureAliases`), for an emitter that maps the filter param
160
+ * itself (#3402).
161
+ */
162
+ captured: ParsedExpr
163
+ /**
164
+ * `captured` with the filter param renamed to the loop param too: the
165
+ * predicate read off the row item. The tree is renamed, not the rendered
166
+ * text, so a string literal or a property key of the same spelling stays
167
+ * (#3404).
168
+ */
169
+ onRow: ParsedExpr
170
+ /** Each capture alias and the enclosing name it keeps, for the scope the predicate renders under. */
171
+ aliases: ReadonlyMap<string, string>
172
+ }
173
+
174
+ /** An adapter's spelling of a {@link LoopFilterPlan}. */
175
+ export interface LoopFilterSpelling {
176
+ /** The row's condition for a predicate. */
177
+ condition(filter: LoopFilterPredicate): string
178
+ /** Record the refusal of a filter without a predicate. */
179
+ refuse(message: string, suggestion: string): void
180
+ /** The condition that stands in for a refused predicate, so the template stays valid. */
181
+ refused: string
182
+ /** The guard's opening line. */
183
+ open(condition: string): string
184
+ /** The guard's closing line. */
185
+ close: string
186
+ }
187
+
188
+ /**
189
+ * The lines of a loop row: `row` itself, or with a filter `row` inside the
190
+ * guard on the filter's condition.
191
+ */
192
+ export function spellFilteredRow(filter: LoopFilterPlan | null, row: readonly string[], spelling: LoopFilterSpelling): string[] {
193
+ if (!filter) return [...row]
194
+ return [spelling.open(filterCondition(filter, spelling)), ...row, spelling.close]
195
+ }
196
+
197
+ function filterCondition(filter: LoopFilterPlan, spelling: LoopFilterSpelling): string {
198
+ if (filter.kind === 'predicate') return spelling.condition(filter)
199
+ spelling.refuse(filter.message, filter.suggestion)
200
+ return spelling.refused
201
+ }
202
+
203
+ function filterPlan(
204
+ loop: IRLoop,
205
+ captureAliases: LoopPlan<unknown>['captureAliases'],
206
+ adapterName: string,
207
+ ): LoopFilterPlan | null {
208
+ const filter = loop.filterPredicate
209
+ if (!filter) return null
210
+ if (!filter.predicate) return { kind: 'refuse', ...missingFilterPredicateRefusal(filter.raw, adapterName) }
211
+ const captureRenames = new Map(captureAliases.map(({ name, alias }) => [name, alias]))
212
+ const rowRenames = new Map(captureRenames)
213
+ if (filter.param !== loop.param) rowRenames.set(filter.param, loop.param)
214
+ return {
215
+ kind: 'predicate',
216
+ param: filter.param,
217
+ predicate: filter.predicate,
218
+ captured: renameFreeIdentifiers(filter.predicate, captureRenames),
219
+ onRow: renameFreeIdentifiers(filter.predicate, rowRenames),
220
+ aliases: new Map(captureAliases.map(({ name, alias }) => [alias, name])),
221
+ }
54
222
  }
55
223
 
56
224
  /** Plan a loop against the scope outside it. */
@@ -59,15 +227,35 @@ export function planLoop<Spelled>(loop: IRLoop, ctx: LoopPlanContext<Spelled>):
59
227
  isNameShadowed: ctx.scope.asShadowPredicate(),
60
228
  })
61
229
  const staticSource = staticItems !== null ? ctx.spellStatic(staticItems) : null
230
+ const destructure = destructureKind(loop)
231
+ const captureAliases = filterCaptureCollisions(loop).map((name) => ({ name, alias: `__bf_cap_${loop.markerId}_${name}` }))
62
232
  return {
63
- destructure: destructureKind(loop),
233
+ destructure,
64
234
  staticSource,
65
235
  unresolvableConst: staticSource === null ? unresolvableConst(loop, ctx) : null,
66
- sort: loop.sortComparator ? lowerCallbackMethod('sort', loop.sortComparator.arrow, [], ctx.callbackLowering) : null,
67
- captureAliases: filterCaptureCollisions(loop).map((name) => ({ name, alias: `__bf_cap_${loop.markerId}_${name}` })),
236
+ sort: loop.sortComparator ? lowerSortComparator('sort', loop.sortComparator.arrow, ctx.callbackLowering.adapterName) : null,
237
+ captureAliases,
238
+ filter: filterPlan(loop, captureAliases, ctx.callbackLowering.adapterName),
239
+ itemVar: loop.iterationShape === 'keys' || destructure === 'lowerable' ? '__bf_item' : loop.param,
240
+ indexLocal: indexLocal(loop),
241
+ destructureLocals: destructure === 'lowerable' ? destructureLocals(loop) : [],
68
242
  }
69
243
  }
70
244
 
245
+ function indexLocal(loop: IRLoop): string | null {
246
+ if (loop.objectIteration) return null
247
+ return loop.iterationShape === 'keys' ? loop.param : loop.index
248
+ }
249
+
250
+ function destructureLocals(loop: IRLoop): LoopPlan<unknown>['destructureLocals'] {
251
+ return (loop.paramBindings ?? []).map((b) => {
252
+ const segments = b.segments ?? []
253
+ if (b.rest?.kind === 'array') return { name: b.name, value: { kind: 'slice', segments, from: b.rest.from } }
254
+ if (b.rest?.kind === 'object') return { name: b.name, value: { kind: 'omit', segments, exclude: b.rest.exclude.map((k) => k.key) } }
255
+ return { name: b.name, value: { kind: 'path', segments } }
256
+ })
257
+ }
258
+
71
259
  function destructureKind(loop: IRLoop): LoopPlan<unknown>['destructure'] {
72
260
  if (!loop.paramBindings || loop.paramBindings.length === 0) return 'none'
73
261
  return isLowerableLoopDestructure(loop) ? 'lowerable' : 'unlowerable'
@@ -307,14 +307,18 @@ export function isNumericArithmeticResult(
307
307
 
308
308
  /** A runtime helper of the template-helper catalogue (`spec/template-helpers.md`)
309
309
  * that a binary arithmetic operator lowers to. */
310
- export type ArithmeticHelper = 'mod'
310
+ export type ArithmeticHelper = 'mod' | 'div'
311
311
 
312
312
  /**
313
313
  * The runtime helper a JS binary arithmetic operator lowers to on every
314
314
  * template backend, or `null` when the backend spells the operator itself
315
315
  * (#3474). The adapter only spells the call, in its own syntax
316
- * (`bf.mod(a, b)`, `$bf->mod(a, b)`, `bf_mod a b`), over operands already
317
- * coerced (`arithmeticOperandCoercion`) and grouped ({@link groupBinaryOperand}).
316
+ * (`bf.mod(a, b)`, `$bf->mod(a, b)`, `bf_mod a b`), and the helper's name
317
+ * where its runtime names it differently (Perl's `divide`), over operands
318
+ * already coerced (`arithmeticOperandCoercion`) and grouped
319
+ * ({@link groupBinaryOperand}). Where the adapter leaves the `null`
320
+ * coercion unspelled because the engine's native operator reads nil as `0`
321
+ * (PHP, Perl), the helper reads nil as `0` too.
318
322
  *
319
323
  * `%` is JS's truncated remainder: the result takes the dividend's sign
320
324
  * (`-7 % 2` is `-1`, `7 % -2` is `1`), keeps a fraction (`7.5 % 2` is `1.5`),
@@ -323,9 +327,16 @@ export type ArithmeticHelper = 'mod'
323
327
  * quotient (`-7 % 2` is `1`), MiniJinja takes the Euclidean remainder, PHP,
324
328
  * Perl and Kolon convert the operands to integers first (`NaN % 2` is `0`),
325
329
  * and an integer zero divisor raises in Java, PHP and MiniJinja (#3574).
330
+ *
331
+ * `/` is IEEE division: the quotient keeps its fraction (`7 / 2` is `3.5`),
332
+ * and a zero divisor gives an infinity signed by both operands (`1 / -0` is
333
+ * `-Infinity`) or `NaN` (`0 / 0`). Ruby's `/` on two integers truncates, and
334
+ * Python's and PHP's raise on a zero divisor.
326
335
  */
327
336
  export function arithmeticHelper(op: string): ArithmeticHelper | null {
328
- return op === '%' ? 'mod' : null
337
+ if (op === '%') return 'mod'
338
+ if (op === '/') return 'div'
339
+ return null
329
340
  }
330
341
 
331
342
  /**
@@ -403,6 +414,20 @@ export function groupObjectLiteralSegments(
403
414
  return segments
404
415
  }
405
416
 
417
+ /**
418
+ * The receiver of a zero-arg, non-optional `recv.toString()` call, which
419
+ * stringifies as `String(recv)` does; `null` for any other expression. A
420
+ * radix argument (`n.toString(16)`) and an optional call (`x?.toString()`,
421
+ * `undefined` for a nullish receiver where `String` gives `'undefined'`)
422
+ * are not this shape.
423
+ */
424
+ export function asToStringCall(expr: ParsedExpr): ParsedExpr | null {
425
+ if (expr.kind !== 'call' || expr.args.length !== 0) return null
426
+ const callee = expr.callee
427
+ if (callee.kind !== 'member' || callee.computed || callee.optional || callee.property !== 'toString') return null
428
+ return callee.object
429
+ }
430
+
406
431
  /**
407
432
  * Single point of dispatch from `ParsedExpr.kind` to the adapter's
408
433
  * method. Adapters call this once at their entry point; the recursion
@@ -435,6 +460,14 @@ export function emitParsedExpr(expr: ParsedExpr, emitter: ParsedExprEmitter): st
435
460
  break
436
461
  }
437
462
  }
463
+ // `x.toString()` is `String(x)` (#3621): every adapter registers the
464
+ // `String` template primitive, while a zero-arg method call on a
465
+ // non-global reaches `call()`'s getter fallback, which reads the
466
+ // callee `x.toString` as a property and drops the call.
467
+ const toStringReceiver = asToStringCall(expr)
468
+ if (toStringReceiver) {
469
+ return emitter.call({ kind: 'identifier', name: 'String' }, [toStringReceiver], emit)
470
+ }
438
471
  // A higher-order callback call (`arr.filter(p)` / `arr.sort(cmp)` / …)
439
472
  // routes to the dedicated `callbackMethod` arm; any other call is generic.
440
473
  const cb = asCallbackMethodCall(expr)
package/src/analyzer.ts CHANGED
@@ -10,9 +10,10 @@ import ts from 'typescript'
10
10
  import { foldRenderReassignmentsInSource } from './fold-render-reassignments.ts'
11
11
  import { CLIENT_DIRECTIVE_INTERIOR_RE, USE_CLIENT_DIRECTIVE, isUseClientDirectiveText } from './directives.ts'
12
12
  import type { ImportSpecifier, TypeInfo, ParamInfo, PropDefaultPart, PropDefaultRead, ReactiveFactoryInfo, DeclinedReactiveFactory, RequiredFactoryImport, FactoryRenameSite, SourceLocation, SignalFactoryCall, MemoInfo } from './types.ts'
13
- import { parseExpression, parseBlockBodyTolerant, foldBlockToExpr, tsNodeToParsedExpr, stringifyParsedExpr, type ParsedExpr } from './expression-parser.ts'
13
+ import { CALLBACK_METHODS, parseExpression, parseBlockBodyTolerant, foldBlockToExpr, tsNodeToParsedExpr, stringifyParsedExpr, type ParsedExpr } from './expression-parser.ts'
14
14
  import type { CallbackBodyAcceptor } from './adapters/interface.ts'
15
- import { rewriteBarePropRefs, splitScopedValueRefs } from './prop-rewrite.ts'
15
+ import { collectAssignmentTargets, rewriteBarePropRefs, splitScopedValueRefs } from './prop-rewrite.ts'
16
+ import { isEventHandlerName } from './event-handler-name.ts'
16
17
  import { buildPropAliasMap, coalesceDefaultText, livePropReadExpr, signalPropSeed } from './props-binding.ts'
17
18
  import { incrementCounter } from './instrumentation.ts'
18
19
  import {
@@ -4705,6 +4706,7 @@ function validateContext(ctx: AnalyzerContext): void {
4705
4706
  // `localConstants` binding after its declaration — flag those bindings so
4706
4707
  // downstream inlining never re-embeds their stale initializer text (#2910).
4707
4708
  markMutatedConstants(ctx)
4709
+ markWrittenBindings(ctx)
4708
4710
 
4709
4711
  // BF052: init statements that write to an identifier with no visible
4710
4712
  // declaration cause a ReferenceError in ESM strict mode. Flag them
@@ -5013,6 +5015,285 @@ function markMutatedConstants(ctx: AnalyzerContext): void {
5013
5015
  }
5014
5016
  }
5015
5017
 
5018
+ /**
5019
+ * Flag the component-scope bindings the component writes anywhere in its
5020
+ * body, nested functions and markup included (`collectAssignmentTargets`),
5021
+ * which `markMutatedConstants` does not see: it reads only the top-level
5022
+ * statements, up to the first nested function.
5023
+ *
5024
+ * - Every written binding gets `reassigned` (`ParamInfo` and
5025
+ * `ConstantInfo` alike), so it fails `keepsDeclaredValue`: it is a local
5026
+ * the component owns, never rewritten into a live prop read (`++start`
5027
+ * would become `++(_p.start ?? 0)`, a SyntaxError).
5028
+ * - A `localConstants` binding a write changes during render (a markup
5029
+ * expression, not an event handler) gets `mutatedAfterDeclaration`, like
5030
+ * a top-level statement's write: its declared value is no longer what a
5031
+ * later read sees, so nothing inlines it (`{++nextId}` would become
5032
+ * `++(0)`). A write in an event handler or another callback leaves the
5033
+ * declared value in place for render, so the binding stays inlinable.
5034
+ */
5035
+ function markWrittenBindings(ctx: AnalyzerContext): void {
5036
+ const body = ctx.componentNode?.body
5037
+ if (!body) return
5038
+ const params = ctx.propsObjectName === null ? ctx.propsParams.filter(p => !p.isRest) : []
5039
+ const names = new Set<string>([...params.map(p => p.name), ...ctx.localConstants.map(c => c.name)])
5040
+ if (names.size === 0) return
5041
+
5042
+ const { written, writingInitializers } = collectBindingWrites(ctx, body, names)
5043
+ for (const p of params) {
5044
+ if (written.has(p.name)) p.reassigned = true
5045
+ }
5046
+ for (const c of ctx.localConstants) {
5047
+ const when = written.get(c.name)
5048
+ if (when) c.reassigned = true
5049
+ // A const whose initializer writes (`const label = ++start`) must run
5050
+ // once, where it is declared: inlining its value anywhere else would
5051
+ // repeat the write, or carry it into the template's module scope.
5052
+ if (when === 'render' || writingInitializers.has(c.name)) c.mutatedAfterDeclaration = true
5053
+ }
5054
+ }
5055
+
5056
+ /**
5057
+ * Every write `markWrittenBindings` acts on, by binding: whether one runs
5058
+ * during render, and which top-level declarations' initializers write. A
5059
+ * markup write is reported (BF065) on the way.
5060
+ */
5061
+ function collectBindingWrites(
5062
+ ctx: AnalyzerContext,
5063
+ body: ts.Node,
5064
+ names: ReadonlySet<string>,
5065
+ ): { written: Map<string, 'render' | 'deferred'>; writingInitializers: Set<string | undefined> } {
5066
+ const written = new Map<string, 'render' | 'deferred'>()
5067
+ const writingInitializers = new Set<string | undefined>()
5068
+ const roots: readonly ts.Node[] = ts.isBlock(body) ? body.statements : [body]
5069
+ for (const root of roots) {
5070
+ for (const id of collectAssignmentTargets(root, names)) {
5071
+ const when = writeTiming(id, root)
5072
+ if (when === 'markup') reportMarkupWrite(ctx, id)
5073
+ if (when === 'statement') writingInitializers.add(declaredByInitializer(id, root))
5074
+ if (written.get(id.text) !== 'render') written.set(id.text, when === 'deferred' ? 'deferred' : 'render')
5075
+ }
5076
+ }
5077
+ return { written, writingInitializers }
5078
+ }
5079
+
5080
+ /**
5081
+ * When the write `id` (inside the component-body statement `root`) runs:
5082
+ * `'markup'` while a markup expression renders, `'statement'` while a
5083
+ * top-level statement runs (init runs it too), `'deferred'` later.
5084
+ * `markupTiming` decides a write that markup reaches; any other write keeps
5085
+ * the statement rule (`statementTiming`).
5086
+ */
5087
+ function writeTiming(id: ts.Identifier, root: ts.Node): 'markup' | 'statement' | 'deferred' {
5088
+ const inMarkup = markupTiming(id, root)
5089
+ return inMarkup === 'outside' ? statementTiming(id, root) : inMarkup
5090
+ }
5091
+
5092
+ /**
5093
+ * The one compositional rule for a write markup reaches. From the write
5094
+ * site, climb to the nearest enclosing function literal F:
5095
+ *
5096
+ * - none before a markup expression (`JsxExpression` / spread attribute):
5097
+ * the write runs while that expression renders — `'markup'`, an
5098
+ * event-handler attribute included (`onClick={(++id, () => {})}`);
5099
+ * - F found: follow how F's value is used (`valueUseOf`: parentheses,
5100
+ * casts, a conditional's branches, `&&` / `||` / `??`, a comma's last
5101
+ * operand, object / array literal members — not a spread, which runs
5102
+ * getters or iterates), then
5103
+ * - the callee of a call (an IIFE, `(c ? f : g)()`): F runs when that
5104
+ * call is evaluated — the same rule from the call;
5105
+ * - directly a JSX attribute's value (a child prop, a context value's
5106
+ * `setApi`, an event handler): handed on, it runs when the receiver
5107
+ * calls it — `'deferred'`;
5108
+ * - an argument of a call: `'deferred'` only when that call is, by the
5109
+ * same value walk and through further wrapper calls, an
5110
+ * event-handler attribute's value (`onClick={wrap(() => ++n)}`,
5111
+ * `onInput={debounce(…)}`); otherwise the callee may run it while
5112
+ * rendering (`Array.from(xs, () => ++n)`, `.map`, `.replace`), so
5113
+ * the same rule from the call;
5114
+ * - anything else (stored in a variable, a JSX child): the same rule
5115
+ * from where its value lands, so unknown use inside markup refuses.
5116
+ *
5117
+ * `'outside'` when the climb reaches the component-body statement without
5118
+ * meeting markup.
5119
+ */
5120
+ function markupTiming(site: ts.Node, root: ts.Node): 'markup' | 'deferred' | 'outside' {
5121
+ for (let n: ts.Node = site; n !== root && n.parent; n = n.parent) {
5122
+ const parent = n.parent
5123
+ if (ts.isJsxExpression(parent) || ts.isJsxSpreadAttribute(parent)) return 'markup'
5124
+ if (isFunctionScope(parent)) return functionUseTiming(parent, root)
5125
+ }
5126
+ return 'outside'
5127
+ }
5128
+
5129
+ function functionUseTiming(fn: ts.Node, root: ts.Node): 'markup' | 'deferred' | 'outside' {
5130
+ const { use, dropped } = valueWalk(fn)
5131
+ // A setter an object spread meets is neither copied nor called.
5132
+ if (dropped) return 'deferred'
5133
+ const parent = use.parent
5134
+ if (ts.isJsxExpression(parent) && ts.isJsxAttribute(parent.parent)) return 'deferred'
5135
+ if (ts.isCallExpression(parent) && parent.expression !== use && isEventHandlerValue(parent)) return 'deferred'
5136
+ return markupTiming(ts.isCallExpression(parent) ? parent : use, root)
5137
+ }
5138
+
5139
+ /** Whether `call` is, through value-passing wrappers and further calls, an event-handler attribute's value. */
5140
+ function isEventHandlerValue(call: ts.CallExpression): boolean {
5141
+ const use = valueUseOf(call)
5142
+ const parent = use.parent
5143
+ if (ts.isJsxExpression(parent) && ts.isJsxAttribute(parent.parent)) {
5144
+ return ts.isIdentifier(parent.parent.name) && isEventHandlerName(parent.parent.name.text)
5145
+ }
5146
+ return ts.isCallExpression(parent) && parent.expression !== use && isEventHandlerValue(parent)
5147
+ }
5148
+
5149
+ /**
5150
+ * The outermost expression that carries `node`'s value unchanged: through
5151
+ * parentheses, casts, a conditional's branches (not its condition), `&&` /
5152
+ * `||` / `??`, a comma's last operand, object / array literal members, and a
5153
+ * spread that copies it (`spreadPassesOn`).
5154
+ */
5155
+ function valueUseOf(node: ts.Node): ts.Node {
5156
+ return valueWalk(node).use
5157
+ }
5158
+
5159
+ /**
5160
+ * `valueUseOf`'s walk. `dropped`: the value is a setter an object spread
5161
+ * meets, which the spread neither copies nor calls.
5162
+ */
5163
+ function valueWalk(node: ts.Node): { use: ts.Node; dropped: boolean } {
5164
+ let v = node
5165
+ let member: ts.Node | undefined
5166
+ for (;;) {
5167
+ const p = v.parent
5168
+ if (!p) return { use: v, dropped: false }
5169
+ if (ts.isSpreadAssignment(p) || ts.isSpreadElement(p)) {
5170
+ const spread = spreadPassesOn(p, v, member)
5171
+ if (spread === 'dropped') return { use: v, dropped: true }
5172
+ if (spread === 'consumed') return { use: v, dropped: false }
5173
+ } else if (!passesValueOn(v)) {
5174
+ return { use: v, dropped: false }
5175
+ }
5176
+ if (ts.isObjectLiteralExpression(p)) member = v
5177
+ v = p
5178
+ }
5179
+ }
5180
+
5181
+ /**
5182
+ * What a spread does with its operand `v`, per JavaScript:
5183
+ *
5184
+ * - an object spread copies the operand literal's data properties and
5185
+ * methods (`'passes'`), calls its getters (`'consumed'`: the rule
5186
+ * applies from the spread site) and skips its setters (`'dropped'`);
5187
+ * `member` is the operand member the walk came through;
5188
+ * - an array or argument spread of an array literal copies its elements
5189
+ * (`'passes'`); of anything else it runs the operand's iterator, which may
5190
+ * run any function in it (`'consumed'`).
5191
+ */
5192
+ function spreadPassesOn(
5193
+ p: ts.SpreadAssignment | ts.SpreadElement,
5194
+ v: ts.Node,
5195
+ member: ts.Node | undefined,
5196
+ ): 'passes' | 'consumed' | 'dropped' {
5197
+ if (ts.isSpreadElement(p)) return ts.isArrayLiteralExpression(v) ? 'passes' : 'consumed'
5198
+ if (!ts.isObjectLiteralExpression(v)) return 'consumed'
5199
+ if (member && ts.isGetAccessorDeclaration(member)) return 'consumed'
5200
+ if (member && ts.isSetAccessorDeclaration(member)) return 'dropped'
5201
+ return 'passes'
5202
+ }
5203
+
5204
+ function passesValueOn(v: ts.Node): boolean {
5205
+ const p = v.parent
5206
+ if (ts.isParenthesizedExpression(p) || ts.isAsExpression(p) || ts.isSatisfiesExpression(p)) return true
5207
+ if (ts.isNonNullExpression(p) || ts.isTypeAssertionExpression(p)) return true
5208
+ if (ts.isConditionalExpression(p)) return p.condition !== v
5209
+ if (ts.isBinaryExpression(p)) return isValuePassingOperator(p, v)
5210
+ if (ts.isPropertyAssignment(p)) return p.initializer === v
5211
+ return ts.isObjectLiteralExpression(p) || ts.isArrayLiteralExpression(p)
5212
+ }
5213
+
5214
+ function isValuePassingOperator(p: ts.BinaryExpression, v: ts.Node): boolean {
5215
+ const op = p.operatorToken.kind
5216
+ if (op === ts.SyntaxKind.CommaToken) return p.right === v
5217
+ return op === ts.SyntaxKind.AmpersandAmpersandToken || op === ts.SyntaxKind.BarBarToken || op === ts.SyntaxKind.QuestionQuestionToken
5218
+ }
5219
+
5220
+ /**
5221
+ * The statement rule for a write no markup reaches: a top-level statement
5222
+ * runs during render (`'statement'`) unless a function encloses the write
5223
+ * that is not invoked where it stands (`isInvokedInPlace`) — `'deferred'`.
5224
+ * That only decides whether a later read may inline the binding's declared
5225
+ * value (`mutatedAfterDeclaration`).
5226
+ */
5227
+ function statementTiming(id: ts.Identifier, root: ts.Node): 'statement' | 'deferred' {
5228
+ for (let n: ts.Node = id; n !== root && n.parent; n = n.parent) {
5229
+ if (isFunctionScope(n.parent) && !isInvokedInPlace(n.parent)) return 'deferred'
5230
+ }
5231
+ return 'statement'
5232
+ }
5233
+
5234
+ /**
5235
+ * Whether a function literal outside markup is called where it stands: the
5236
+ * callee of a call (an IIFE, `(() => …)()`), or the callback of an array
5237
+ * iteration method, which calls it before returning (`xs.map(cb)`, the
5238
+ * higher-order methods of `CALLBACK_METHODS`, plus `forEach`). Any other
5239
+ * function there is deferred, which only decides whether a later read may
5240
+ * inline the binding's declared value (`mutatedAfterDeclaration`).
5241
+ */
5242
+ function isInvokedInPlace(fn: ts.Node): boolean {
5243
+ let node = fn
5244
+ while (ts.isParenthesizedExpression(node.parent)) node = node.parent
5245
+ const call = node.parent
5246
+ if (!ts.isCallExpression(call)) return false
5247
+ if (call.expression === node) return true
5248
+ return call.arguments[0] === node && isArrayIterationCallee(call.expression)
5249
+ }
5250
+
5251
+ /** `<receiver>.<method>` where `method` is an array iteration method that calls its callback in place. */
5252
+ function isArrayIterationCallee(callee: ts.Expression): boolean {
5253
+ if (!ts.isPropertyAccessExpression(callee)) return false
5254
+ const method = callee.name.text
5255
+ return CALLBACK_METHODS.has(method) || method === 'forEach'
5256
+ }
5257
+
5258
+ /**
5259
+ * The name a top-level declaration binds when the write `id` sits in its
5260
+ * initializer (`const label = ++start` → `label`), or undefined.
5261
+ */
5262
+ function declaredByInitializer(id: ts.Identifier, root: ts.Node): string | undefined {
5263
+ for (let n: ts.Node = id; n !== root && n.parent; n = n.parent) {
5264
+ const parent = n.parent
5265
+ if (ts.isVariableDeclaration(parent) && parent.initializer === n && ts.isIdentifier(parent.name)) return parent.name.text
5266
+ }
5267
+ return undefined
5268
+ }
5269
+
5270
+ /**
5271
+ * BF065: a client component's markup writes a component binding while it
5272
+ * renders (`{++nextId}`, a `.map()` row that increments a counter). A
5273
+ * callback the markup hands on (an event handler, a child prop, a context
5274
+ * value) is not: it runs when called. The client renders markup in two places that
5275
+ * cannot share that write: the client template, which runs at module scope
5276
+ * with no binding to write, and init, which re-evaluates only reactive
5277
+ * positions. A client-side mount would lose the written value, so the
5278
+ * shape is refused rather than rendered empty. A server-only component has
5279
+ * no client side and renders it as JavaScript does.
5280
+ */
5281
+ function reportMarkupWrite(ctx: AnalyzerContext, id: ts.Identifier): void {
5282
+ if (!ctx.hasUseClientDirective) return
5283
+ ctx.errors.push(
5284
+ createError(ErrorCodes.STAGE_WRITE_IN_MARKUP, getSourceLocation(id, ctx.sourceFile, ctx.filePath), {
5285
+ message:
5286
+ `The markup writes '${id.text}' while it renders. The client template cannot write a component binding, ` +
5287
+ 'so a client-side mount would lose the written value.',
5288
+ suggestion: {
5289
+ message:
5290
+ `Compute the value before the return (\`const label = ++${id.text}\`) and render that, ` +
5291
+ 'or keep the value in a signal and update it from an event handler.',
5292
+ },
5293
+ }),
5294
+ )
5295
+ }
5296
+
5016
5297
  function validateInitStatementReferences(ctx: AnalyzerContext): void {
5017
5298
  if (ctx.initStatements.length === 0) return
5018
5299