@barefootjs/jsx 0.39.8 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/adapters/attr-plan.d.ts +1 -20
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/callback-method.d.ts +19 -7
  4. package/dist/adapters/callback-method.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +79 -1
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  7. package/dist/adapters/loop-plan.d.ts +173 -9
  8. package/dist/adapters/loop-plan.d.ts.map +1 -1
  9. package/dist/adapters/parsed-expr-emitter.d.ts +20 -3
  10. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  11. package/dist/analyzer.d.ts.map +1 -1
  12. package/dist/assignment-target.d.ts +26 -0
  13. package/dist/assignment-target.d.ts.map +1 -0
  14. package/dist/augment-inherited-props.d.ts.map +1 -1
  15. package/dist/css-layer-prefixer.d.ts.map +1 -1
  16. package/dist/debug.d.ts.map +1 -1
  17. package/dist/errors.d.ts +1 -0
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/index.d.ts +6 -6
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +2566 -2007
  22. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  25. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  27. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  29. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  31. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/phases/props-extraction.d.ts +5 -3
  35. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  37. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  40. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/utils.d.ts +1 -1
  42. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  43. package/dist/jsx-to-ir.d.ts.map +1 -1
  44. package/dist/module-exports.d.ts.map +1 -1
  45. package/dist/prop-rewrite.d.ts +17 -8
  46. package/dist/prop-rewrite.d.ts.map +1 -1
  47. package/dist/props-binding.d.ts +57 -0
  48. package/dist/props-binding.d.ts.map +1 -1
  49. package/dist/scope/binding-scope.d.ts +32 -2
  50. package/dist/scope/binding-scope.d.ts.map +1 -1
  51. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  52. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  53. package/dist/template-parts.d.ts +1 -1
  54. package/dist/template-parts.d.ts.map +1 -1
  55. package/dist/types.d.ts +30 -2
  56. package/dist/types.d.ts.map +1 -1
  57. package/package.json +2 -2
  58. package/src/__tests__/arithmetic-lowering.test.ts +5 -1
  59. package/src/__tests__/attr-plan.test.ts +1 -14
  60. package/src/__tests__/binding-scope.test.ts +29 -0
  61. package/src/__tests__/client-template-escape-soundness.test.ts +17 -4
  62. package/src/__tests__/client-template-static-delimiters.test.ts +57 -0
  63. package/src/__tests__/create-query.test.ts +1 -1
  64. package/src/__tests__/dsl-template-adapter.test.ts +70 -0
  65. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  66. package/src/__tests__/extract-function-params.test.ts +37 -0
  67. package/src/__tests__/issue-2960-multi-root-cond-same-tag.test.ts +18 -0
  68. package/src/__tests__/jsx-text-linebreak-whitespace.test.ts +11 -0
  69. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  70. package/src/__tests__/loop-plan.test.ts +196 -1
  71. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  72. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  73. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  74. package/src/__tests__/props-alias-const.test.ts +60 -1
  75. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  76. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  77. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  78. package/src/__tests__/template-parts-literal-boundary.test.ts +22 -0
  79. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  80. package/src/adapters/attr-plan.ts +2 -54
  81. package/src/adapters/callback-method.ts +25 -10
  82. package/src/adapters/dsl-template-adapter.ts +155 -2
  83. package/src/adapters/loop-plan.ts +267 -14
  84. package/src/adapters/parsed-expr-emitter.ts +37 -4
  85. package/src/analyzer.ts +283 -2
  86. package/src/assignment-target.ts +79 -0
  87. package/src/augment-inherited-props.ts +5 -9
  88. package/src/css-layer-prefixer.ts +4 -5
  89. package/src/debug.ts +1 -0
  90. package/src/errors.ts +11 -0
  91. package/src/index.ts +23 -4
  92. package/src/ir-to-client-js/compute-inlinability.ts +7 -4
  93. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  94. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  95. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  96. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  97. package/src/ir-to-client-js/csr-substitute.ts +70 -22
  98. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  99. package/src/ir-to-client-js/emit-registration.ts +6 -1
  100. package/src/ir-to-client-js/html-template.ts +70 -52
  101. package/src/ir-to-client-js/phases/props-extraction.ts +26 -5
  102. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  103. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  104. package/src/ir-to-client-js/rewrite-destructured-props.ts +2 -2
  105. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  106. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  107. package/src/ir-to-client-js/utils.ts +41 -97
  108. package/src/jsx-to-ir.ts +65 -32
  109. package/src/loop-destructure.ts +4 -1
  110. package/src/module-exports.ts +13 -21
  111. package/src/prop-rewrite.ts +31 -72
  112. package/src/props-binding.ts +73 -1
  113. package/src/rich-type-refusal.ts +3 -1
  114. package/src/scope/binding-scope.ts +39 -3
  115. package/src/scope/lexical-scope-walk.ts +167 -0
  116. package/src/template-parts.ts +4 -2
  117. package/src/template-position-walk.ts +3 -1
  118. package/src/types.ts +27 -2
@@ -86,14 +86,22 @@ export interface CallbackEvalPlan {
86
86
  captured: string[]
87
87
  }
88
88
 
89
- /** A lowered callback method call, as data. */
90
- export type CallbackPlan =
89
+ /**
90
+ * A lowered `.sort` / `.toSorted` comparator: the evaluator call, the
91
+ * structured `{keys: …}` descriptor for a comparator the evaluator cannot
92
+ * model, or BF101.
93
+ */
94
+ export type SortPlan =
91
95
  | CallbackEvalPlan
92
96
  /** A comparator the evaluator cannot model but the `{keys: …}` descriptor can. */
93
97
  | { kind: 'structured-sort'; comparator: SortComparator }
98
+ | { kind: 'refuse'; message: string; suggestion: string }
99
+
100
+ /** A lowered callback method call, as data. */
101
+ export type CallbackPlan =
102
+ | SortPlan
94
103
  /** A predicate for the adapter's own native form (see `nativePredicate`). */
95
104
  | { kind: 'native-predicate'; method: PredicateMethod; param: string; predicate: ParsedExpr }
96
- | { kind: 'refuse'; message: string; suggestion: string }
97
105
  /** A method outside `CALLBACK_METHODS`; unreachable, as the parser recognises only those. */
98
106
  | { kind: 'receiver' }
99
107
 
@@ -119,13 +127,7 @@ export function lowerCallbackMethod(
119
127
  const { adapterName } = options
120
128
  const { body, params } = arrow
121
129
  if (isPredicateMethod(method)) return lowerPredicate(method, arrow, options)
122
- if (method === 'sort' || method === 'toSorted') {
123
- const plan = sortEvalPlan(body, params)
124
- if (plan) return plan
125
- const comparator = sortComparatorFromArrow(arrow)
126
- if (comparator) return { kind: 'structured-sort', comparator }
127
- return sortRefusal(method, adapterName)
128
- }
130
+ if (method === 'sort' || method === 'toSorted') return lowerSortComparator(method, arrow, adapterName)
129
131
  if (method === 'reduce' || method === 'reduceRight') {
130
132
  const init = restArgs[0]
131
133
  const plan = init ? reduceEvalPlan(body, params, init, method === 'reduceRight' ? 'right' : 'left') : null
@@ -178,6 +180,19 @@ function lowerPredicate(method: PredicateMethod, arrow: Arrow, options: Callback
178
180
  }
179
181
  }
180
182
 
183
+ /**
184
+ * Lower a `.sort` / `.toSorted` comparator: the evaluator first, then the
185
+ * structured `{keys: …}` descriptor, otherwise BF101. A loop source's sort
186
+ * (`planLoop`) and `.sort(cmp)` at an expression position decide the same.
187
+ */
188
+ export function lowerSortComparator(method: 'sort' | 'toSorted', arrow: Arrow, adapterName: string): SortPlan {
189
+ const plan = sortEvalPlan(arrow.body, arrow.params)
190
+ if (plan) return plan
191
+ const comparator = sortComparatorFromArrow(arrow)
192
+ if (comparator) return { kind: 'structured-sort', comparator }
193
+ return sortRefusal(method, adapterName)
194
+ }
195
+
181
196
  /**
182
197
  * The evaluator plan for a sort comparator, or `null` when the body is
183
198
  * outside the evaluator surface (a `localeCompare` comparator) or the arrow
@@ -14,12 +14,21 @@ import {
14
14
  type NullishAttrContext,
15
15
  } from '../nullable-signal-attr.ts'
16
16
  import { BindingScope } from '../scope/binding-scope.ts'
17
- import { rootPropAliasNames } from '../scope/root-prop-alias.ts'
18
- import type { CompilerError, ComponentIR, IRIfStatement, IRMetadata } from '../types.ts'
17
+ import { rootPropAliasesForLoop, rootPropAliasNames } from '../scope/root-prop-alias.ts'
18
+ import type {
19
+ CompilerError,
20
+ ComponentIR,
21
+ ConstantInfo,
22
+ IRIfStatement,
23
+ IRLoop,
24
+ IRMetadata,
25
+ PreambleValueDeclaration,
26
+ } from '../types.ts'
19
27
  import { collectImportedLoopChildComponentErrors } from './component-tree.ts'
20
28
  import { computedConstContext, type ComputedConstContext } from './computed-const.ts'
21
29
  import { searchParamsLocalNames } from './env-signal.ts'
22
30
  import { BaseAdapter, type AdapterGenerateOptions, type AdapterOutput } from './interface.ts'
31
+ import { type LoopPlan, type LoopPlanContext, planLoop } from './loop-plan.ts'
23
32
  import { collectBooleanTypedProps, collectNullableOptionalProps } from './prop-classes.ts'
24
33
  import { templateNameCollisionErrors } from './template-name-collisions.ts'
25
34
 
@@ -34,6 +43,56 @@ export interface TemplateIdentifierSpelling {
34
43
  label: string
35
44
  }
36
45
 
46
+ /**
47
+ * An adapter's spelling of a loop row's window ({@link DslTemplateAdapter.renderLoopRow}).
48
+ * Each hook runs under the row's scope.
49
+ */
50
+ export interface LoopRowSpelling {
51
+ /** Runs first, before anything in the row renders: the adapter's own per-row bookkeeping. */
52
+ enter?(row: BindingScope, outside: BindingScope): void
53
+ /** A `.map()` preamble declaration as a per-row local (#2447). */
54
+ preamble(declaration: PreambleValueDeclaration): string
55
+ /** The whole-item-conditional `<!--bf-loop-i:KEY-->` anchor for the key expression `key`. */
56
+ keyAnchor(key: string): string
57
+ }
58
+
59
+ /** A loop row rendered under its own scope. */
60
+ export interface LoopRow {
61
+ /** The scope outside the loop, current again once the row is rendered. */
62
+ outside: BindingScope
63
+ /** `outside.enterLoopRow(loop)`: the scope the row rendered under. */
64
+ row: BindingScope
65
+ /** The props the row's bindings newly shadow, each with its root alias (#3314). */
66
+ rootAliases: { name: string; alias: string }[]
67
+ /** One spelled local per preamble declaration, in source order. */
68
+ preamble: string[]
69
+ /** The children, after the key anchor of a whole-item-conditional body. */
70
+ body: string
71
+ }
72
+
73
+ /** The parts of a {@link LoopPlanContext} each adapter spells. */
74
+ export type LoopPlanSpelling<Spelled> = Pick<
75
+ LoopPlanContext<Spelled>,
76
+ 'resolveLiteralConst' | 'callbackLowering' | 'spellStatic'
77
+ >
78
+
79
+ /**
80
+ * An adapter's wording of the refusals a {@link LoopPlan} decides
81
+ * ({@link DslTemplateAdapter.recordLoopPlanRefusals}).
82
+ */
83
+ export interface LoopRefusalSpelling {
84
+ /** The BF104 message for a destructure pattern `param` that no template binds. */
85
+ destructureMessage(param: string): string
86
+ /** The BF104 suggestion. */
87
+ destructureSuggestion: string
88
+ /**
89
+ * BF101 for a source naming a const no template binds: the engine name
90
+ * the shared wording uses ("Jinja", "MiniJinja", …), or the adapter's own
91
+ * recording of it.
92
+ */
93
+ unresolvableConst: string | ((constant: ConstantInfo) => void)
94
+ }
95
+
37
96
  export abstract class DslTemplateAdapter extends BaseAdapter {
38
97
  // ===========================================================================
39
98
  // Per-compile state, set at `generate()` entry
@@ -127,6 +186,12 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
127
186
  protected importAliases: Map<string, string> = new Map()
128
187
  /** Numbers the children captures of a child component that has no slot id. */
129
188
  protected childrenCaptureCounter = 0
189
+ /**
190
+ * True while a loop row's children render ({@link renderLoopRow}): a
191
+ * component inside takes the loop-child naming, and a child prop that
192
+ * needs a per-instance value has none to read.
193
+ */
194
+ protected inLoop = false
130
195
 
131
196
  // ===========================================================================
132
197
  // What each adapter supplies
@@ -147,6 +212,93 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
147
212
  * above and before any diagnostic or rendering.
148
213
  */
149
214
  protected resetAdapterState(_ir: ComponentIR): void {}
215
+
216
+ /** `render()` under `scope`, the current scope restored afterwards. */
217
+ protected renderInScope<T>(scope: BindingScope, render: () => T): T {
218
+ const outer = this.scope
219
+ this.scope = scope
220
+ try {
221
+ return render()
222
+ } finally {
223
+ this.scope = outer
224
+ }
225
+ }
226
+
227
+ /** {@link planLoop} against the current scope and the component's constants. */
228
+ protected loopPlanFor<Spelled>(loop: IRLoop, spelling: LoopPlanSpelling<Spelled>): LoopPlan<Spelled> {
229
+ return planLoop(loop, { scope: this.scope, localConstants: this.localConstants ?? [], ...spelling })
230
+ }
231
+
232
+ /**
233
+ * Record the refusals `plan` decided for `loop`, at the loop's location:
234
+ * BF104 for a destructure pattern no template binds, then BF101 for a
235
+ * source naming a computed const no template binds (#3473). The plan
236
+ * decides; the adapter only words them.
237
+ */
238
+ protected recordLoopPlanRefusals(loop: IRLoop, plan: LoopPlan<unknown>, spelling: LoopRefusalSpelling): void {
239
+ const loc = loop.loc ?? { file: this.componentName + '.tsx', start: { line: 1, column: 0 }, end: { line: 1, column: 0 } }
240
+ if (plan.destructure === 'unlowerable') {
241
+ this.errors.push({
242
+ code: 'BF104',
243
+ severity: 'error',
244
+ message: spelling.destructureMessage(loop.param),
245
+ loc,
246
+ suggestion: { message: spelling.destructureSuggestion },
247
+ })
248
+ }
249
+ const constant = plan.unresolvableConst
250
+ if (!constant) return
251
+ if (typeof spelling.unresolvableConst === 'function') {
252
+ spelling.unresolvableConst(constant)
253
+ return
254
+ }
255
+ this.errors.push({
256
+ code: 'BF101',
257
+ severity: 'error',
258
+ message: `Loop array \`${constant.name}\` is a const (module- or function-scope) computed value (\`${constant.value}\`) that the ${spelling.unresolvableConst} adapter cannot bind as a template variable — only numeric/string-literal locals inline at their use site.`,
259
+ loc,
260
+ suggestion: {
261
+ message:
262
+ 'Pre-compute the array server-side and pass it as a prop, or mark the loop position as @client-only so it runs in JS on the client.',
263
+ escape: [{ kind: 'prop-precompute' }, { kind: 'client-directive' }],
264
+ },
265
+ })
266
+ }
267
+
268
+ /**
269
+ * A loop row's window (#3473): the row's scope entered around everything
270
+ * that evaluates per row (the preamble locals' initializers, the children,
271
+ * the whole-item-conditional key anchor) and the outer scope restored
272
+ * after. The children render under `inLoop`; the key anchor, after them,
273
+ * does not. The preamble converts first, so a later initializer sees an
274
+ * earlier local, as in the source block.
275
+ *
276
+ * What sits outside the window stays the adapter's: the loop header, the
277
+ * sort, and the filter predicate, which a filter callback's own frame
278
+ * scopes rather than the `.map()` row.
279
+ */
280
+ protected renderLoopRow(loop: IRLoop, spelling: LoopRowSpelling): LoopRow {
281
+ const outside = this.scope
282
+ const row = outside.enterLoopRow(loop)
283
+ return this.renderInScope(row, () => {
284
+ spelling.enter?.(row, outside)
285
+ const preamble = (loop.preamble?.declarations ?? []).map(d => spelling.preamble(d))
286
+ const children = this.renderInLoop(() => this.renderChildren(loop.children))
287
+ const body = loop.bodyIsItemConditional && loop.key ? `${spelling.keyAnchor(loop.key)}\n${children}` : children
288
+ return { outside, row, rootAliases: rootPropAliasesForLoop(outside, row, this.rootPropAliases), preamble, body }
289
+ })
290
+ }
291
+
292
+ private renderInLoop<T>(render: () => T): T {
293
+ const outer = this.inLoop
294
+ this.inLoop = true
295
+ try {
296
+ return render()
297
+ } finally {
298
+ this.inLoop = outer
299
+ }
300
+ }
301
+
150
302
  /** The root `if` statement of a component with conditional returns. */
151
303
  protected abstract renderIfStatement(ifStmt: IRIfStatement): string
152
304
  /** The script registrations the template starts with. */
@@ -225,6 +377,7 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
225
377
  this.computedConsts = computedConstContext(ir.metadata, name => this.scope.isBound(name))
226
378
  this.importAliases = buildImportAliasMap(ir.metadata.imports ?? [])
227
379
  this.childrenCaptureCounter = 0
380
+ this.inLoop = false
228
381
  this.errors = []
229
382
  this.resetAdapterState(ir)
230
383
  }
@@ -4,19 +4,29 @@
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; {@link savedLoopBindings} decides, against the row's scope, which
12
+ * row bindings a backend without loop-scoped `set` saves and restores. The adapter keeps the spelling:
13
+ * the loop header, the row bindings, the diagnostics' wording, and the order
14
+ * it emits them in.
12
15
  */
13
16
 
14
- import { parseExpression } from '../expression-parser.ts'
17
+ import { type ParsedExpr, parseExpression, renameFreeIdentifiers, type SortComparator } from '../expression-parser.ts'
15
18
  import { isLowerableLoopDestructure } from '../loop-destructure.ts'
16
- import type { BindingScope } from '../scope/binding-scope.ts'
19
+ import type { BindingScope, ScopeBindingSource } from '../scope/binding-scope.ts'
17
20
  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'
21
+ import type { ConstantInfo, IRLoop, LoopBindingPathSegment } from '../types.ts'
22
+ import {
23
+ type CallbackEvalSpelling,
24
+ type CallbackLoweringOptions,
25
+ emitCallbackEval,
26
+ lowerSortComparator,
27
+ missingFilterPredicateRefusal,
28
+ type SortPlan,
29
+ } from './callback-method.ts'
20
30
  import { filterCaptureCollisions } from './filter-capture-collisions.ts'
21
31
 
22
32
  export interface LoopPlanContext<Spelled> {
@@ -47,10 +57,233 @@ export interface LoopPlan<Spelled> {
47
57
  * name is the row's value, not the const (#3473).
48
58
  */
49
59
  unresolvableConst: ConstantInfo | null
50
- /** The `.sort` / `.toSorted` comparator's lowering, or `null` without one. */
51
- sort: CallbackPlan | null
60
+ /**
61
+ * The `.sort` / `.toSorted` comparator's lowering, or `null` without one:
62
+ * the evaluator, the structured `{keys: …}` descriptor, or BF101, the same
63
+ * chain as `.sort(cmp)` at an expression position.
64
+ */
65
+ sort: SortPlan | null
52
66
  /** The filter predicate's captures that a row binding would shadow, each with its alias. */
53
67
  captureAliases: Array<{ name: string; alias: string }>
68
+ /** The `.filter()` predicate of a `.filter().map()` loop, or `null` without one. */
69
+ filter: LoopFilterPlan | null
70
+ /**
71
+ * The for-target of an array iteration: the param itself, or the synthetic
72
+ * `__bf_item` when the param is not the item (a `.keys()` iteration, whose
73
+ * param is the index, or a lowered destructure, whose bindings read off it).
74
+ */
75
+ itemVar: string
76
+ /**
77
+ * The name a local binds to the row's 0-based index in an array iteration:
78
+ * a `.keys()` iteration's param, else the explicit index param. `null` for
79
+ * an object iteration, whose key the header binds.
80
+ */
81
+ indexLocal: string | null
82
+ /** One local per binding of a lowered destructure, in pattern order. */
83
+ destructureLocals: Array<{ name: string; value: DestructureValue }>
84
+ }
85
+
86
+ /**
87
+ * What a lowered destructure binding reads off the row item: the value at
88
+ * `segments`, or for a rest binding the residual of the value there (the
89
+ * array from `from` on, or the object without the `exclude` keys).
90
+ */
91
+ export type DestructureValue =
92
+ | { kind: 'path'; segments: readonly LoopBindingPathSegment[] }
93
+ | { kind: 'slice'; segments: readonly LoopBindingPathSegment[]; from: number }
94
+ | { kind: 'omit'; segments: readonly LoopBindingPathSegment[]; exclude: readonly string[] }
95
+
96
+ /** An adapter's spelling of a {@link DestructureValue}. */
97
+ export interface DestructureSpelling {
98
+ /** The value at `segments` off `item`. */
99
+ accessor(item: string, segments: readonly LoopBindingPathSegment[]): string
100
+ /** The array `parent` from index `from` on. */
101
+ slice(parent: string, from: number): string
102
+ /** The object `parent` without the `keys`. */
103
+ omit(parent: string, keys: readonly string[]): string
104
+ }
105
+
106
+ /** Spell each destructure local's value off the row item `item`. */
107
+ export function spellDestructureLocals(
108
+ plan: Pick<LoopPlan<unknown>, 'destructureLocals'>,
109
+ item: string,
110
+ spelling: DestructureSpelling,
111
+ ): Array<{ name: string; value: string }> {
112
+ return plan.destructureLocals.map(({ name, value }) => {
113
+ const parent = spelling.accessor(item, value.segments)
114
+ if (value.kind === 'slice') return { name, value: spelling.slice(parent, value.from) }
115
+ if (value.kind === 'omit') return { name, value: spelling.omit(parent, value.exclude) }
116
+ return { name, value: parent }
117
+ })
118
+ }
119
+
120
+ /** An adapter's spelling of a {@link SortPlan} over the loop source. */
121
+ export interface LoopSortSpelling {
122
+ /** A captured name's SSR value, for the evaluator's env. */
123
+ emit(e: ParsedExpr): string
124
+ /** The evaluator call. */
125
+ eval: CallbackEvalSpelling
126
+ /** The structured `bf.sort` call over `recv` with the `{keys: …}` descriptor. */
127
+ structured(recv: string, comparator: SortComparator): string
128
+ /** Record the refusal of a comparator neither form models (BF101). */
129
+ refuse(message: string, suggestion: string): void
130
+ }
131
+
132
+ /**
133
+ * The loop source `recv` sorted by the loop's comparator, or `recv` itself
134
+ * without one. A refused comparator is recorded and leaves `recv` unsorted,
135
+ * so the template stays valid.
136
+ */
137
+ export function spellSortedSource(sort: SortPlan | null, recv: string, spelling: LoopSortSpelling): string {
138
+ if (!sort) return recv
139
+ if (sort.kind === 'eval') return emitCallbackEval(sort, recv, spelling.emit, spelling.eval)
140
+ if (sort.kind === 'structured-sort') return spelling.structured(recv, sort.comparator)
141
+ spelling.refuse(sort.message, sort.suggestion)
142
+ return recv
143
+ }
144
+
145
+ /**
146
+ * The names a loop's for-header binds: the key and the value of an
147
+ * `entries` object iteration, the param of a `keys` / `values` one, and the
148
+ * item var of an array iteration when it is the param itself. A backend
149
+ * whose for-header scopes its targets to the loop passes these to
150
+ * {@link savedLoopBindings} as names it restores itself.
151
+ */
152
+ export function loopHeaderTargets(loop: IRLoop, plan: Pick<LoopPlan<unknown>, 'itemVar'>): string[] {
153
+ if (loop.objectIteration === 'entries') return [loop.index ?? loop.param, loop.param]
154
+ return loop.objectIteration || plan.itemVar === loop.param ? [loop.param] : []
155
+ }
156
+
157
+ /** Where a loop row sits, for {@link savedLoopBindings}. */
158
+ export interface LoopRowScopes {
159
+ /** The scope outside the loop. */
160
+ outside: BindingScope
161
+ /** `outside.enterLoopRow(loop)`. */
162
+ row: BindingScope
163
+ /** The template-level names: signals, memos, props and constants. */
164
+ templateLevelNames: ReadonlySet<string>
165
+ }
166
+
167
+ const SAVE_ORDER: readonly ScopeBindingSource[] = ['item', 'index', 'destructure', 'preamble']
168
+
169
+ /** A row binding a loop saves before its header and restores after its end. */
170
+ export interface SavedLoopBinding {
171
+ name: string
172
+ /** The template variable that holds the outer value across the loop. */
173
+ temporary: string
174
+ }
175
+
176
+ /**
177
+ * The row bindings a backend whose `set` is not loop-scoped (Pebble, Twig,
178
+ * Blade) saves before the loop and restores after it (#3386, #3391): each
179
+ * name the row binds that already means something outside it, an enclosing
180
+ * row's binding or a template-level name. JS scopes the callback's bindings
181
+ * to the row; without the restore the last row's value leaks past the loop.
182
+ * They come in the order a row binds them in a template: the for-header's
183
+ * item, the index local, each destructure local, each preamble local.
184
+ *
185
+ * `skip` names the bindings the backend restores itself: those its
186
+ * for-header scopes to the loop ({@link loopHeaderTargets}), or a root prop
187
+ * it restores through its alias. `temporary` spells the holder of the
188
+ * `ordinal`-th saved name; a holder that collides with a row binding or a
189
+ * template-level name gets `_` appended until it does not.
190
+ */
191
+ export function savedLoopBindings(
192
+ scopes: LoopRowScopes,
193
+ skip: Iterable<string>,
194
+ temporary: (name: string, ordinal: number) => string,
195
+ ): SavedLoopBinding[] {
196
+ const skipped = new Set(skip)
197
+ const rank = (name: string) => SAVE_ORDER.indexOf(scopes.row.lookup(name)?.binding.source ?? 'param')
198
+ return scopes.row
199
+ .innermostNames()
200
+ .filter((name) => !skipped.has(name) && (scopes.templateLevelNames.has(name) || scopes.outside.isBound(name)))
201
+ .sort((a, b) => rank(a) - rank(b))
202
+ .map((name, ordinal) => {
203
+ let held = temporary(name, ordinal)
204
+ while (scopes.row.isBound(held) || scopes.templateLevelNames.has(held)) held += '_'
205
+ return { name, temporary: held }
206
+ })
207
+ }
208
+
209
+ /**
210
+ * The `.filter()` predicate a `.filter().map()` loop tests on each row: the
211
+ * predicate with the names it reads renamed for the row, or the refusal of a
212
+ * filter whose predicate never reached the IR (BF101, #3534).
213
+ */
214
+ export type LoopFilterPlan = LoopFilterPredicate | { kind: 'refuse'; message: string; suggestion: string }
215
+
216
+ export interface LoopFilterPredicate {
217
+ kind: 'predicate'
218
+ /** The filter callback's own param. */
219
+ param: string
220
+ /** The predicate as written. */
221
+ predicate: ParsedExpr
222
+ /**
223
+ * The predicate with each capture a row binding would shadow renamed to
224
+ * its alias (`captureAliases`), for an emitter that maps the filter param
225
+ * itself (#3402).
226
+ */
227
+ captured: ParsedExpr
228
+ /**
229
+ * `captured` with the filter param renamed to the loop param too: the
230
+ * predicate read off the row item. The tree is renamed, not the rendered
231
+ * text, so a string literal or a property key of the same spelling stays
232
+ * (#3404).
233
+ */
234
+ onRow: ParsedExpr
235
+ /** Each capture alias and the enclosing name it keeps, for the scope the predicate renders under. */
236
+ aliases: ReadonlyMap<string, string>
237
+ }
238
+
239
+ /** An adapter's spelling of a {@link LoopFilterPlan}. */
240
+ export interface LoopFilterSpelling {
241
+ /** The row's condition for a predicate. */
242
+ condition(filter: LoopFilterPredicate): string
243
+ /** Record the refusal of a filter without a predicate. */
244
+ refuse(message: string, suggestion: string): void
245
+ /** The condition that stands in for a refused predicate, so the template stays valid. */
246
+ refused: string
247
+ /** The guard's opening line. */
248
+ open(condition: string): string
249
+ /** The guard's closing line. */
250
+ close: string
251
+ }
252
+
253
+ /**
254
+ * The lines of a loop row: `row` itself, or with a filter `row` inside the
255
+ * guard on the filter's condition.
256
+ */
257
+ export function spellFilteredRow(filter: LoopFilterPlan | null, row: readonly string[], spelling: LoopFilterSpelling): string[] {
258
+ if (!filter) return [...row]
259
+ return [spelling.open(filterCondition(filter, spelling)), ...row, spelling.close]
260
+ }
261
+
262
+ function filterCondition(filter: LoopFilterPlan, spelling: LoopFilterSpelling): string {
263
+ if (filter.kind === 'predicate') return spelling.condition(filter)
264
+ spelling.refuse(filter.message, filter.suggestion)
265
+ return spelling.refused
266
+ }
267
+
268
+ function filterPlan(
269
+ loop: IRLoop,
270
+ captureAliases: LoopPlan<unknown>['captureAliases'],
271
+ adapterName: string,
272
+ ): LoopFilterPlan | null {
273
+ const filter = loop.filterPredicate
274
+ if (!filter) return null
275
+ if (!filter.predicate) return { kind: 'refuse', ...missingFilterPredicateRefusal(filter.raw, adapterName) }
276
+ const captureRenames = new Map(captureAliases.map(({ name, alias }) => [name, alias]))
277
+ const rowRenames = new Map(captureRenames)
278
+ if (filter.param !== loop.param) rowRenames.set(filter.param, loop.param)
279
+ return {
280
+ kind: 'predicate',
281
+ param: filter.param,
282
+ predicate: filter.predicate,
283
+ captured: renameFreeIdentifiers(filter.predicate, captureRenames),
284
+ onRow: renameFreeIdentifiers(filter.predicate, rowRenames),
285
+ aliases: new Map(captureAliases.map(({ name, alias }) => [alias, name])),
286
+ }
54
287
  }
55
288
 
56
289
  /** Plan a loop against the scope outside it. */
@@ -59,15 +292,35 @@ export function planLoop<Spelled>(loop: IRLoop, ctx: LoopPlanContext<Spelled>):
59
292
  isNameShadowed: ctx.scope.asShadowPredicate(),
60
293
  })
61
294
  const staticSource = staticItems !== null ? ctx.spellStatic(staticItems) : null
295
+ const destructure = destructureKind(loop)
296
+ const captureAliases = filterCaptureCollisions(loop).map((name) => ({ name, alias: `__bf_cap_${loop.markerId}_${name}` }))
62
297
  return {
63
- destructure: destructureKind(loop),
298
+ destructure,
64
299
  staticSource,
65
300
  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}` })),
301
+ sort: loop.sortComparator ? lowerSortComparator('sort', loop.sortComparator.arrow, ctx.callbackLowering.adapterName) : null,
302
+ captureAliases,
303
+ filter: filterPlan(loop, captureAliases, ctx.callbackLowering.adapterName),
304
+ itemVar: loop.iterationShape === 'keys' || destructure === 'lowerable' ? '__bf_item' : loop.param,
305
+ indexLocal: indexLocal(loop),
306
+ destructureLocals: destructure === 'lowerable' ? destructureLocals(loop) : [],
68
307
  }
69
308
  }
70
309
 
310
+ function indexLocal(loop: IRLoop): string | null {
311
+ if (loop.objectIteration) return null
312
+ return loop.iterationShape === 'keys' ? loop.param : loop.index
313
+ }
314
+
315
+ function destructureLocals(loop: IRLoop): LoopPlan<unknown>['destructureLocals'] {
316
+ return (loop.paramBindings ?? []).map((b) => {
317
+ const segments = b.segments ?? []
318
+ if (b.rest?.kind === 'array') return { name: b.name, value: { kind: 'slice', segments, from: b.rest.from } }
319
+ if (b.rest?.kind === 'object') return { name: b.name, value: { kind: 'omit', segments, exclude: b.rest.exclude.map((k) => k.key) } }
320
+ return { name: b.name, value: { kind: 'path', segments } }
321
+ })
322
+ }
323
+
71
324
  function destructureKind(loop: IRLoop): LoopPlan<unknown>['destructure'] {
72
325
  if (!loop.paramBindings || loop.paramBindings.length === 0) return 'none'
73
326
  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)