@barefootjs/jsx 0.39.4 → 0.39.6

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 (97) hide show
  1. package/dist/adapters/array-method.d.ts +93 -0
  2. package/dist/adapters/array-method.d.ts.map +1 -0
  3. package/dist/adapters/attr-plan.d.ts +135 -0
  4. package/dist/adapters/attr-plan.d.ts.map +1 -0
  5. package/dist/adapters/boolean-result.d.ts +84 -9
  6. package/dist/adapters/boolean-result.d.ts.map +1 -1
  7. package/dist/adapters/callback-method.d.ts +126 -0
  8. package/dist/adapters/callback-method.d.ts.map +1 -0
  9. package/dist/adapters/component-props.d.ts +99 -0
  10. package/dist/adapters/component-props.d.ts.map +1 -0
  11. package/dist/adapters/component-tree.d.ts +25 -0
  12. package/dist/adapters/component-tree.d.ts.map +1 -0
  13. package/dist/adapters/filter-capture-collisions.d.ts +17 -0
  14. package/dist/adapters/filter-capture-collisions.d.ts.map +1 -0
  15. package/dist/adapters/literal-value.d.ts +22 -0
  16. package/dist/adapters/literal-value.d.ts.map +1 -0
  17. package/dist/adapters/loop-plan.d.ts +53 -0
  18. package/dist/adapters/loop-plan.d.ts.map +1 -0
  19. package/dist/adapters/parsed-expr-emitter.d.ts +8 -0
  20. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  21. package/dist/adapters/prop-classes.d.ts +37 -0
  22. package/dist/adapters/prop-classes.d.ts.map +1 -0
  23. package/dist/adapters/template-name-collisions.d.ts +21 -0
  24. package/dist/adapters/template-name-collisions.d.ts.map +1 -0
  25. package/dist/analyzer-context.d.ts.map +1 -1
  26. package/dist/expression-parser.d.ts +48 -0
  27. package/dist/expression-parser.d.ts.map +1 -1
  28. package/dist/index.d.ts +20 -4
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +2077 -1000
  31. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +8 -0
  33. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts +3 -2
  35. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/utils.d.ts +39 -1
  39. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  40. package/dist/jsx-to-ir.d.ts +465 -1
  41. package/dist/jsx-to-ir.d.ts.map +1 -1
  42. package/dist/nullable-signal-attr.d.ts +31 -0
  43. package/dist/nullable-signal-attr.d.ts.map +1 -1
  44. package/dist/scope/binding-scope.d.ts +10 -0
  45. package/dist/scope/binding-scope.d.ts.map +1 -1
  46. package/dist/types.d.ts +7 -0
  47. package/dist/types.d.ts.map +1 -1
  48. package/package.json +2 -2
  49. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +1 -1
  50. package/src/__tests__/action-accessor.test.ts +6 -24
  51. package/src/__tests__/array-method-catalogue.test.ts +99 -0
  52. package/src/__tests__/attr-plan.test.ts +121 -0
  53. package/src/__tests__/binding-scope-ratchet.test.ts +13 -13
  54. package/src/__tests__/binding-scope.test.ts +11 -0
  55. package/src/__tests__/boolean-result-expr.test.ts +106 -0
  56. package/src/__tests__/boolean-result.test.ts +34 -1
  57. package/src/__tests__/callback-method.test.ts +189 -0
  58. package/src/__tests__/compile-without-node-process.test.ts +78 -0
  59. package/src/__tests__/component-props.test.ts +148 -0
  60. package/src/__tests__/delegated-handler-preamble.test.ts +4 -4
  61. package/src/__tests__/doc-examples.test.ts +1 -0
  62. package/src/__tests__/dsl-shared-helpers.test.ts +166 -0
  63. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +1 -1
  64. package/src/__tests__/loop-plan.test.ts +104 -0
  65. package/src/__tests__/map-call-decisions.test.ts +521 -0
  66. package/src/__tests__/nested-row-shadowing.test.ts +57 -0
  67. package/src/__tests__/nullable-signal-attr.test.ts +45 -0
  68. package/src/__tests__/rename-free-identifiers.test.ts +26 -0
  69. package/src/__tests__/template-name-collisions.test.ts +81 -0
  70. package/src/adapters/array-method.ts +193 -0
  71. package/src/adapters/attr-plan.ts +200 -0
  72. package/src/adapters/boolean-result.ts +208 -12
  73. package/src/adapters/callback-method.ts +301 -0
  74. package/src/adapters/component-props.ts +144 -0
  75. package/src/adapters/component-tree.ts +118 -0
  76. package/src/adapters/filter-capture-collisions.ts +29 -0
  77. package/src/adapters/literal-value.ts +36 -0
  78. package/src/adapters/loop-plan.ts +88 -0
  79. package/src/adapters/parsed-expr-emitter.ts +18 -0
  80. package/src/adapters/prop-classes.ts +73 -0
  81. package/src/adapters/template-name-collisions.ts +120 -0
  82. package/src/analyzer-context.ts +15 -1
  83. package/src/expression-parser.ts +569 -374
  84. package/src/index.ts +58 -3
  85. package/src/ir-to-client-js/collect-elements.ts +11 -7
  86. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +31 -10
  87. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +12 -5
  88. package/src/ir-to-client-js/control-flow/plan/build-reactive-effects.ts +2 -2
  89. package/src/ir-to-client-js/control-flow/shared.ts +4 -1
  90. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +9 -7
  91. package/src/ir-to-client-js/html-template.ts +13 -7
  92. package/src/ir-to-client-js/index.ts +7 -2
  93. package/src/ir-to-client-js/utils.ts +81 -7
  94. package/src/jsx-to-ir.ts +1328 -991
  95. package/src/nullable-signal-attr.ts +116 -6
  96. package/src/scope/binding-scope.ts +19 -0
  97. package/src/types.ts +7 -0
@@ -1,10 +1,26 @@
1
1
  /**
2
- * Backend-neutral boolean-result classification shared by the adapters whose
3
- * host language has no boolean type (Mojolicious, Xslate: Perl renders a
4
- * comparison as `''` / `1` and the literal `false` as `0`). Both adapters
5
- * route a boolean-shaped attribute value through their `bool_str` runtime
6
- * helper; this module decides which `ParsedExpr` shapes are boolean-shaped
7
- * and rewrites a ternary that only PARTLY is (#3349).
2
+ * Backend-neutral boolean-result classification shared by every DSL
3
+ * template adapter (Blade, ERB, Jinja, MiniJinja, Mojolicious, Pebble, Twig,
4
+ * Xslate; #3475 lifted the per-adapter copies here). It decides which
5
+ * `ParsedExpr` shapes evaluate to a JS boolean, rewrites a ternary that only
6
+ * PARTLY does (#3349), and names the ARIA attributes whose binding is
7
+ * boolean by definition. The adapters use it for two decisions:
8
+ *
9
+ * 1. **Stringification.** A boolean-shaped attribute / text binding is routed
10
+ * through the runtime's `bool_str` helper so it serialises as JS
11
+ * `String(boolean)` ("true" / "false"). No host language gets this for
12
+ * free: Perl renders a comparison as `''` / `1` and `false` as `0`;
13
+ * Python's `str(True)` is `"True"`; PHP's `(string) true` is `"1"` and
14
+ * `(string) false` is `""`; Java's `Boolean.toString()` happens to match,
15
+ * but Pebble still routes explicitly so `bf.string` handles every JS value
16
+ * shape the same way.
17
+ * 2. **Condition-position truthiness** (Blade, Jinja, MiniJinja, Pebble,
18
+ * Twig). A condition that is already boolean-shaped is emitted as is;
19
+ * anything else is wrapped in the runtime's JS-faithful `truthy` before it
20
+ * becomes an `if` / ternary test, because those hosts disagree with JS on
21
+ * empty containers (`[]` / `{}` are JS-truthy, falsy in Python, PHP and
22
+ * Pebble) and PHP also on the string `'0'`. Perl never needed this: an
23
+ * array / hash reference is always true there.
8
24
  *
9
25
  * Detected boolean-result shapes:
10
26
  * - `binary` with a comparison operator (`<`, `>`, `<=`, `>=`, `==`,
@@ -12,10 +28,18 @@
12
28
  * - `unary` with logical `!`
13
29
  * - `literal` with `literalType: 'boolean'`
14
30
  * - `logical` (`&&` / `||` / `??`) when both sides are boolean-result
31
+ * (`x > 0 && y < 10`, not `x() || 'fallback'`)
15
32
  * - `conditional` (`?:`) when both branches are boolean-result
33
+ * - with a caller's `isBooleanName`, a getter call, `props.X` or bare
34
+ * name declared `boolean`
35
+ *
36
+ * Anything else is not boolean-result, including a bare identifier
37
+ * (`accepted`) or call (`accepted()`) without a witness: its type is not
38
+ * recoverable from source text.
16
39
  */
17
40
 
18
- import type { ParsedExpr } from '../expression-parser.ts'
41
+ import { parseExpression, type ParsedExpr } from '../expression-parser.ts'
42
+ import type { IRMetadata, TypeInfo } from '../types.ts'
19
43
 
20
44
  const COMPARISON_OPS = new Set([
21
45
  '<',
@@ -28,8 +52,18 @@ const COMPARISON_OPS = new Set([
28
52
  '!==',
29
53
  ])
30
54
 
31
- /** Whether `node` structurally evaluates to a JS boolean. */
32
- export function isBooleanResultParsed(node: ParsedExpr): boolean {
55
+ /**
56
+ * Whether `node` evaluates to a JS boolean: structurally, or, when the
57
+ * caller passes `isBooleanName`, through a leaf declared `boolean` — a
58
+ * zero-arg getter call (`on()`), `props.on`, or a bare name — the same
59
+ * witness shape `isStringTypedOperand` takes for strings. A logical
60
+ * expression mixing a boolean prop with a comparison (`props.on &&
61
+ * !props.off`) then classifies as boolean (#3443).
62
+ */
63
+ export function isBooleanResultParsed(
64
+ node: ParsedExpr,
65
+ isBooleanName?: (name: string, componentProperty?: boolean) => boolean,
66
+ ): boolean {
33
67
  switch (node.kind) {
34
68
  case 'literal':
35
69
  return node.literalType === 'boolean'
@@ -41,14 +75,21 @@ export function isBooleanResultParsed(node: ParsedExpr): boolean {
41
75
  // `x > 0 && y < 10` is boolean; `x() || 'fallback'` is not.
42
76
  // Only both-sides-boolean qualifies.
43
77
  return (
44
- isBooleanResultParsed(node.left) && isBooleanResultParsed(node.right)
78
+ isBooleanResultParsed(node.left, isBooleanName) && isBooleanResultParsed(node.right, isBooleanName)
45
79
  )
46
80
  case 'conditional':
47
81
  // `cond ? bool : bool` is boolean; `cond ? 'a' : 'b'` is not.
48
82
  return (
49
- isBooleanResultParsed(node.consequent) &&
50
- isBooleanResultParsed(node.alternate)
83
+ isBooleanResultParsed(node.consequent, isBooleanName) &&
84
+ isBooleanResultParsed(node.alternate, isBooleanName)
51
85
  )
86
+ case 'call':
87
+ return !!isBooleanName && node.callee.kind === 'identifier' && node.args.length === 0 && isBooleanName(node.callee.name)
88
+ case 'member':
89
+ return !!isBooleanName && !node.computed && node.object.kind === 'identifier' && node.object.name === 'props' &&
90
+ isBooleanName(node.property, true)
91
+ case 'identifier':
92
+ return !!isBooleanName && isBooleanName(node.name)
52
93
  default:
53
94
  return false
54
95
  }
@@ -87,3 +128,158 @@ function stringifyBooleanBranch(branch: ParsedExpr): ParsedExpr {
87
128
  }
88
129
  }
89
130
 
131
+
132
+ /**
133
+ * Names whose value is always a JS boolean, for {@link isBooleanResultParsed}'s
134
+ * `isBooleanName` (#3443):
135
+ *
136
+ * - `names`, read as a bare identifier or getter call: signals and memos
137
+ * typed `boolean` (or, untyped, seeded with a boolean literal), local
138
+ * constants typed or seeded so, and — only when the props are
139
+ * destructured — the `boolean` props. A local constant of another type
140
+ * shadows a same-named prop: with a props object (`props.enabled`) a bare
141
+ * `enabled` is never the prop.
142
+ * - `props`, read as `props.X`: the `boolean` props by their source key.
143
+ *
144
+ * A prop counts only when it can't be `undefined` (required, or carrying a
145
+ * default proven boolean); an omitted one stringifies as `undefined`, not
146
+ * `false`, and so does one defaulted to `undefined` or any other non-boolean
147
+ * expression. A loop
148
+ * or callback binding of the same name shadows a bare name, which the
149
+ * caller's scope decides.
150
+ */
151
+ export function collectBooleanValueNames(
152
+ metadata: Pick<IRMetadata, 'signals' | 'memos' | 'propsParams' | 'localConstants' | 'propsObjectName'>,
153
+ ): { names: Set<string>; props: Set<string> } {
154
+ const isBoolean = (type: TypeInfo | null | undefined): boolean =>
155
+ type?.kind === 'primitive' && type.primitive === 'boolean'
156
+ const isBooleanSeed = (type: TypeInfo | null | undefined, seed: string | undefined): boolean => {
157
+ const text = seed?.trim()
158
+ return isBoolean(type) || ((!type || type.kind === 'unknown') && (text === 'true' || text === 'false'))
159
+ }
160
+ const names = new Set<string>()
161
+ const props = new Set<string>()
162
+ for (const signal of metadata.signals) {
163
+ if (isBooleanSeed(signal.type, signal.initialValue)) names.add(signal.getter)
164
+ }
165
+ for (const memo of metadata.memos ?? []) {
166
+ if (isBoolean(memo.type)) names.add(memo.name)
167
+ }
168
+ // A destructure default sees only the bindings before it, so one that
169
+ // reads an earlier proven-boolean param (`{ off = false, on = off }`) is
170
+ // boolean too.
171
+ const provenParams = new Set<string>()
172
+ for (const param of metadata.propsParams) {
173
+ if (!isBoolean(param.type)) continue
174
+ if (param.optional && !(param.parsed && isBooleanResultParsed(param.parsed, (n, member) => !member && provenParams.has(n)))) continue
175
+ provenParams.add(param.name)
176
+ props.add(param.sourceName ?? param.name)
177
+ if (!metadata.propsObjectName) names.add(param.name)
178
+ }
179
+ // A body destructure of a boolean prop (`const { on } = props` →
180
+ // `props.on`), or one defaulted to a boolean (`const { on = false } =
181
+ // props` → `props.on ?? false`), is boolean whatever the prop's
182
+ // optionality: the default covers the absent case.
183
+ const propsObject = metadata.propsObjectName
184
+ const booleanTyped = new Set(
185
+ metadata.propsParams.filter(p => isBoolean(p.type)).map(p => p.sourceName ?? p.name),
186
+ )
187
+ const readsBooleanProp = (e: ParsedExpr | undefined): boolean => {
188
+ if (!e) return false
189
+ if (e.kind === 'member') {
190
+ return !e.computed && !!propsObject && e.object.kind === 'identifier' && e.object.name === propsObject &&
191
+ props.has(e.property)
192
+ }
193
+ if (e.kind === 'logical' && (e.op === '??' || e.op === '||')) {
194
+ const left = e.left
195
+ return left.kind === 'member' && !left.computed && !!propsObject && left.object.kind === 'identifier' &&
196
+ left.object.name === propsObject && booleanTyped.has(left.property) &&
197
+ e.right.kind === 'literal' && e.right.literalType === 'boolean'
198
+ }
199
+ return false
200
+ }
201
+ for (const constant of metadata.localConstants ?? []) {
202
+ if (readsBooleanProp(constant.parsed) || isBooleanSeed(constant.type ?? undefined, constant.value)) names.add(constant.name)
203
+ else names.delete(constant.name)
204
+ }
205
+ return { names, props }
206
+ }
207
+
208
+ /**
209
+ * {@link isBooleanResultParsed} over expression source text: parses `expr`
210
+ * and classifies the tree structurally (no `isBooleanName` witness). An
211
+ * unparseable expression is not boolean-result.
212
+ */
213
+ export function isBooleanResultExpr(expr: string): boolean {
214
+ const parsed = parseExpression(expr.trim())
215
+ if (!parsed) return false
216
+ return isBooleanResultParsed(parsed)
217
+ }
218
+
219
+ /**
220
+ * True when `expr`'s top-level shape is an explicit one-argument JS
221
+ * `String(x)` call (the `EVAL_BUILTIN_IDENTS` builtin the compiler
222
+ * recognizes structurally; each DSL adapter lowers it to its runtime's
223
+ * `string` helper).
224
+ *
225
+ * Guards the {@link isAriaBooleanAttr}-driven `bool_str` override in the DSL
226
+ * adapters' attribute emitters: an author who wrote `String(...)` has opted
227
+ * into JS `String()` semantics, and `bool_str` over that already-stringified
228
+ * value is a truthiness test of a string (`"false"` is a non-empty, truthy
229
+ * string in Python, Ruby, PHP and Java), so it must not run on top.
230
+ */
231
+ export function isExplicitStringCall(expr: string): boolean {
232
+ const parsed = parseExpression(expr.trim())
233
+ return (
234
+ !!parsed &&
235
+ parsed.kind === 'call' &&
236
+ parsed.callee.kind === 'identifier' &&
237
+ parsed.callee.name === 'String' &&
238
+ parsed.args.length === 1
239
+ )
240
+ }
241
+
242
+ /**
243
+ * ARIA attributes whose spec values are `"true"`, `"false"`, and (for
244
+ * tri-state members) `"mixed"`. When a fixture binds one of these to an
245
+ * arbitrary JS expression (`aria-checked={accepted()}`), the expression's
246
+ * type isn't recoverable from source text, but the attribute name witnesses
247
+ * that the binding is boolean-shaped, so the DSL adapters route it through
248
+ * their `bool_str` runtime helper for the spec-canonical `"true"` /
249
+ * `"false"`.
250
+ *
251
+ * Deliberately conservative: only attributes whose spec value set is exactly
252
+ * `true | false` or `true | false | mixed`. Tokenised ARIA attributes
253
+ * (`aria-current` is `page | step | …`, `aria-sort` is `ascending | …`) are
254
+ * excluded so a string-valued binding is never coerced to `"true"` /
255
+ * `"false"`.
256
+ */
257
+ const ARIA_BOOLEAN_ATTRS = new Set([
258
+ // Strict boolean state (true | false; some allow `undefined` = attribute
259
+ // absent, which the runtime emits as no-attr regardless).
260
+ 'aria-atomic',
261
+ 'aria-busy',
262
+ 'aria-disabled',
263
+ 'aria-hidden',
264
+ 'aria-modal',
265
+ 'aria-multiline',
266
+ 'aria-multiselectable',
267
+ 'aria-readonly',
268
+ 'aria-required',
269
+ // true | false | undefined (absent): selection / disclosure state (#1897:
270
+ // tabs' `aria-selected={props.selected ?? false}` rendered Perl's `1` /
271
+ // `0` without this).
272
+ 'aria-selected',
273
+ 'aria-expanded',
274
+ // Tri-state (true | false | mixed). `bool_str` only maps truthy / falsy to
275
+ // true / false; a fixture that wants the literal "mixed" binds a
276
+ // string-valued JSX attr (`aria-checked="mixed"`), which lowers through
277
+ // the `literal` emit path and never reaches this set.
278
+ 'aria-checked',
279
+ 'aria-pressed',
280
+ ])
281
+
282
+ /** Whether `name` is one of {@link ARIA_BOOLEAN_ATTRS}. */
283
+ export function isAriaBooleanAttr(name: string): boolean {
284
+ return ARIA_BOOLEAN_ATTRS.has(name)
285
+ }
@@ -0,0 +1,301 @@
1
+ /**
2
+ * The higher-order callback chain shared by the DSL adapters (#3477).
3
+ *
4
+ * `xs.filter(x => …)`, `xs.toSorted((a, b) => …)`, `xs.reduce((acc, x) => …,
5
+ * init)` and the rest of {@link CALLBACK_METHODS} lower the same way on every
6
+ * DSL backend: the runtime evaluator first (the callback body travels as
7
+ * serialized `ParsedExpr` JSON, see `serializeParsedExpr`), then a structured
8
+ * fallback (`.sort` only, the `{keys: …}` descriptor), then the adapter's own
9
+ * native predicate form where it has one (Kolon lambdas, Ruby blocks, Perl
10
+ * `grep`), and otherwise BF101. {@link lowerCallbackMethod} makes those
11
+ * decisions once and returns them as a plan; an adapter only spells the
12
+ * result through {@link CallbackEvalSpelling}.
13
+ *
14
+ * A callback that reads its index or array parameter never gets here: the
15
+ * support gate refuses it (`unboundCallbackParamRead`), because no DSL
16
+ * runtime binds those.
17
+ */
18
+
19
+ import {
20
+ freeVarsInBody,
21
+ hasOpaqueCall,
22
+ readsNestedCallbackIndex,
23
+ serializeParsedExpr,
24
+ sortComparatorFromArrow,
25
+ type ParsedExpr,
26
+ type SortComparator,
27
+ } from '../expression-parser.ts'
28
+
29
+ type Arrow = Extract<ParsedExpr, { kind: 'arrow' }>
30
+
31
+ /** The predicate members of `CALLBACK_METHODS`. */
32
+ export type PredicateMethod =
33
+ | 'filter'
34
+ | 'every'
35
+ | 'some'
36
+ | 'find'
37
+ | 'findIndex'
38
+ | 'findLast'
39
+ | 'findLastIndex'
40
+
41
+ const PREDICATE_EVAL: Readonly<Record<PredicateMethod, { helper: CallbackEvalHelper; forward?: boolean }>> = {
42
+ filter: { helper: 'filter_eval' },
43
+ every: { helper: 'every_eval' },
44
+ some: { helper: 'some_eval' },
45
+ find: { helper: 'find_eval', forward: true },
46
+ findLast: { helper: 'find_eval', forward: false },
47
+ findIndex: { helper: 'find_index_eval', forward: true },
48
+ findLastIndex: { helper: 'find_index_eval', forward: false },
49
+ }
50
+
51
+ /** Whether `method` is one of the {@link PredicateMethod}s. */
52
+ export function isPredicateMethod(method: string): method is PredicateMethod {
53
+ return Object.hasOwn(PREDICATE_EVAL, method)
54
+ }
55
+
56
+ /** The runtime evaluator helpers, by id. Every DSL runtime spells them the same. */
57
+ export type CallbackEvalHelper =
58
+ | 'sort_eval'
59
+ | 'reduce_eval'
60
+ | 'filter_eval'
61
+ | 'every_eval'
62
+ | 'some_eval'
63
+ | 'find_eval'
64
+ | 'find_index_eval'
65
+ | 'flat_map_eval'
66
+ | 'map_eval'
67
+
68
+ /** An evaluator-call operand after the receiver and before the env. */
69
+ export type CallbackEvalOperand =
70
+ | { kind: 'string'; value: string }
71
+ /** A number literal's source text. */
72
+ | { kind: 'number'; text: string }
73
+ | { kind: 'boolean'; value: boolean }
74
+
75
+ /**
76
+ * An evaluator call: `helper(recv, ...operands, env)`. The operands carry the
77
+ * serialized body, the callback's param names and the per-helper extras (a
78
+ * reduce's initial value and direction, a find's direction). `captured` are
79
+ * the body's free names; the env maps each to its SSR value.
80
+ */
81
+ export interface CallbackEvalPlan {
82
+ kind: 'eval'
83
+ helper: CallbackEvalHelper
84
+ operands: CallbackEvalOperand[]
85
+ captured: string[]
86
+ }
87
+
88
+ /** A lowered callback method call, as data. */
89
+ export type CallbackPlan =
90
+ | CallbackEvalPlan
91
+ /** A comparator the evaluator cannot model but the `{keys: …}` descriptor can. */
92
+ | { kind: 'structured-sort'; comparator: SortComparator }
93
+ /** A predicate for the adapter's own native form (see `nativePredicate`). */
94
+ | { kind: 'native-predicate'; method: PredicateMethod; param: string; predicate: ParsedExpr }
95
+ | { kind: 'refuse'; message: string; suggestion: string }
96
+ /** A method outside `CALLBACK_METHODS`; unreachable, as the parser recognises only those. */
97
+ | { kind: 'receiver' }
98
+
99
+ export interface CallbackLoweringOptions {
100
+ /** The display name BF101 uses: "the Jinja adapter". */
101
+ adapterName: string
102
+ /**
103
+ * The adapter lowers a predicate the evaluator cannot model to a native
104
+ * form (Xslate, ERB, Mojolicious). Such an adapter also takes the
105
+ * identity filter (`xs.filter(x => x)`) natively without trying the
106
+ * evaluator.
107
+ */
108
+ nativePredicate?: boolean
109
+ }
110
+
111
+ /** Lower `<recv>.<method>(arrow, ...restArgs)`. */
112
+ export function lowerCallbackMethod(
113
+ method: string,
114
+ arrow: Arrow,
115
+ restArgs: readonly ParsedExpr[],
116
+ options: CallbackLoweringOptions,
117
+ ): CallbackPlan {
118
+ const { adapterName } = options
119
+ const { body, params } = arrow
120
+ if (isPredicateMethod(method)) return lowerPredicate(method, arrow, options)
121
+ if (method === 'sort' || method === 'toSorted') {
122
+ const plan = sortEvalPlan(body, params)
123
+ if (plan) return plan
124
+ const comparator = sortComparatorFromArrow(arrow)
125
+ if (comparator) return { kind: 'structured-sort', comparator }
126
+ return sortRefusal(method, adapterName)
127
+ }
128
+ if (method === 'reduce' || method === 'reduceRight') {
129
+ const init = restArgs[0]
130
+ const plan = init ? reduceEvalPlan(body, params, init, method === 'reduceRight' ? 'right' : 'left') : null
131
+ return (
132
+ plan ?? {
133
+ kind: 'refuse',
134
+ message: `'.${method}(...)' is outside the ${adapterName} adapter's evaluable surface (needs a literal initial value and an evaluable reducer body)`,
135
+ suggestion: `Pre-compute the reduced value, or move this position to a '/* @client */' boundary.`,
136
+ }
137
+ )
138
+ }
139
+ if (method === 'flatMap' || method === 'map') {
140
+ const plan = projectionEvalPlan(method === 'map' ? 'map_eval' : 'flat_map_eval', body, params)
141
+ return (
142
+ plan ?? {
143
+ kind: 'refuse',
144
+ message: `'.${method}(...)' projection is outside the ${adapterName} adapter's evaluable surface`,
145
+ suggestion: `Pre-compute the projected array, or move this position to a '/* @client */' boundary.`,
146
+ }
147
+ )
148
+ }
149
+ return { kind: 'receiver' }
150
+ }
151
+
152
+ function lowerPredicate(method: PredicateMethod, arrow: Arrow, options: CallbackLoweringOptions): CallbackPlan {
153
+ const param = String(arrow.params[0])
154
+ const native: CallbackPlan = { kind: 'native-predicate', method, param, predicate: arrow.body }
155
+ // A native form lowers an opaque call to a read of its callee, silently, and
156
+ // binds no nested callback's index, so such a predicate takes the
157
+ // evaluator or BF101 on every adapter alike.
158
+ const nativeOk =
159
+ options.nativePredicate === true && !hasOpaqueCall(arrow.body) && !readsNestedCallbackIndex(arrow.body)
160
+ const identity = method === 'filter' && arrow.body.kind === 'identifier' && arrow.body.name === param
161
+ if (nativeOk && identity) return native
162
+ const json = serializeParsedExpr(arrow.body)
163
+ if (json !== null) {
164
+ const { helper, forward } = PREDICATE_EVAL[method]
165
+ const operands: CallbackEvalOperand[] = [
166
+ { kind: 'string', value: json },
167
+ { kind: 'string', value: param },
168
+ ]
169
+ if (forward !== undefined) operands.push({ kind: 'boolean', value: forward })
170
+ return { kind: 'eval', helper, operands, captured: freeVarsInBody(arrow.body, new Set(arrow.params.slice(0, 1))) }
171
+ }
172
+ if (nativeOk) return native
173
+ return {
174
+ kind: 'refuse',
175
+ message: `'.${method}(...)' predicate is outside the ${options.adapterName} adapter's evaluable surface`,
176
+ suggestion: `Rewrite the predicate as a pure expression the evaluator can serialize (no nested method-call callbacks), or move this position to a '/* @client */' boundary.`,
177
+ }
178
+ }
179
+
180
+ /**
181
+ * The evaluator plan for a sort comparator, or `null` when the body is
182
+ * outside the evaluator surface (a `localeCompare` comparator) or the arrow
183
+ * has fewer than the two params a comparator needs. The loop-source sort
184
+ * shares this with `.sort(cmp)` at an expression position.
185
+ */
186
+ export function sortEvalPlan(body: ParsedExpr, params: readonly string[]): CallbackEvalPlan | null {
187
+ const json = serializeParsedExpr(body)
188
+ if (json === null || params.length < 2) return null
189
+ return {
190
+ kind: 'eval',
191
+ helper: 'sort_eval',
192
+ operands: [
193
+ { kind: 'string', value: json },
194
+ { kind: 'string', value: params[0]! },
195
+ { kind: 'string', value: params[1]! },
196
+ ],
197
+ captured: freeVarsInBody(body, new Set(params)),
198
+ }
199
+ }
200
+
201
+ /** The BF101 for a comparator neither the evaluator nor the descriptor can model. */
202
+ export function sortRefusal(method: string, adapterName: string): { kind: 'refuse'; message: string; suggestion: string } {
203
+ return {
204
+ kind: 'refuse',
205
+ message: `'.${method}(...)' comparator is outside the ${adapterName} adapter's evaluable / structured surface`,
206
+ suggestion: `Pre-compute the sorted array, or move this position to a '/* @client */' boundary.`,
207
+ }
208
+ }
209
+
210
+ /**
211
+ * The evaluator plan for a reducer. Only a string or number literal seeds
212
+ * the fold; anything else (and a body outside the evaluator surface, or a
213
+ * reducer without both `acc` and item params) returns `null`.
214
+ */
215
+ function reduceEvalPlan(
216
+ body: ParsedExpr,
217
+ params: readonly string[],
218
+ init: ParsedExpr,
219
+ direction: 'left' | 'right',
220
+ ): CallbackEvalPlan | null {
221
+ const json = serializeParsedExpr(body)
222
+ if (json === null || init.kind !== 'literal' || params.length < 2) return null
223
+ let seed: CallbackEvalOperand
224
+ if (init.literalType === 'string') seed = { kind: 'string', value: String(init.value) }
225
+ else if (init.literalType === 'number') seed = { kind: 'number', text: String(init.value) }
226
+ else return null
227
+ return {
228
+ kind: 'eval',
229
+ helper: 'reduce_eval',
230
+ operands: [
231
+ { kind: 'string', value: json },
232
+ { kind: 'string', value: params[0]! },
233
+ { kind: 'string', value: params[1]! },
234
+ seed,
235
+ { kind: 'string', value: direction },
236
+ ],
237
+ captured: freeVarsInBody(body, new Set(params)),
238
+ }
239
+ }
240
+
241
+ function projectionEvalPlan(
242
+ helper: 'map_eval' | 'flat_map_eval',
243
+ body: ParsedExpr,
244
+ params: readonly string[],
245
+ ): CallbackEvalPlan | null {
246
+ const json = serializeParsedExpr(body)
247
+ if (json === null) return null
248
+ return {
249
+ kind: 'eval',
250
+ helper,
251
+ operands: [
252
+ { kind: 'string', value: json },
253
+ { kind: 'string', value: String(params[0]) },
254
+ ],
255
+ captured: freeVarsInBody(body, new Set(params.slice(0, 1))),
256
+ }
257
+ }
258
+
259
+ /** How one DSL backend spells an evaluator call. */
260
+ export interface CallbackEvalSpelling {
261
+ /** `helper(operands)`: `bf.sort_eval(…)`, `$bf->sort_eval(…)`, `bf->sort_eval(…)`. */
262
+ call(helper: CallbackEvalHelper, operands: readonly string[]): string
263
+ /** A single-quoted string literal, escaped for the backend. */
264
+ string(value: string): string
265
+ /** `true` / `false`, or Perl's `1` / `0`. */
266
+ boolean(value: boolean): string
267
+ /** The env literal mapping each captured name to its SSR value, `{}` when empty. */
268
+ env(entries: ReadonlyArray<readonly [name: string, value: string]>): string
269
+ }
270
+
271
+ /**
272
+ * Emit an evaluator plan. `recv` is the already-emitted receiver; `emit`
273
+ * renders each captured name's SSR value, after the receiver.
274
+ */
275
+ export function emitCallbackEval(
276
+ plan: CallbackEvalPlan,
277
+ recv: string,
278
+ emit: (e: ParsedExpr) => string,
279
+ spelling: CallbackEvalSpelling,
280
+ ): string {
281
+ const operands = [recv]
282
+ for (const operand of plan.operands) {
283
+ if (operand.kind === 'string') operands.push(spelling.string(operand.value))
284
+ else if (operand.kind === 'number') operands.push(operand.text)
285
+ else operands.push(spelling.boolean(operand.value))
286
+ }
287
+ const env = plan.captured.map((name) => [name, emit({ kind: 'identifier', name })] as const)
288
+ operands.push(spelling.env(env))
289
+ return spelling.call(plan.helper, operands)
290
+ }
291
+
292
+ /**
293
+ * The BF101 for a callback method nested inside a filter predicate, which a
294
+ * predicate emitter has no scalar form for.
295
+ */
296
+ export function nestedCallbackRefusal(method: string, adapterName: string): { message: string; suggestion: string } {
297
+ return {
298
+ message: `Filter predicate contains a nested '.${method}(...)' callback, which has no ${adapterName} scalar form`,
299
+ suggestion: `Rewrite the predicate without a nested callback method, or add /* @client */ for client-only evaluation (no SSR).`,
300
+ }
301
+ }