@barefootjs/jsx 0.39.7 → 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 (192) hide show
  1. package/dist/adapters/callback-method.d.ts +36 -7
  2. package/dist/adapters/callback-method.d.ts.map +1 -1
  3. package/dist/adapters/component-props.d.ts +80 -13
  4. package/dist/adapters/component-props.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +153 -0
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -0
  7. package/dist/adapters/jsx-adapter.d.ts +4 -0
  8. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  9. package/dist/adapters/literal-value.d.ts +2 -2
  10. package/dist/adapters/literal-value.d.ts.map +1 -1
  11. package/dist/adapters/loop-plan.d.ts +133 -9
  12. package/dist/adapters/loop-plan.d.ts.map +1 -1
  13. package/dist/adapters/parsed-expr-emitter.d.ts +44 -0
  14. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  15. package/dist/adapters/style-object.d.ts +33 -0
  16. package/dist/adapters/style-object.d.ts.map +1 -0
  17. package/dist/analyzer.d.ts.map +1 -1
  18. package/dist/assignment-target.d.ts +26 -0
  19. package/dist/assignment-target.d.ts.map +1 -0
  20. package/dist/children-nullish.d.ts +22 -0
  21. package/dist/children-nullish.d.ts.map +1 -0
  22. package/dist/errors.d.ts +2 -0
  23. package/dist/errors.d.ts.map +1 -1
  24. package/dist/expression-parser.d.ts +9 -19
  25. package/dist/expression-parser.d.ts.map +1 -1
  26. package/dist/free-refs.d.ts +6 -0
  27. package/dist/free-refs.d.ts.map +1 -1
  28. package/dist/index.d.ts +17 -14
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +15040 -13899
  31. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +2 -1
  34. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -2
  36. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  38. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  40. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  42. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +10 -9
  45. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  47. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/emit-reactive.d.ts +1 -1
  49. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  50. package/dist/ir-to-client-js/emit-registration.d.ts +10 -8
  51. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  52. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  53. package/dist/ir-to-client-js/html-template.d.ts +0 -9
  54. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  55. package/dist/ir-to-client-js/identifiers.d.ts +6 -8
  56. package/dist/ir-to-client-js/identifiers.d.ts.map +1 -1
  57. package/dist/ir-to-client-js/imports.d.ts +23 -2
  58. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  59. package/dist/ir-to-client-js/phases/props-extraction.d.ts +6 -3
  60. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  61. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  62. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  63. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +1 -1
  64. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  65. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  66. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +1 -1
  67. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -1
  68. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  69. package/dist/ir-to-client-js/safe-html.d.ts +20 -2
  70. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  71. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  72. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  73. package/dist/ir-to-client-js/types.d.ts +3 -3
  74. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  75. package/dist/ir-to-client-js/utils.d.ts +2 -11
  76. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  77. package/dist/jsx-to-ir.d.ts.map +1 -1
  78. package/dist/nullable-signal-attr.d.ts +40 -10
  79. package/dist/nullable-signal-attr.d.ts.map +1 -1
  80. package/dist/prop-rewrite.d.ts +35 -8
  81. package/dist/prop-rewrite.d.ts.map +1 -1
  82. package/dist/props-binding.d.ts +66 -1
  83. package/dist/props-binding.d.ts.map +1 -1
  84. package/dist/scanner/js-scanner.d.ts.map +1 -1
  85. package/dist/scanner/js-scanner.js +30 -2
  86. package/dist/scope/binding-scope.d.ts +30 -2
  87. package/dist/scope/binding-scope.d.ts.map +1 -1
  88. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  89. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  90. package/dist/signal-prop-name-collision.d.ts +6 -5
  91. package/dist/signal-prop-name-collision.d.ts.map +1 -1
  92. package/dist/ssr-defaults.d.ts +28 -0
  93. package/dist/ssr-defaults.d.ts.map +1 -1
  94. package/dist/ssr-seed-plan.d.ts +39 -14
  95. package/dist/ssr-seed-plan.d.ts.map +1 -1
  96. package/dist/types.d.ts +133 -19
  97. package/dist/types.d.ts.map +1 -1
  98. package/dist/value-references.d.ts +21 -0
  99. package/dist/value-references.d.ts.map +1 -1
  100. package/package.json +2 -2
  101. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +18 -18
  102. package/src/__tests__/adapter-output.test.ts +5 -3
  103. package/src/__tests__/analyzer.test.ts +33 -0
  104. package/src/__tests__/arithmetic-lowering.test.ts +48 -0
  105. package/src/__tests__/binding-scope.test.ts +29 -0
  106. package/src/__tests__/children-read.test.ts +226 -0
  107. package/src/__tests__/client-template-escape-soundness.test.ts +31 -1
  108. package/src/__tests__/component-props.test.ts +68 -1
  109. package/src/__tests__/constant-inlining-tree.test.ts +136 -0
  110. package/src/__tests__/create-query.test.ts +1 -1
  111. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +138 -0
  112. package/src/__tests__/dsl-template-adapter.test.ts +173 -0
  113. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  114. package/src/__tests__/event-handler-verbatim.test.ts +73 -0
  115. package/src/__tests__/expression-parser.test.ts +1 -44
  116. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  117. package/src/__tests__/loop-plan.test.ts +131 -1
  118. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  119. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  120. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  121. package/src/__tests__/nullable-signal-attr.test.ts +67 -3
  122. package/src/__tests__/props-alias-const.test.ts +60 -1
  123. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  124. package/src/__tests__/reference-graph-identifiers.test.ts +161 -0
  125. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  126. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  127. package/src/__tests__/runtime-import-detection.test.ts +134 -0
  128. package/src/__tests__/signal-prop-name-collision.test.ts +30 -0
  129. package/src/__tests__/ssr-defaults.test.ts +19 -1
  130. package/src/__tests__/ssr-seed-plan.test.ts +119 -0
  131. package/src/__tests__/style-object-plan.test.ts +54 -0
  132. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  133. package/src/__tests__/zero-param-helper-inline.test.ts +57 -0
  134. package/src/adapters/callback-method.ts +48 -10
  135. package/src/adapters/component-props.ts +130 -12
  136. package/src/adapters/dsl-template-adapter.ts +259 -0
  137. package/src/adapters/jsx-adapter.ts +12 -6
  138. package/src/adapters/literal-value.ts +2 -2
  139. package/src/adapters/loop-plan.ts +201 -13
  140. package/src/adapters/parsed-expr-emitter.ts +67 -0
  141. package/src/adapters/style-object.ts +61 -0
  142. package/src/analyzer.ts +396 -16
  143. package/src/assignment-target.ts +79 -0
  144. package/src/children-nullish.ts +33 -0
  145. package/src/debug.ts +2 -2
  146. package/src/errors.ts +23 -0
  147. package/src/expression-parser.ts +56 -53
  148. package/src/free-refs.ts +28 -17
  149. package/src/index.ts +31 -10
  150. package/src/ir-to-client-js/compute-inlinability.ts +35 -5
  151. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  152. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +2 -1
  153. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -2
  154. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  155. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  156. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  157. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +3 -2
  158. package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +13 -12
  159. package/src/ir-to-client-js/csr-substitute.ts +82 -24
  160. package/src/ir-to-client-js/emit-reactive.ts +3 -3
  161. package/src/ir-to-client-js/emit-registration.ts +34 -58
  162. package/src/ir-to-client-js/generate-init.ts +17 -1
  163. package/src/ir-to-client-js/html-template.ts +48 -57
  164. package/src/ir-to-client-js/identifiers.ts +75 -24
  165. package/src/ir-to-client-js/imports.ts +56 -19
  166. package/src/ir-to-client-js/index.ts +2 -1
  167. package/src/ir-to-client-js/phases/event-handlers.ts +2 -2
  168. package/src/ir-to-client-js/phases/props-extraction.ts +39 -17
  169. package/src/ir-to-client-js/plan/build-declaration-emit.ts +2 -2
  170. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  171. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  172. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +7 -4
  173. package/src/ir-to-client-js/reactivity.ts +2 -2
  174. package/src/ir-to-client-js/rewrite-destructured-props.ts +22 -5
  175. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  176. package/src/ir-to-client-js/safe-html.ts +29 -35
  177. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  178. package/src/ir-to-client-js/types.ts +3 -2
  179. package/src/ir-to-client-js/utils.ts +42 -122
  180. package/src/jsx-to-ir.ts +310 -90
  181. package/src/nullable-signal-attr.ts +149 -33
  182. package/src/prop-rewrite.ts +72 -72
  183. package/src/props-binding.ts +90 -3
  184. package/src/scanner/__tests__/js-scanner.test.ts +37 -0
  185. package/src/scanner/js-scanner.ts +64 -4
  186. package/src/scope/binding-scope.ts +34 -3
  187. package/src/scope/lexical-scope-walk.ts +167 -0
  188. package/src/signal-prop-name-collision.ts +50 -24
  189. package/src/ssr-defaults.ts +47 -20
  190. package/src/ssr-seed-plan.ts +103 -23
  191. package/src/types.ts +140 -20
  192. package/src/value-references.ts +132 -0
@@ -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'
@@ -305,6 +305,40 @@ export function isNumericArithmeticResult(
305
305
  return expr.op === '-' || expr.op === '*' || expr.op === '/' || expr.op === '%'
306
306
  }
307
307
 
308
+ /** A runtime helper of the template-helper catalogue (`spec/template-helpers.md`)
309
+ * that a binary arithmetic operator lowers to. */
310
+ export type ArithmeticHelper = 'mod' | 'div'
311
+
312
+ /**
313
+ * The runtime helper a JS binary arithmetic operator lowers to on every
314
+ * template backend, or `null` when the backend spells the operator itself
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`), 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.
322
+ *
323
+ * `%` is JS's truncated remainder: the result takes the dividend's sign
324
+ * (`-7 % 2` is `-1`, `7 % -2` is `1`), keeps a fraction (`7.5 % 2` is `1.5`),
325
+ * and is `NaN` for a zero divisor or a `NaN` / infinite dividend. No
326
+ * engine's native operator computes it: Ruby, Python and Perl floor the
327
+ * quotient (`-7 % 2` is `1`), MiniJinja takes the Euclidean remainder, PHP,
328
+ * Perl and Kolon convert the operands to integers first (`NaN % 2` is `0`),
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.
335
+ */
336
+ export function arithmeticHelper(op: string): ArithmeticHelper | null {
337
+ if (op === '%') return 'mod'
338
+ if (op === '/') return 'div'
339
+ return null
340
+ }
341
+
308
342
  /**
309
343
  * Wrap an emitted binary/logical/ternary OPERAND in parentheses so the
310
344
  * source grouping the `ParsedExpr` tree encodes survives infix
@@ -325,6 +359,17 @@ export function groupBinaryOperand(operand: ParsedExpr, emitted: string): string
325
359
  : emitted
326
360
  }
327
361
 
362
+ /**
363
+ * Wrap an emitted unary-minus OPERAND in parentheses where the target's
364
+ * prefix `-` would otherwise bind to only part of it (#3474): a compound
365
+ * operand for the reason {@link groupBinaryOperand} gives (`-(a + b)`
366
+ * re-emitted as `-a + b`), and a nested unary operand, since `--x` is a
367
+ * decrement in PHP and Perl. A leaf operand stays unwrapped.
368
+ */
369
+ export function groupUnaryOperand(operand: ParsedExpr, emitted: string): string {
370
+ return operand.kind === 'unary' ? `(${emitted})` : groupBinaryOperand(operand, emitted)
371
+ }
372
+
328
373
  /**
329
374
  * Split an `object-literal`'s (order-preserving) `properties` into rendered
330
375
  * SEGMENTS an adapter's `objectLiteral()` folds with its own merge idiom
@@ -369,6 +414,20 @@ export function groupObjectLiteralSegments(
369
414
  return segments
370
415
  }
371
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
+
372
431
  /**
373
432
  * Single point of dispatch from `ParsedExpr.kind` to the adapter's
374
433
  * method. Adapters call this once at their entry point; the recursion
@@ -401,6 +460,14 @@ export function emitParsedExpr(expr: ParsedExpr, emitter: ParsedExprEmitter): st
401
460
  break
402
461
  }
403
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
+ }
404
471
  // A higher-order callback call (`arr.filter(p)` / `arr.sort(cmp)` / …)
405
472
  // routes to the dedicated `callbackMethod` arm; any other call is generic.
406
473
  const cb = asCallbackMethodCall(expr)
@@ -0,0 +1,61 @@
1
+ /**
2
+ * `style={{ … }}` object-literal lowering plan, shared by the template
3
+ * adapters (#3541).
4
+ *
5
+ * Every adapter used to re-parse the attribute text through
6
+ * `parseStyleObjectEntries` (a fresh `ts.createSourceFile`) and then each
7
+ * dynamic value through `parseExpression`. The IR already carries the
8
+ * object-literal tree on `ExpressionAttr.parsed`, so the plan reads that:
9
+ * the CSS keys are decided here once, and an adapter spells only its
10
+ * `style_object` runtime call. Reading the tree also accepts the shorthand
11
+ * `{ color }`, which the text parser refused.
12
+ */
13
+
14
+ import type { ExpressionAttr } from '../types.ts'
15
+ import {
16
+ cssKebabCase,
17
+ isSupported,
18
+ stringifyParsedExpr,
19
+ type ParsedExpr,
20
+ } from '../expression-parser.ts'
21
+
22
+ /** One CSS declaration of a style object: a static string, or a value to lower. */
23
+ export type StyleObjectPlanEntry =
24
+ | { cssKey: string; kind: 'literal'; value: string }
25
+ | { cssKey: string; kind: 'expr'; expr: string; parsed: ParsedExpr }
26
+
27
+ /** The static string a value spells, when it is a string or a substitution-free template literal. */
28
+ function staticString(value: ParsedExpr): string | null {
29
+ if (value.kind === 'literal' && value.literalType === 'string' && typeof value.value === 'string') return value.value
30
+ if (value.kind === 'template-literal' && value.parts.every(p => p.type === 'string')) {
31
+ return value.parts.map(p => (p.type === 'string' ? p.value : '')).join('')
32
+ }
33
+ return null
34
+ }
35
+
36
+ /**
37
+ * The CSS declarations of a `style` attribute's object literal, or `null`
38
+ * when the value is not an object literal every entry of which an adapter
39
+ * can lower: a spread, a numeric key, or a value outside the template
40
+ * subset keeps the attribute on the adapter's refusal path.
41
+ */
42
+ export function planStyleObject(value: Pick<ExpressionAttr, 'expr' | 'parsed'>): StyleObjectPlanEntry[] | null {
43
+ // Phase 1 attaches `parsed` to every expression attribute; without it
44
+ // there is no tree to plan from, and the attribute stays on the refusal path.
45
+ const parsed = value.parsed
46
+ if (parsed?.kind !== 'object-literal' || parsed.properties.length === 0) return null
47
+ const entries: StyleObjectPlanEntry[] = []
48
+ for (const prop of parsed.properties) {
49
+ if (prop.kind !== 'prop' || prop.keyKind === 'numeric') return null
50
+ const cssKey = cssKebabCase(prop.key)
51
+ const literal = staticString(prop.value)
52
+ if (literal !== null) {
53
+ entries.push({ cssKey, kind: 'literal', value: literal })
54
+ } else if (isSupported(prop.value).supported) {
55
+ entries.push({ cssKey, kind: 'expr', expr: stringifyParsedExpr(prop.value), parsed: prop.value })
56
+ } else {
57
+ return null
58
+ }
59
+ }
60
+ return entries
61
+ }