@barefootjs/jsx 0.40.1 → 0.41.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 (211) hide show
  1. package/dist/adapters/boolean-result.d.ts +32 -10
  2. package/dist/adapters/boolean-result.d.ts.map +1 -1
  3. package/dist/adapters/brace-delimiter-text.d.ts +18 -0
  4. package/dist/adapters/brace-delimiter-text.d.ts.map +1 -0
  5. package/dist/adapters/callback-method.d.ts +45 -5
  6. package/dist/adapters/callback-method.d.ts.map +1 -1
  7. package/dist/adapters/component-props.d.ts +3 -4
  8. package/dist/adapters/component-props.d.ts.map +1 -1
  9. package/dist/adapters/computed-const.d.ts +11 -1
  10. package/dist/adapters/computed-const.d.ts.map +1 -1
  11. package/dist/adapters/dsl-template-adapter.d.ts +24 -12
  12. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  13. package/dist/adapters/loop-bound-names.d.ts +9 -1
  14. package/dist/adapters/loop-bound-names.d.ts.map +1 -1
  15. package/dist/adapters/loop-row-type.d.ts +59 -0
  16. package/dist/adapters/loop-row-type.d.ts.map +1 -0
  17. package/dist/adapters/nil-reading.d.ts +63 -0
  18. package/dist/adapters/nil-reading.d.ts.map +1 -0
  19. package/dist/adapters/non-primitive-equality.d.ts +33 -0
  20. package/dist/adapters/non-primitive-equality.d.ts.map +1 -0
  21. package/dist/adapters/number-value.d.ts +5 -3
  22. package/dist/adapters/number-value.d.ts.map +1 -1
  23. package/dist/adapters/operand-typing.d.ts +126 -0
  24. package/dist/adapters/operand-typing.d.ts.map +1 -0
  25. package/dist/adapters/parsed-expr-emitter.d.ts +80 -12
  26. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  27. package/dist/adapters/primitive-plan.d.ts +320 -0
  28. package/dist/adapters/primitive-plan.d.ts.map +1 -0
  29. package/dist/adapters/prop-classes.d.ts +5 -0
  30. package/dist/adapters/prop-classes.d.ts.map +1 -1
  31. package/dist/analyzer-context.d.ts +4 -0
  32. package/dist/analyzer-context.d.ts.map +1 -1
  33. package/dist/analyzer.d.ts.map +1 -1
  34. package/dist/augment-inherited-props.d.ts +63 -8
  35. package/dist/augment-inherited-props.d.ts.map +1 -1
  36. package/dist/compiler.d.ts.map +1 -1
  37. package/dist/event-handler-name.d.ts +12 -0
  38. package/dist/event-handler-name.d.ts.map +1 -1
  39. package/dist/expression-parser.d.ts +8 -0
  40. package/dist/expression-parser.d.ts.map +1 -1
  41. package/dist/index.d.ts +20 -11
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +4903 -2311
  44. package/dist/ir-to-client-js/build-references.d.ts.map +1 -1
  45. package/dist/ir-to-client-js/child-props-object.d.ts +106 -0
  46. package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -0
  47. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  49. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  50. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  51. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts +4 -2
  52. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts.map +1 -1
  53. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  54. package/dist/ir-to-client-js/imports.d.ts +2 -2
  55. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  56. package/dist/ir-to-client-js/index.d.ts +2 -6
  57. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  58. package/dist/ir-to-client-js/phases/props-extraction.d.ts +3 -3
  59. package/dist/ir-to-client-js/plan/build-declaration-emit.d.ts.map +1 -1
  60. package/dist/ir-to-client-js/plan/build-static-array-child-init.d.ts.map +1 -1
  61. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +30 -18
  62. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  63. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  64. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +3 -1
  65. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  66. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +3 -2
  67. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  68. package/dist/jsx-to-ir.d.ts +1 -0
  69. package/dist/jsx-to-ir.d.ts.map +1 -1
  70. package/dist/nullable-signal-attr.d.ts +51 -34
  71. package/dist/nullable-signal-attr.d.ts.map +1 -1
  72. package/dist/prop-rewrite.d.ts +7 -0
  73. package/dist/prop-rewrite.d.ts.map +1 -1
  74. package/dist/props-binding.d.ts +58 -13
  75. package/dist/props-binding.d.ts.map +1 -1
  76. package/dist/props-object-whole-read.d.ts +15 -0
  77. package/dist/props-object-whole-read.d.ts.map +1 -0
  78. package/dist/rich-type-refusal.d.ts.map +1 -1
  79. package/dist/scope/binding-scope.d.ts +85 -10
  80. package/dist/scope/binding-scope.d.ts.map +1 -1
  81. package/dist/scope/lexical-scope-walk.d.ts +3 -2
  82. package/dist/scope/lexical-scope-walk.d.ts.map +1 -1
  83. package/dist/scope/root-prop-alias.d.ts +10 -7
  84. package/dist/scope/root-prop-alias.d.ts.map +1 -1
  85. package/dist/ssr-defaults.d.ts +39 -3
  86. package/dist/ssr-defaults.d.ts.map +1 -1
  87. package/dist/strip-types.d.ts +13 -0
  88. package/dist/strip-types.d.ts.map +1 -1
  89. package/dist/template-position-walk.d.ts +21 -3
  90. package/dist/template-position-walk.d.ts.map +1 -1
  91. package/dist/types.d.ts +90 -0
  92. package/dist/types.d.ts.map +1 -1
  93. package/package.json +2 -2
  94. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +9 -9
  95. package/src/__tests__/binding-scope.test.ts +89 -1
  96. package/src/__tests__/body-destructure-props-object-alias.test.ts +123 -0
  97. package/src/__tests__/body-destructured-prop-default-arrow.test.ts +2 -2
  98. package/src/__tests__/body-destructured-props-live.test.ts +5 -5
  99. package/src/__tests__/boolean-result.test.ts +22 -5
  100. package/src/__tests__/brace-delimiter-text.test.ts +26 -0
  101. package/src/__tests__/callback-method.test.ts +62 -2
  102. package/src/__tests__/child-components-in-map.test.ts +1 -1
  103. package/src/__tests__/client-js-generation.test.ts +3 -3
  104. package/src/__tests__/computed-const.test.ts +103 -0
  105. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +7 -7
  106. package/src/__tests__/destructured-props-live.test.ts +1 -1
  107. package/src/__tests__/emit-to-string-call.test.ts +2 -1
  108. package/src/__tests__/hydration-payload-analysis.test.ts +166 -0
  109. package/src/__tests__/issue-2724-prop-alias-loop-not-static.test.ts +7 -7
  110. package/src/__tests__/issue-2754-rest-spread-needs-slot.test.ts +5 -2
  111. package/src/__tests__/issue-2798-static-nested-loop-bindings.test.ts +1 -1
  112. package/src/__tests__/issue-2835-props-type-member-name-collision.test.ts +4 -4
  113. package/src/__tests__/issue-3044-nested-prop-object-array-not-static.test.ts +1 -1
  114. package/src/__tests__/issue-3688-props-spread-child-csr.test.ts +2 -1
  115. package/src/__tests__/issue-3713-props-spread-loop-row.test.ts +65 -0
  116. package/src/__tests__/issue-3861-object-spread-child.test.ts +102 -0
  117. package/src/__tests__/lookup-literal-const.test.ts +9 -3
  118. package/src/__tests__/loop-index-reactivity.test.ts +2 -2
  119. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +1 -1
  120. package/src/__tests__/loop-plan.test.ts +1 -1
  121. package/src/__tests__/loop-row-const-initializer-shadow.test.ts +146 -0
  122. package/src/__tests__/loop-row-type.test.ts +64 -0
  123. package/src/__tests__/lowering-value-position.test.ts +4 -0
  124. package/src/__tests__/memo-body-expr.test.ts +2 -2
  125. package/src/__tests__/module-const-destructure-default.test.ts +156 -0
  126. package/src/__tests__/nested-loop-index-param.test.ts +1 -1
  127. package/src/__tests__/nested-loop-reactive-attrs.test.ts +2 -2
  128. package/src/__tests__/nested-row-shadowing.test.ts +2 -2
  129. package/src/__tests__/nil-reading.test.ts +78 -0
  130. package/src/__tests__/nullable-signal-attr.test.ts +109 -48
  131. package/src/__tests__/primitive-plan.test.ts +494 -0
  132. package/src/__tests__/profile-loop-binding-ids.test.ts +2 -2
  133. package/src/__tests__/profile-nested-binding-ids.test.ts +2 -2
  134. package/src/__tests__/prop-default-undefined-only.test.ts +115 -0
  135. package/src/__tests__/prop-references.test.ts +2 -2
  136. package/src/__tests__/props-destructuring.test.ts +17 -0
  137. package/src/__tests__/props-object-whole-read.test.ts +40 -0
  138. package/src/__tests__/prune-unused-prop-extractions.test.ts +3 -3
  139. package/src/__tests__/reactive-attrs-in-map.test.ts +1 -1
  140. package/src/__tests__/reactive-factory-inlining.test.ts +4 -1
  141. package/src/__tests__/renamed-body-destructure-template.test.ts +7 -7
  142. package/src/__tests__/rest-binding-gaps.test.ts +192 -0
  143. package/src/__tests__/rewrite-destructured-props.test.ts +1 -1
  144. package/src/__tests__/root-prop-alias.test.ts +53 -8
  145. package/src/__tests__/ssr-defaults.test.ts +113 -25
  146. package/src/__tests__/static-loop-csr-materialize.test.ts +2 -2
  147. package/src/__tests__/static-record-literal-array.test.ts +171 -0
  148. package/src/__tests__/string-concat-identifier.test.ts +40 -1
  149. package/src/__tests__/written-binding-substitution.test.ts +8 -8
  150. package/src/adapters/boolean-result.ts +72 -66
  151. package/src/adapters/brace-delimiter-text.ts +25 -0
  152. package/src/adapters/callback-method.ts +159 -27
  153. package/src/adapters/component-props.ts +3 -4
  154. package/src/adapters/computed-const.ts +238 -4
  155. package/src/adapters/dsl-template-adapter.ts +62 -26
  156. package/src/adapters/loop-bound-names.ts +9 -1
  157. package/src/adapters/loop-plan.ts +1 -1
  158. package/src/adapters/loop-row-type.ts +149 -0
  159. package/src/adapters/nil-reading.ts +295 -0
  160. package/src/adapters/non-primitive-equality.ts +92 -0
  161. package/src/adapters/number-value.ts +17 -4
  162. package/src/adapters/operand-typing.ts +522 -0
  163. package/src/adapters/parsed-expr-emitter.ts +183 -19
  164. package/src/adapters/primitive-plan.ts +765 -0
  165. package/src/adapters/prop-classes.ts +16 -3
  166. package/src/analyzer-context.ts +6 -0
  167. package/src/analyzer.ts +532 -26
  168. package/src/augment-inherited-props.ts +108 -10
  169. package/src/compiler.ts +17 -0
  170. package/src/event-handler-name.ts +15 -0
  171. package/src/expression-parser.ts +70 -1
  172. package/src/index.ts +35 -16
  173. package/src/ir-to-client-js/build-references.ts +69 -0
  174. package/src/ir-to-client-js/child-props-object.ts +240 -0
  175. package/src/ir-to-client-js/collect-elements.ts +31 -63
  176. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +8 -1
  177. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +31 -28
  178. package/src/ir-to-client-js/control-flow/shared.ts +20 -22
  179. package/src/ir-to-client-js/control-flow/stringify/claim-plan.ts +5 -3
  180. package/src/ir-to-client-js/control-flow/stringify/inner-loop.ts +2 -2
  181. package/src/ir-to-client-js/control-flow/stringify/lazy-row.ts +1 -1
  182. package/src/ir-to-client-js/control-flow/stringify/loop-child-arm.ts +2 -2
  183. package/src/ir-to-client-js/control-flow/stringify/loop.ts +1 -1
  184. package/src/ir-to-client-js/control-flow/stringify/reactive-effects.ts +3 -3
  185. package/src/ir-to-client-js/html-template.ts +43 -17
  186. package/src/ir-to-client-js/imports.ts +2 -2
  187. package/src/ir-to-client-js/index.ts +53 -11
  188. package/src/ir-to-client-js/phases/props-extraction.ts +11 -7
  189. package/src/ir-to-client-js/plan/build-declaration-emit.ts +40 -7
  190. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +31 -14
  191. package/src/ir-to-client-js/plan/static-array-child-init.ts +27 -18
  192. package/src/ir-to-client-js/prop-handling.ts +22 -3
  193. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +58 -5
  194. package/src/ir-to-client-js/rewrite-destructured-props.ts +31 -1
  195. package/src/ir-to-client-js/stringify/static-array-child-init.ts +26 -10
  196. package/src/jsx-to-ir.ts +459 -37
  197. package/src/nullable-signal-attr.ts +200 -110
  198. package/src/prop-rewrite.ts +30 -6
  199. package/src/props-binding.ts +84 -19
  200. package/src/props-object-whole-read.ts +87 -0
  201. package/src/rich-type-refusal.ts +2 -1
  202. package/src/scope/binding-scope.ts +182 -18
  203. package/src/scope/lexical-scope-walk.ts +4 -3
  204. package/src/scope/root-prop-alias.ts +15 -8
  205. package/src/ssr-defaults.ts +100 -11
  206. package/src/strip-types.ts +31 -3
  207. package/src/template-position-walk.ts +57 -28
  208. package/src/types.ts +87 -0
  209. package/dist/adapters/ambiguous-nil-arithmetic.d.ts +0 -41
  210. package/dist/adapters/ambiguous-nil-arithmetic.d.ts.map +0 -1
  211. package/src/adapters/ambiguous-nil-arithmetic.ts +0 -94
@@ -0,0 +1,765 @@
1
+ /**
2
+ * The JS primitive plan (`spec/js-primitive-semantics.md`, "Decision
3
+ * point"): one pure decision per primitive operation — ToBoolean, ToNumber,
4
+ * `+`, `===`, relational, unary `-`, number literal, nullish, index read —
5
+ * whether a target may spell its native operator (Phase-1 types prove the
6
+ * operands are in a range where native and JS agree, and the target's
7
+ * {@link NativeSafeTable} claims that proof) or must call the runtime
8
+ * helper.
9
+ *
10
+ * `emitParsedExpr` computes the plan for every operator node and hands it to
11
+ * the emitter as the method's last parameter; the emitter only spells it.
12
+ * Step 0 of #3824 fills each adapter's table so that the plans describe
13
+ * today's output; each rollout step narrows a table to what the
14
+ * `primitives/` vectors pin and makes the emitters spell the plan.
15
+ */
16
+
17
+ import type { ParsedExpr } from '../expression-parser.ts'
18
+ import { PROPS_OBJECT_IDENTIFIER, type BindingScope } from '../scope/binding-scope.ts'
19
+ import {
20
+ UNKNOWN_FACTS,
21
+ factsOf,
22
+ isExactly,
23
+ isNeverNil,
24
+ nilFacts,
25
+ provenPrimitive,
26
+ unionFacts,
27
+ withoutNil,
28
+ type OperandFacts,
29
+ type OperandType,
30
+ type OperandTyping,
31
+ type ScopedOperandTyping,
32
+ } from './operand-typing.ts'
33
+
34
+ export type PrimitiveOp =
35
+ | 'to-boolean'
36
+ | 'to-number'
37
+ | 'to-string'
38
+ | 'boolean-value'
39
+ | 'get'
40
+ | 'strict-eq'
41
+ | 'relational'
42
+ | 'plus'
43
+ | 'neg'
44
+ | 'number-literal'
45
+ | 'nullish'
46
+ | 'nil-test'
47
+
48
+ /**
49
+ * What Phase 1 proved about the operands of one operation.
50
+ *
51
+ * `unproven` is not in the design note's sketch: it is the proof of an
52
+ * operation whose operands Phase 1 proves nothing about. No target claims
53
+ * it: every runtime carries JS `undefined` apart from `null`
54
+ * (`spec/js-undefined-value.md`), so an unproven operand may be `UNDEF`,
55
+ * which only the runtime's helper reads exactly.
56
+ */
57
+ export type Proof =
58
+ | 'boolean'
59
+ | 'number'
60
+ | 'string'
61
+ | 'number-pair'
62
+ | 'string-pair'
63
+ | 'boolean-pair'
64
+ | 'array-index'
65
+ | 'safe-integer'
66
+ | 'non-nil'
67
+ | 'unproven'
68
+
69
+ /**
70
+ * The (op, proof) pairs a target's native operators are pinned for. Every
71
+ * target's runtime carries JS `undefined` apart from `null`
72
+ * (`spec/js-undefined-value.md`), so the plan needs nothing else about it:
73
+ * an operand Phase 1 does not prove (`either`, unknown, a dynamic `+`) takes
74
+ * the runtime's helper, which reads `null` and `UNDEF` exactly, and
75
+ * `x === null` / `x === undefined` / `x == null` plan as the `is_null` /
76
+ * `is_undefined` / `is_nullish` tests ("Decisions" (3) and (7)).
77
+ */
78
+ export type NativeSafeClaims = Readonly<Partial<Record<PrimitiveOp, readonly Exclude<Proof, 'unproven'>[]>>>
79
+
80
+ /** A target's native-operator claims ({@link NativeSafeClaims}). */
81
+ export type NativeSafeTable = NativeSafeClaims
82
+
83
+ /**
84
+ * The runtime helper a plan names, by its catalogue id
85
+ * (`spec/template-helpers.md`); each runtime keeps its own spelling (Perl's
86
+ * `subtract`, Go's `bf_eq`, PHP's `index` for `get`).
87
+ */
88
+ export type PrimitiveHelper =
89
+ | 'truthy'
90
+ | 'to_number'
91
+ | 'add'
92
+ | 'sub'
93
+ | 'mul'
94
+ | 'div'
95
+ | 'mod'
96
+ | 'plus'
97
+ | 'to_string'
98
+ | 'strict_eq'
99
+ | 'lt'
100
+ | 'le'
101
+ | 'gt'
102
+ | 'ge'
103
+ | 'neg'
104
+ | 'number'
105
+ | 'coalesce'
106
+ | 'get'
107
+ | 'boolean'
108
+ | NilTestHelper
109
+
110
+ /**
111
+ * The nil tests of a target that carries `undefined`
112
+ * (`spec/js-undefined-value.md`, "Decisions" (3)): `x === null`,
113
+ * `x === undefined` and the loose `x == null` / `x == undefined`.
114
+ */
115
+ export type NilTestHelper = 'is_null' | 'is_undefined' | 'is_nullish'
116
+
117
+ export type PrimitivePlan =
118
+ | {
119
+ readonly mode: 'native'
120
+ readonly op: PrimitiveOp
121
+ readonly proof: Proof
122
+ /**
123
+ * A native string `+` (`plus` over the `string` proof): which operand
124
+ * the emitter spells through the runtime's `to_string` before the
125
+ * host's concatenation, `[left, right]`. A proven string operand is
126
+ * concatenated as it is (#3824 step 4).
127
+ */
128
+ readonly stringify?: readonly [boolean, boolean]
129
+ }
130
+ | { readonly mode: 'helper'; readonly op: PrimitiveOp; readonly helper: PrimitiveHelper; readonly proof: Proof }
131
+ /** `===` / `!==` across operands proven of different primitive types. */
132
+ | { readonly mode: 'const'; readonly op: PrimitiveOp; readonly value: boolean }
133
+ /** A BF101 refusal (e.g. a nil reading `either` under a numeric operator). */
134
+ | { readonly mode: 'refuse'; readonly op: PrimitiveOp; readonly reason: string }
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // operandFacts — the single classifier
138
+ // ---------------------------------------------------------------------------
139
+
140
+ const COMPARISON_OPS: ReadonlySet<string> = new Set(['<', '>', '<=', '>=', '==', '===', '!=', '!=='])
141
+ const NUMERIC_BINARY_OPS: ReadonlySet<string> = new Set(['-', '*', '/', '%', '**'])
142
+
143
+ /** `row.id.label` as its root name and field path; null for any other shape. */
144
+ function memberChain(expr: Extract<ParsedExpr, { kind: 'member' }>): { root: string; path: string[] } | null {
145
+ const path: string[] = []
146
+ let current: ParsedExpr = expr
147
+ while (current.kind === 'member' && !current.computed) {
148
+ path.unshift(current.property)
149
+ current = current.object
150
+ }
151
+ return current.kind === 'identifier' ? { root: current.name, path } : null
152
+ }
153
+
154
+ function memberFacts(expr: Extract<ParsedExpr, { kind: 'member' }>, typing: ScopedOperandTyping): OperandFacts {
155
+ // `props['n']` reads the prop `n` as `props.n` does (#3750).
156
+ if (expr.object.kind === 'identifier' && expr.object.name === PROPS_OBJECT_IDENTIFIER) return typing.prop(expr.property)
157
+ if (expr.computed) return UNKNOWN_FACTS
158
+ const chain = memberChain(expr)
159
+ return chain ? typing.path(chain.root, chain.path) : UNKNOWN_FACTS
160
+ }
161
+
162
+ /** The facts of a JS `+`: a string when either side is a proven string, a number when neither can be one. */
163
+ function plusFacts(left: OperandFacts, right: OperandFacts): OperandFacts {
164
+ if (isExactly(left, 'string') || isExactly(right, 'string')) return factsOf('string')
165
+ const numeric = (f: OperandFacts) => [...f.types].every(t => t === 'number' || t === 'boolean' || t === 'nil')
166
+ return numeric(left) && numeric(right) ? factsOf('number') : UNKNOWN_FACTS
167
+ }
168
+
169
+ function binaryFacts(expr: Extract<ParsedExpr, { kind: 'binary' }>, typing: ScopedOperandTyping): OperandFacts {
170
+ if (COMPARISON_OPS.has(expr.op)) return factsOf('boolean')
171
+ if (NUMERIC_BINARY_OPS.has(expr.op)) return factsOf('number')
172
+ if (expr.op === '+') return plusFacts(operandFacts(expr.left, typing), operandFacts(expr.right, typing))
173
+ return UNKNOWN_FACTS
174
+ }
175
+
176
+ function unaryFacts(op: string): OperandFacts {
177
+ if (op === '!') return factsOf('boolean')
178
+ return op === '-' || op === '+' ? factsOf('number') : UNKNOWN_FACTS
179
+ }
180
+
181
+ function logicalFacts(expr: Extract<ParsedExpr, { kind: 'logical' }>, typing: ScopedOperandTyping): OperandFacts {
182
+ const left = operandFacts(expr.left, typing)
183
+ const right = operandFacts(expr.right, typing)
184
+ // `l ?? r` yields `l` only when it is not nil.
185
+ return unionFacts(expr.op === '??' ? withoutNil(left) : left, right)
186
+ }
187
+
188
+ function literalFacts(expr: Extract<ParsedExpr, { kind: 'literal' }>): OperandFacts {
189
+ return expr.literalType === 'null' ? nilFacts('null') : factsOf(expr.literalType)
190
+ }
191
+
192
+ function callFacts(expr: Extract<ParsedExpr, { kind: 'call' }>, typing: ScopedOperandTyping): OperandFacts {
193
+ return expr.callee.kind === 'identifier' && expr.args.length === 0 ? typing.name(expr.callee.name) : UNKNOWN_FACTS
194
+ }
195
+
196
+ const ARRAY_FACTS: OperandFacts = { types: new Set<OperandType>(['object']), array: true }
197
+
198
+ /**
199
+ * What Phase-1 types prove about `expr` at its read in `typing`'s scope: the
200
+ * single classifier the primitive plan, and the legacy predicates that wrap
201
+ * it, read.
202
+ *
203
+ * Step 0 deliberately types no call other than a getter read and no method
204
+ * result (`.includes()` is a boolean in JS, `.join()` a string), so that
205
+ * `isBooleanResultParsed`, which wraps this, stays byte-identical.
206
+ */
207
+ export function operandFacts(expr: ParsedExpr, typing: ScopedOperandTyping): OperandFacts {
208
+ switch (expr.kind) {
209
+ case 'literal':
210
+ return literalFacts(expr)
211
+ case 'identifier':
212
+ return expr.name === 'undefined' && !typing.scope.isBound('undefined') ? nilFacts('undefined') : typing.name(expr.name)
213
+ case 'template-literal':
214
+ return factsOf('string')
215
+ case 'call':
216
+ return callFacts(expr, typing)
217
+ case 'member':
218
+ return memberFacts(expr, typing)
219
+ case 'binary':
220
+ return binaryFacts(expr, typing)
221
+ case 'unary':
222
+ return unaryFacts(expr.op)
223
+ case 'logical':
224
+ return logicalFacts(expr, typing)
225
+ case 'conditional':
226
+ return unionFacts(operandFacts(expr.consequent, typing), operandFacts(expr.alternate, typing))
227
+ case 'array-literal':
228
+ return ARRAY_FACTS
229
+ case 'object-literal':
230
+ return factsOf('object')
231
+ default:
232
+ return UNKNOWN_FACTS
233
+ }
234
+ }
235
+
236
+ // ---------------------------------------------------------------------------
237
+ // planPrimitive — the decision
238
+ // ---------------------------------------------------------------------------
239
+
240
+ function decide(op: PrimitiveOp, proof: Proof, target: NativeSafeTable, helper: PrimitiveHelper): PrimitivePlan {
241
+ return claimsNative(op, proof, target) ? { mode: 'native', op, proof } : { mode: 'helper', op, helper, proof }
242
+ }
243
+
244
+ /**
245
+ * Whether `target` spells its native operator for `op` over `proof`. An
246
+ * `unproven` operand is never native: it may be `UNDEF`, which only the
247
+ * runtime's helper reads exactly.
248
+ */
249
+ function claimsNative(op: PrimitiveOp, proof: Proof, target: NativeSafeTable): boolean {
250
+ if (proof === 'unproven') return false
251
+ return target[op]?.includes(proof) ?? false
252
+ }
253
+
254
+ /** A pair proof when both operands are proven the same non-nil primitive. */
255
+ function pairProof(left: OperandFacts, right: OperandFacts): Proof {
256
+ const l = provenPrimitive(left)
257
+ return l !== null && l === provenPrimitive(right) ? (`${l}-pair` as Proof) : 'unproven'
258
+ }
259
+
260
+ const RELATIONAL_HELPERS: Readonly<Record<string, PrimitiveHelper>> = { '<': 'lt', '<=': 'le', '>': 'gt', '>=': 'ge' }
261
+
262
+ function planStrictEq(op: string, left: OperandFacts, right: OperandFacts, target: NativeSafeTable): PrimitivePlan {
263
+ const l = provenPrimitive(left)
264
+ const r = provenPrimitive(right)
265
+ // Operands proven of different primitive types are never `===`.
266
+ if (l !== null && r !== null && l !== r) return { mode: 'const', op: 'strict-eq', value: op === '!==' }
267
+ return decide('strict-eq', pairProof(left, right), target, 'strict_eq')
268
+ }
269
+
270
+ /** The literal `null`, or an unbound `undefined`: the operand of a nullish test. */
271
+ export function isNilLiteralOperand(expr: ParsedExpr, typing?: ScopedOperandTyping): boolean {
272
+ if (expr.kind === 'literal') return expr.literalType === 'null'
273
+ return expr.kind === 'identifier' && expr.name === 'undefined' && !typing?.scope.isBound('undefined')
274
+ }
275
+
276
+ /** A `===` / `!==` / `==` / `!=` with a nil literal on one side: a nullish test, not a strict equality. */
277
+ export function isNullishTest(op: string, left: ParsedExpr, right: ParsedExpr, typing?: ScopedOperandTyping): boolean {
278
+ return (op === '===' || op === '!==' || op === '==' || op === '!=') &&
279
+ (isNilLiteralOperand(left, typing) || isNilLiteralOperand(right, typing))
280
+ }
281
+
282
+ /**
283
+ * The plan of a nullish test (`x === null`, `x !== undefined`, `x == null`;
284
+ * {@link isNullishTest}), `spec/js-undefined-value.md` "Decisions" (7):
285
+ * `===` / `!==` against `null` is the strict `is_null`, against `undefined`
286
+ * the strict `is_undefined`, and the loose `==` / `!=` against either is
287
+ * `is_nullish`; the emitter negates the test for `!==` / `!=`. With a nil
288
+ * literal on both sides, the right one names the test (`null === undefined`
289
+ * is `is_undefined(null)`, `false`).
290
+ */
291
+ function planNilTest(op: string, left: ParsedExpr, right: ParsedExpr, typing: ScopedOperandTyping): PrimitivePlan {
292
+ const nilTest = (helper: NilTestHelper): PrimitivePlan => ({ mode: 'helper', op: 'nil-test', helper, proof: 'unproven' })
293
+ if (op === '==' || op === '!=') return nilTest('is_nullish')
294
+ // `isNullishTest` holds, so when `right` is not a nil literal `left` is.
295
+ const literal = nilTestOperand(left, right, typing) === left ? right : left
296
+ return nilTest(literal.kind === 'literal' ? 'is_null' : 'is_undefined')
297
+ }
298
+
299
+ /**
300
+ * The operand a nil test ({@link planNilTest}) tests: the side that is not
301
+ * the nil literal, `left` when both are (`null === undefined` tests `null`).
302
+ */
303
+ export function nilTestOperand(left: ParsedExpr, right: ParsedExpr, typing?: ScopedOperandTyping): ParsedExpr {
304
+ return isNilLiteralOperand(right, typing) ? left : right
305
+ }
306
+
307
+ /**
308
+ * Refuse a nil-test plan ({@link planNilTest}) at an emitter that has no
309
+ * spelling for it (no `nilTest`), instead of letting it fall back to its
310
+ * host nil test, which cannot tell `null` from `undefined`.
311
+ */
312
+ export function refuseUnspelledNilTest(plan: PrimitivePlan | null): void {
313
+ if (plan?.op !== 'nil-test' || plan.mode !== 'helper') return
314
+ throw new Error(
315
+ `[barefootjs] the primitive plan names the \`${plan.helper}\` nil test (a target that carries \`undefined\`), ` +
316
+ 'but this emitter has no spelling for it (spec/js-undefined-value.md)',
317
+ )
318
+ }
319
+
320
+ /** The array element reads whose value is one element of their receiver. */
321
+ const ELEMENT_READ_METHODS: ReadonlySet<string> = new Set(['at', 'find', 'findLast'])
322
+
323
+ /** The receiver of an element read (`a[i]`, `a.at(i)`, `a.find(p)`), or null. */
324
+ function elementReadReceiver(expr: ParsedExpr): ParsedExpr | null {
325
+ if (expr.kind === 'index-access') return expr.object
326
+ if (expr.kind === 'member' && expr.computed) return expr.object
327
+ if (expr.kind === 'array-method' && ELEMENT_READ_METHODS.has(expr.method)) return expr.object
328
+ return null
329
+ }
330
+
331
+ /**
332
+ * Whether `expr` may hold an object or array at its read
333
+ * (`spec/js-primitive-semantics.md`, "Decisions" (4)): its facts admit
334
+ * `object` (an object, array or interface type, an object or array
335
+ * literal), or it is an element read of an array whose declared element
336
+ * type or array-literal seed admits one (`rows().at(0)` over
337
+ * `createSignal([{ id: 1 }])`, typed `unknown[]`). An operand Phase 1
338
+ * proves nothing else about (an untyped row field, a call result) is not
339
+ * refused: the runtime's `strict_eq` compares it. A named type reference
340
+ * (`Row`, `Tone`) counts only when `isObjectTypeName` resolves it to an
341
+ * object shape; by default it does not.
342
+ */
343
+ export function mayHoldObject(
344
+ expr: ParsedExpr,
345
+ typing: ScopedOperandTyping,
346
+ isObjectTypeName: (name: string) => boolean = () => false,
347
+ ): boolean {
348
+ const holdsObject = (facts: OperandFacts): boolean =>
349
+ facts.types.has('object') && (!facts.namedObjects || facts.namedObjects.some(isObjectTypeName))
350
+ if (holdsObject(operandFacts(expr, typing))) return true
351
+ const receiver = elementReadReceiver(expr)
352
+ if (!receiver) return false
353
+ const facts = operandFacts(receiver, typing)
354
+ // `element` alone, not `array`: a nullable or union-typed array
355
+ // (`rows?: Row[]`) keeps its element evidence without being proven an array.
356
+ return facts.element !== undefined && holdsObject(facts.element)
357
+ }
358
+
359
+ /** The BF101 reason of a `===` / `!==` over an operand that may be an object (#3774). */
360
+ export const NON_PRIMITIVE_EQUALITY_REASON = 'non-primitive-strict-equality'
361
+
362
+ /**
363
+ * How an emitter spells a `===` / `!==` under its plan (#3824 step 8):
364
+ *
365
+ * - `native`: the target's own operator for the proven pair (`proof`).
366
+ * - `helper`: the runtime's `strict_eq`, negated for `!==`. A refused plan
367
+ * spells it too: the refusal itself is recorded once per component by
368
+ * `refuseNonPrimitiveStrictEquality`.
369
+ * - `const`: the folded answer for operands proven of different types.
370
+ * - `nullish`: a nullish test (`x === null`) reached without a plan (an
371
+ * emitter method called outside `emitParsedExpr`). Under a plan a nullish
372
+ * test is a nil test, which `emitParsedExpr` hands to the emitter's
373
+ * `nilTest` ({@link refuseUnspelledNilTest} when it has none).
374
+ *
375
+ * Null for any other operator (loose `==` keeps its own lowering). A null
376
+ * plan takes the helper, which is never wrong.
377
+ */
378
+ export type StrictEqSpelling =
379
+ | { readonly kind: 'native'; readonly proof: Proof; readonly negated: boolean }
380
+ | { readonly kind: 'helper'; readonly negated: boolean }
381
+ | { readonly kind: 'const'; readonly value: boolean }
382
+ | { readonly kind: 'nullish' }
383
+
384
+ export function strictEqSpelling(op: string, left: ParsedExpr, right: ParsedExpr, plan: PrimitivePlan | null): StrictEqSpelling | null {
385
+ refuseUnspelledNilTest(plan)
386
+ if (op !== '===' && op !== '!==') return null
387
+ if (isNilLiteralOperand(left) || isNilLiteralOperand(right)) return { kind: 'nullish' }
388
+ const negated = op === '!=='
389
+ if (plan?.op === 'strict-eq' && plan.mode === 'const') return { kind: 'const', value: plan.value }
390
+ if (plan?.op === 'strict-eq' && plan.mode === 'native') return { kind: 'native', proof: plan.proof, negated }
391
+ return { kind: 'helper', negated }
392
+ }
393
+
394
+ /**
395
+ * A binary `+` (#3824 step 4): the host's `+` over two proven non-nil
396
+ * numbers (`add` on a target that does not claim it); the host's
397
+ * concatenation when one operand is a proven non-nil string, with the other
398
+ * through `to_string` unless it is a proven string too; the runtime's JS `+`
399
+ * (`plus`) otherwise. The nil-reading rewrite runs first, so a typed
400
+ * nil-capable operand is already non-nil here.
401
+ */
402
+ function planPlus(left: OperandFacts, right: OperandFacts, target: NativeSafeTable): PrimitivePlan {
403
+ if (isExactly(left, 'number') && isExactly(right, 'number')) return decide('plus', 'number-pair', target, 'add')
404
+ const ls = isExactly(left, 'string')
405
+ const rs = isExactly(right, 'string')
406
+ if (ls || rs) {
407
+ const plan = decide('plus', 'string', target, 'plus')
408
+ return plan.mode === 'native' ? { ...plan, stringify: [!ls, !rs] } : plan
409
+ }
410
+ return decide('plus', 'unproven', target, 'plus')
411
+ }
412
+
413
+ /**
414
+ * How an emitter spells a `+` under its plan (#3824 step 4):
415
+ *
416
+ * - `add`: the host's numeric `+` (`native`), or the runtime's numbers-only
417
+ * `add` helper (`helper`, Perl and Go).
418
+ * - `concat`: the host's string concatenation, each operand whose
419
+ * `stringify` flag is set through the runtime's `to_string`.
420
+ * - `plus`: the runtime's JS `+`.
421
+ *
422
+ * A null plan (an emitter method reached outside `emitParsedExpr`) takes
423
+ * `plus`, which is never wrong.
424
+ */
425
+ export type PlusSpelling =
426
+ | { readonly kind: 'add'; readonly native: boolean }
427
+ | { readonly kind: 'concat'; readonly stringify: readonly [boolean, boolean] }
428
+ | { readonly kind: 'plus' }
429
+
430
+ export function plusSpelling(plan: PrimitivePlan | null): PlusSpelling {
431
+ if (plan?.op !== 'plus') return { kind: 'plus' }
432
+ if (plan.mode === 'native') {
433
+ return plan.proof === 'number-pair' ? { kind: 'add', native: true } : { kind: 'concat', stringify: plan.stringify ?? [true, true] }
434
+ }
435
+ return plan.mode === 'helper' && plan.helper === 'add' ? { kind: 'add', native: false } : { kind: 'plus' }
436
+ }
437
+
438
+ /**
439
+ * The ToString plan of a template-literal part (#3824 step 4): the part
440
+ * itself when it is a proven non-nil string and the target claims the
441
+ * `string` proof for `to-string`, the runtime's `to_string` otherwise. The
442
+ * nil-reading rewrite has already turned a typed nil-capable part into a
443
+ * non-nil one.
444
+ */
445
+ export function planToString(part: ParsedExpr, typing: ScopedOperandTyping, target: NativeSafeTable): PrimitivePlan {
446
+ return decide('to-string', isExactly(operandFacts(part, typing), 'string') ? 'string' : 'unproven', target, 'to_string')
447
+ }
448
+
449
+ /** Whether a ToString plan names the runtime's `to_string`; a null plan does. */
450
+ export function needsToString(plan: PrimitivePlan | null): boolean {
451
+ return !isNativePlan(plan, 'to-string')
452
+ }
453
+
454
+ function planNumericBinary(op: string, left: OperandFacts, right: OperandFacts, target: NativeSafeTable): PrimitivePlan {
455
+ // `/` and `%` have no native spelling on any target (`arithmeticHelper`).
456
+ if (op === '/') return { mode: 'helper', op: 'to-number', helper: 'div', proof: pairProof(left, right) }
457
+ if (op === '%') return { mode: 'helper', op: 'to-number', helper: 'mod', proof: pairProof(left, right) }
458
+ const proof: Proof = isExactly(left, 'number') && isExactly(right, 'number') ? 'number-pair' : 'unproven'
459
+ return decide('to-number', proof, target, op === '-' ? 'sub' : 'mul')
460
+ }
461
+
462
+ function planBinary(expr: Extract<ParsedExpr, { kind: 'binary' }>, typing: ScopedOperandTyping, target: NativeSafeTable): PrimitivePlan | null {
463
+ const { op } = expr
464
+ // `x === null` / `x == null` is a nullish test, not a strict equality.
465
+ if (isNullishTest(op, expr.left, expr.right, typing)) return planNilTest(op, expr.left, expr.right, typing)
466
+ const isPrimitiveOp = op === '===' || op === '!==' || op === '+' || op in RELATIONAL_HELPERS || op === '-' || op === '*' || op === '/' || op === '%'
467
+ if (!isPrimitiveOp) return null
468
+ const left = operandFacts(expr.left, typing)
469
+ const right = operandFacts(expr.right, typing)
470
+ if (op === '===' || op === '!==') {
471
+ if (mayHoldObject(expr.left, typing) || mayHoldObject(expr.right, typing)) {
472
+ return { mode: 'refuse', op: 'strict-eq', reason: NON_PRIMITIVE_EQUALITY_REASON }
473
+ }
474
+ return planStrictEq(op, left, right, target)
475
+ }
476
+ if (op === '+') return planPlus(left, right, target)
477
+ const relational = RELATIONAL_HELPERS[op]
478
+ if (relational) {
479
+ const proof: Proof = isExactly(left, 'number') && isExactly(right, 'number') ? 'number-pair' : 'unproven'
480
+ return decide('relational', proof, target, relational)
481
+ }
482
+ return planNumericBinary(op, left, right, target)
483
+ }
484
+
485
+ /** A test position: ToBoolean of `test`. */
486
+ function planToBoolean(test: ParsedExpr, typing: ScopedOperandTyping, target: NativeSafeTable): PrimitivePlan {
487
+ return decide('to-boolean', isExactly(operandFacts(test, typing), 'boolean') ? 'boolean' : 'unproven', target, 'truthy')
488
+ }
489
+
490
+ /**
491
+ * The ToBoolean plan of a test position whose node `emitParsedExpr` does not
492
+ * plan, because the position, not an operator node, applies the conversion:
493
+ * an `if` condition (a JSX conditional, a conditional return), a `.filter()`
494
+ * / `.every()` / `.some()` predicate body, a loop filter's guard, an
495
+ * attribute's presence test. The `!`, `&&`, `||` and `?:` nodes receive the
496
+ * same plan from the dispatcher.
497
+ */
498
+ export function planTest(test: ParsedExpr, typing: ScopedOperandTyping, target: NativeSafeTable): PrimitivePlan {
499
+ return planToBoolean(test, typing, target)
500
+ }
501
+
502
+ /**
503
+ * Spell a ToBoolean plan over a rendered test: the test itself when the plan
504
+ * is native, `helper(rendered)` otherwise. A null plan (an emitter method
505
+ * reached outside `emitParsedExpr`) takes the helper, which is never wrong.
506
+ */
507
+ export function spellTest(plan: PrimitivePlan | null, rendered: string, helper: (rendered: string) => string): string {
508
+ return plan?.mode === 'native' && plan.op === 'to-boolean' ? rendered : helper(rendered)
509
+ }
510
+
511
+ type NumberLiteral = Extract<ParsedExpr, { kind: 'literal' }> & { value: number }
512
+
513
+ /**
514
+ * A unary `-` over a non-zero number literal, folded into the literal it
515
+ * denotes (`-1.5` is the literal `-1.5`); null for any other node
516
+ * (`spec/js-primitive-semantics.md`, "Unary `-` and number literals"). The
517
+ * fold is the only native-safe unary minus: any other operand can be an
518
+ * integer zero in a host whose integer and float types differ, and the sign
519
+ * of `-0` would be lost, so it takes the `neg` helper. `-0` itself is not
520
+ * folded: a zero operand is exactly that case.
521
+ */
522
+ export function foldNegatedNumberLiteral(expr: ParsedExpr): NumberLiteral | null {
523
+ if (expr.kind !== 'unary' || expr.op !== '-') return null
524
+ const arg = expr.argument
525
+ if (arg.kind !== 'literal' || arg.literalType !== 'number' || typeof arg.value !== 'number' || arg.value === 0) return null
526
+ return { kind: 'literal', value: -arg.value, literalType: 'number', raw: String(-arg.value) }
527
+ }
528
+
529
+ function planUnary(expr: Extract<ParsedExpr, { kind: 'unary' }>, typing: ScopedOperandTyping, target: NativeSafeTable): PrimitivePlan | null {
530
+ if (expr.op === '!') return planToBoolean(expr.argument, typing, target)
531
+ if (expr.op === '-') {
532
+ const folded = foldNegatedNumberLiteral(expr)
533
+ return folded ? planNumberLiteral(folded.value, target) : decide('neg', 'unproven', target, 'neg')
534
+ }
535
+ if (expr.op === '+') {
536
+ // A unary `+` is ToNumber itself, and no target's native `+x` converts a
537
+ // string (Python, Ruby and Java raise; Perl, Go and the PHP engines drop
538
+ // it), so only a proven number is a claimable proof (#3824 step 3).
539
+ return isExactly(operandFacts(expr.argument, typing), 'number')
540
+ ? decide('to-number', 'number', target, 'to_number')
541
+ : { mode: 'helper', op: 'to-number', helper: 'to_number', proof: 'unproven' }
542
+ }
543
+ return null
544
+ }
545
+
546
+ /**
547
+ * The helper a relational plan names for `op` (`<` → `lt`, …), or null when
548
+ * the plan names the native operator (both operands proven non-nil numbers
549
+ * and the target claims `number-pair`; #3824 step 3). A null plan (an
550
+ * emitter method reached outside `emitParsedExpr`) takes the helper, which
551
+ * is never wrong. Null too for an `op` that is not relational.
552
+ */
553
+ export function relationalHelper(op: string, plan: PrimitivePlan | null): PrimitiveHelper | null {
554
+ const helper = RELATIONAL_HELPERS[op]
555
+ if (!helper) return null
556
+ return isNativePlan(plan, 'relational') ? null : helper
557
+ }
558
+
559
+ /**
560
+ * Whether a unary-`+` plan names the native spelling (the operand itself, a
561
+ * proven number); otherwise the emitter spells the runtime's `to_number`
562
+ * (#3824 step 3). A null plan takes the helper.
563
+ */
564
+ export function isNativeToNumber(plan: PrimitivePlan | null): boolean {
565
+ return isNativePlan(plan, 'to-number')
566
+ }
567
+
568
+ function planLogical(expr: Extract<ParsedExpr, { kind: 'logical' }>, typing: ScopedOperandTyping, target: NativeSafeTable): PrimitivePlan {
569
+ if (expr.op !== '??') return planToBoolean(expr.left, typing, target)
570
+ return decide('nullish', isNeverNil(operandFacts(expr.left, typing)) ? 'non-nil' : 'unproven', target, 'coalesce')
571
+ }
572
+
573
+ /** An index read: native only for a proven array read by a proven non-negative integer. */
574
+ function planGet(object: ParsedExpr, key: OperandFacts, typing: ScopedOperandTyping, target: NativeSafeTable): PrimitivePlan {
575
+ const receiver = operandFacts(object, typing)
576
+ const proof: Proof = receiver.array && isNeverNil(receiver) && key.index ? 'array-index' : 'unproven'
577
+ return decide('get', proof, target, 'get')
578
+ }
579
+
580
+ /**
581
+ * Whether `plan` names the native operator of `op`. A null plan (an emitter
582
+ * method reached outside `emitParsedExpr`) is never native: the helper is
583
+ * never wrong.
584
+ */
585
+ export function isNativePlan(plan: PrimitivePlan | null, op: PrimitiveOp): boolean {
586
+ return plan?.mode === 'native' && plan.op === op
587
+ }
588
+
589
+ function planNumberLiteral(value: number, target: NativeSafeTable): PrimitivePlan {
590
+ // `-0` is spelled `neg(0)`: no host parses a negative-zero literal.
591
+ if (Object.is(value, -0)) return { mode: 'helper', op: 'number-literal', helper: 'neg', proof: 'unproven' }
592
+ return decide('number-literal', Number.isSafeInteger(value) ? 'safe-integer' : 'unproven', target, 'number')
593
+ }
594
+
595
+ /**
596
+ * Whether `expr` is a number literal that no target spells as a host literal
597
+ * (anything but a safe integer, so `-0` too): its value comes from the
598
+ * runtime's `number` / `neg` and prints in the host's own notation (Perl
599
+ * `1e-07`, Go `1e+20`) unless the text sink routes it through the runtime's
600
+ * JS `Number::toString`.
601
+ */
602
+ export function isRuntimeNumberLiteral(expr: ParsedExpr): boolean {
603
+ return expr.kind === 'literal' && expr.literalType === 'number' && typeof expr.value === 'number' &&
604
+ (!Number.isSafeInteger(expr.value) || Object.is(expr.value, -0))
605
+ }
606
+
607
+ /** The number-literal claim every target makes: a safe integer is spelled as a host literal. */
608
+ const SAFE_INTEGER_LITERALS: NativeSafeTable = { 'number-literal': ['safe-integer'] }
609
+
610
+ /**
611
+ * How an emitter spells a number literal of `value` under its plan:
612
+ *
613
+ * - `native`: the host literal `text` (a safe integer, `String(value)`).
614
+ * - `parse`: the runtime's `number` helper over the string `text`, the JS
615
+ * spelling `String(value)` (`1e+21`, `1e-7`, `0.1`,
616
+ * `100000000000000000000`), which every runtime's `number` parses, so no
617
+ * target needs an exponent or big-integer literal syntax.
618
+ * - `negative-zero`: the runtime's `neg` helper over `0`.
619
+ *
620
+ * A null plan (an emitter method reached outside `emitParsedExpr`) gets the
621
+ * plan of a target that claims only safe integers natively, which every
622
+ * target's table does.
623
+ */
624
+ export type NumberLiteralSpelling =
625
+ | { readonly kind: 'native'; readonly text: string }
626
+ | { readonly kind: 'parse'; readonly text: string }
627
+ | { readonly kind: 'negative-zero' }
628
+
629
+ export function numberLiteralSpelling(value: number, plan: PrimitivePlan | null): NumberLiteralSpelling {
630
+ const decided = plan?.op === 'number-literal' ? plan : planNumberLiteral(value, SAFE_INTEGER_LITERALS)
631
+ if (decided.mode === 'native') return { kind: 'native', text: String(value) }
632
+ if (decided.mode === 'helper' && decided.helper === 'neg') return { kind: 'negative-zero' }
633
+ return { kind: 'parse', text: String(value) }
634
+ }
635
+
636
+ /**
637
+ * The plan for `node` in `typing`'s scope on a target whose native operators
638
+ * are pinned for `target`'s (op, proof) pairs, or null when `node` is not a
639
+ * primitive operation (a non-number literal, loose `==`, `in`, a
640
+ * non-computed member, …).
641
+ *
642
+ * Planned kinds: `binary` (`===` `!==` `<` `<=` `>` `>=` `+` `-` `*` `/`
643
+ * `%`, and a nullish test with `==` / `!=` too, {@link planNilTest}), `unary` (`!` `-` `+`), `logical` (its left operand's test, or `??`),
644
+ * `conditional` (its test), `index-access`, computed `member` and number
645
+ * `literal`.
646
+ */
647
+ export function planPrimitive(node: ParsedExpr, typing: ScopedOperandTyping, target: NativeSafeTable): PrimitivePlan | null {
648
+ switch (node.kind) {
649
+ case 'binary':
650
+ return planBinary(node, typing, target)
651
+ case 'unary':
652
+ return planUnary(node, typing, target)
653
+ case 'logical':
654
+ return planLogical(node, typing, target)
655
+ case 'conditional':
656
+ return planToBoolean(node.test, typing, target)
657
+ case 'index-access':
658
+ return planGet(node.object, operandFacts(node.index, typing), typing, target)
659
+ case 'member':
660
+ // A literal key is never a proven index (the note: only a loop index binding is).
661
+ return node.computed ? planGet(node.object, UNKNOWN_FACTS, typing, target) : null
662
+ case 'literal':
663
+ return node.literalType === 'number' && typeof node.value === 'number' ? planNumberLiteral(node.value, target) : null
664
+ default:
665
+ return null
666
+ }
667
+ }
668
+
669
+ // ---------------------------------------------------------------------------
670
+ // Boolean values (#3824 step 5)
671
+ // ---------------------------------------------------------------------------
672
+
673
+ /**
674
+ * Whether `node` itself produces a boolean (a comparison, `!`, a boolean
675
+ * literal): the nodes whose host value is not a boolean on a target without
676
+ * a boolean type (Perl holds `1` / `''` / `0`). A read of a name never is: a
677
+ * stored value was materialized where it was stored.
678
+ */
679
+ function producesBoolean(node: ParsedExpr): boolean {
680
+ if (node.kind === 'literal') return node.literalType === 'boolean'
681
+ if (node.kind === 'unary') return node.op === '!'
682
+ return node.kind === 'binary' && COMPARISON_OPS.has(node.op)
683
+ }
684
+
685
+ function collectBooleanValueSites(node: ParsedExpr, target: NativeSafeTable, sites: Map<ParsedExpr, PrimitivePlan>): void {
686
+ if (producesBoolean(node)) {
687
+ sites.set(node, decide('boolean-value', 'boolean', target, 'boolean'))
688
+ return
689
+ }
690
+ switch (node.kind) {
691
+ case 'logical':
692
+ // `l && r` / `l || r` / `l ?? r` yield either operand.
693
+ collectBooleanValueSites(node.left, target, sites)
694
+ collectBooleanValueSites(node.right, target, sites)
695
+ return
696
+ case 'conditional':
697
+ // The test is a test position; only the branches are values.
698
+ collectBooleanValueSites(node.consequent, target, sites)
699
+ collectBooleanValueSites(node.alternate, target, sites)
700
+ return
701
+ case 'array-literal':
702
+ for (const element of node.elements) collectBooleanValueSites(element, target, sites)
703
+ return
704
+ case 'object-literal':
705
+ for (const property of node.properties) if (property.kind === 'prop') collectBooleanValueSites(property.value, target, sites)
706
+ return
707
+ default:
708
+ return
709
+ }
710
+ }
711
+
712
+ /**
713
+ * The boolean-value plan of every node of `expr` whose value leaves the
714
+ * expression when `expr` itself does (`spec/js-primitive-semantics.md`,
715
+ * "Boolean values"): `expr` read as a value — a child prop, a stored signal
716
+ * seed / memo / local, a `JSON.stringify` argument, a rendered value — and,
717
+ * through it, an operand `&&` / `||` / `??` returns, a ternary branch and an
718
+ * array or object literal element. A test (a ternary's test, the operand of
719
+ * `!`, an `if` condition) is not a value: it keeps the target's native
720
+ * truthiness. A target with a boolean type claims `boolean-value` natively
721
+ * and spells nothing; Perl materializes each site with its runtime's
722
+ * `boolean`.
723
+ */
724
+ export function booleanValueSites(expr: ParsedExpr, target: NativeSafeTable): ReadonlyMap<ParsedExpr, PrimitivePlan> {
725
+ const sites = new Map<ParsedExpr, PrimitivePlan>()
726
+ collectBooleanValueSites(expr, target, sites)
727
+ return sites
728
+ }
729
+
730
+ /**
731
+ * How a JSX text child displays its value (`spec/js-primitive-semantics.md`,
732
+ * "ToString and boolean values"): JSX renders nothing for `true`, `false`,
733
+ * `null` and `undefined`.
734
+ *
735
+ * - `empty`: Phase 1 proves the value is a boolean or nil, so the child
736
+ * renders nothing (its markers stay).
737
+ * - `display`: the value may be a boolean among other types, so the runtime's
738
+ * `display` helper blanks a boolean at render time.
739
+ * - `plain`: the value is never a boolean (or Phase 1 proves nothing), so the
740
+ * target's text sink prints it as before.
741
+ */
742
+ export type TextDisplay = 'empty' | 'display' | 'plain'
743
+
744
+ export function planTextDisplay(expr: ParsedExpr, typing: ScopedOperandTyping): TextDisplay {
745
+ const { types } = operandFacts(expr, typing)
746
+ if (types.has('unknown') || !types.has('boolean')) return 'plain'
747
+ return [...types].every(t => t === 'boolean' || t === 'nil') ? 'empty' : 'display'
748
+ }
749
+
750
+ /** The inputs an emitter supplies for the plans it receives (`ParsedExprEmitter.primitives`). */
751
+ export interface PrimitiveInputs {
752
+ /** The operand typing at the emission site (`typing.at(scope)`). */
753
+ typing(): ScopedOperandTyping
754
+ /** The target's native-safe (op, proof) pairs. */
755
+ readonly nativeSafe: NativeSafeTable
756
+ }
757
+
758
+ /**
759
+ * {@link PrimitiveInputs} reading `typing` at `scope`. An emitter that is
760
+ * built for one fixed scope (a filter predicate's) supplies this; one that
761
+ * follows the adapter's current scope supplies its own `typing()`.
762
+ */
763
+ export function primitivesAt(typing: OperandTyping, scope: BindingScope, nativeSafe: NativeSafeTable): PrimitiveInputs {
764
+ return { typing: () => typing.at(scope), nativeSafe }
765
+ }