@barefootjs/jsx 0.40.0 → 0.40.1

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 (140) hide show
  1. package/dist/adapters/ambiguous-nil-arithmetic.d.ts +41 -0
  2. package/dist/adapters/ambiguous-nil-arithmetic.d.ts.map +1 -0
  3. package/dist/adapters/attr-plan.d.ts.map +1 -1
  4. package/dist/adapters/boolean-carrier.d.ts +31 -0
  5. package/dist/adapters/boolean-carrier.d.ts.map +1 -0
  6. package/dist/adapters/component-props.d.ts +22 -7
  7. package/dist/adapters/component-props.d.ts.map +1 -1
  8. package/dist/adapters/computed-const.d.ts +17 -0
  9. package/dist/adapters/computed-const.d.ts.map +1 -1
  10. package/dist/adapters/dsl-template-adapter.d.ts +18 -1
  11. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  12. package/dist/adapters/number-value.d.ts +43 -0
  13. package/dist/adapters/number-value.d.ts.map +1 -0
  14. package/dist/analyzer-context.d.ts +7 -0
  15. package/dist/analyzer-context.d.ts.map +1 -1
  16. package/dist/analyzer.d.ts +34 -0
  17. package/dist/analyzer.d.ts.map +1 -1
  18. package/dist/expression-parser.d.ts.map +1 -1
  19. package/dist/index.d.ts +6 -3
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +1006 -351
  22. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +29 -0
  25. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/control-flow/plan/build-lazy-row.d.ts +2 -0
  27. package/dist/ir-to-client-js/control-flow/plan/build-lazy-row.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/control-flow/plan/build-reactive-effects.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/control-flow/plan/inner-loop.d.ts +5 -4
  31. package/dist/ir-to-client-js/control-flow/plan/inner-loop.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/plan/loop-child-arm.d.ts +2 -0
  33. package/dist/ir-to-client-js/control-flow/plan/loop-child-arm.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +15 -0
  35. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/control-flow/plan/reactive-effects.d.ts +2 -0
  37. package/dist/ir-to-client-js/control-flow/plan/reactive-effects.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts +20 -0
  40. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +1 -1
  43. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/control-flow/stringify/lazy-row.d.ts.map +1 -1
  45. package/dist/ir-to-client-js/html-template.d.ts +3 -2
  46. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  47. package/dist/ir-to-client-js/plan/build-static-array-child-init.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +7 -1
  49. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  50. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  51. package/dist/ir-to-client-js/safe-html.d.ts +9 -3
  52. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  53. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  54. package/dist/ir-to-client-js/types.d.ts +30 -0
  55. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  56. package/dist/ir-to-client-js/utils.d.ts +8 -0
  57. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  58. package/dist/jsx-to-ir.d.ts.map +1 -1
  59. package/dist/nullable-signal-attr.d.ts +29 -3
  60. package/dist/nullable-signal-attr.d.ts.map +1 -1
  61. package/dist/props-binding.d.ts +27 -3
  62. package/dist/props-binding.d.ts.map +1 -1
  63. package/dist/scope/binding-scope.d.ts +22 -1
  64. package/dist/scope/binding-scope.d.ts.map +1 -1
  65. package/dist/scope/root-prop-alias.d.ts +14 -1
  66. package/dist/scope/root-prop-alias.d.ts.map +1 -1
  67. package/dist/signal-prop-name-collision.d.ts.map +1 -1
  68. package/dist/ssr-defaults.d.ts +4 -2
  69. package/dist/ssr-defaults.d.ts.map +1 -1
  70. package/dist/ssr-seed-plan.d.ts +14 -0
  71. package/dist/ssr-seed-plan.d.ts.map +1 -1
  72. package/dist/template-parts.d.ts.map +1 -1
  73. package/dist/types.d.ts +30 -0
  74. package/dist/types.d.ts.map +1 -1
  75. package/package.json +2 -2
  76. package/src/__tests__/binding-scope-ratchet.test.ts +12 -2
  77. package/src/__tests__/boolean-carrier.test.ts +74 -0
  78. package/src/__tests__/component-props.test.ts +14 -0
  79. package/src/__tests__/computed-const.test.ts +85 -0
  80. package/src/__tests__/expression-parser.test.ts +24 -0
  81. package/src/__tests__/issue-3688-props-spread-child-csr.test.ts +142 -0
  82. package/src/__tests__/loop-row-prop-read.test.ts +111 -0
  83. package/src/__tests__/memo-body-expr.test.ts +137 -0
  84. package/src/__tests__/nullable-signal-attr.test.ts +97 -2
  85. package/src/__tests__/profile-binding-ids.test.ts +14 -0
  86. package/src/__tests__/root-prop-alias.test.ts +34 -1
  87. package/src/__tests__/signal-prop-name-collision.test.ts +102 -2
  88. package/src/__tests__/source-file-cache.test.ts +105 -0
  89. package/src/__tests__/ssr-seed-plan.test.ts +43 -0
  90. package/src/__tests__/template-parts-literal-boundary.test.ts +19 -0
  91. package/src/adapters/ambiguous-nil-arithmetic.ts +94 -0
  92. package/src/adapters/attr-plan.ts +6 -2
  93. package/src/adapters/boolean-carrier.ts +76 -0
  94. package/src/adapters/component-props.ts +28 -8
  95. package/src/adapters/computed-const.ts +206 -7
  96. package/src/adapters/dsl-template-adapter.ts +39 -0
  97. package/src/adapters/number-value.ts +95 -0
  98. package/src/analyzer-context.ts +8 -0
  99. package/src/analyzer.ts +187 -66
  100. package/src/expression-parser.ts +4 -1
  101. package/src/index.ts +12 -2
  102. package/src/ir-to-client-js/collect-elements.ts +104 -46
  103. package/src/ir-to-client-js/compute-inlinability.ts +1 -1
  104. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +15 -1
  105. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +79 -4
  106. package/src/ir-to-client-js/control-flow/plan/build-lazy-row.ts +3 -0
  107. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +1 -0
  108. package/src/ir-to-client-js/control-flow/plan/build-reactive-effects.ts +1 -0
  109. package/src/ir-to-client-js/control-flow/plan/inner-loop.ts +5 -4
  110. package/src/ir-to-client-js/control-flow/plan/loop-child-arm.ts +2 -0
  111. package/src/ir-to-client-js/control-flow/plan/loop.ts +12 -0
  112. package/src/ir-to-client-js/control-flow/plan/reactive-effects.ts +2 -0
  113. package/src/ir-to-client-js/control-flow/shared.ts +3 -2
  114. package/src/ir-to-client-js/control-flow/stringify/claim-plan.ts +27 -0
  115. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +8 -2
  116. package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +8 -1
  117. package/src/ir-to-client-js/control-flow/stringify/inner-loop.ts +8 -7
  118. package/src/ir-to-client-js/control-flow/stringify/lazy-row.ts +8 -7
  119. package/src/ir-to-client-js/control-flow/stringify/loop-child-arm.ts +4 -4
  120. package/src/ir-to-client-js/control-flow/stringify/loop.ts +3 -3
  121. package/src/ir-to-client-js/control-flow/stringify/reactive-effects.ts +6 -6
  122. package/src/ir-to-client-js/emit-reactive.ts +1 -1
  123. package/src/ir-to-client-js/html-template.ts +70 -30
  124. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +11 -1
  125. package/src/ir-to-client-js/plan/static-array-child-init.ts +7 -1
  126. package/src/ir-to-client-js/reactivity.ts +14 -0
  127. package/src/ir-to-client-js/safe-html.ts +11 -4
  128. package/src/ir-to-client-js/stringify/static-array-child-init.ts +6 -4
  129. package/src/ir-to-client-js/types.ts +23 -0
  130. package/src/ir-to-client-js/utils.ts +15 -1
  131. package/src/jsx-to-ir.ts +78 -35
  132. package/src/nullable-signal-attr.ts +134 -13
  133. package/src/props-binding.ts +54 -3
  134. package/src/scope/binding-scope.ts +30 -2
  135. package/src/scope/root-prop-alias.ts +17 -1
  136. package/src/signal-prop-name-collision.ts +113 -22
  137. package/src/ssr-defaults.ts +10 -4
  138. package/src/ssr-seed-plan.ts +82 -17
  139. package/src/template-parts.ts +21 -1
  140. package/src/types.ts +30 -0
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Which values may hold a JS boolean that the backend received as data, for
3
+ * backends whose own stringification of such a value differs from JS's
4
+ * `String(boolean)`: Perl decodes a JSON `false` to an object that prints
5
+ * `0` (and `true` prints `1`). Unlike `collectBooleanValueNames`, the value
6
+ * need not be a boolean every time — an optional prop, a `boolean | string`
7
+ * union or a `??` fallback may also be absent or another type — so the
8
+ * backend routes it through its JS `String` helper, which prints every value
9
+ * kind as JS does, rather than through `bool_str`.
10
+ */
11
+
12
+ import type { ParsedExpr } from '../expression-parser.ts'
13
+ import type { IRMetadata, TypeInfo } from '../types.ts'
14
+
15
+ /** Whether a declared type admits a boolean: `boolean`, a boolean literal, or a union with such a member. */
16
+ function admitsBoolean(type: TypeInfo | null | undefined): boolean {
17
+ if (!type) return false
18
+ if (type.kind === 'primitive') return type.primitive === 'boolean'
19
+ return type.kind === 'union' && (type.unionTypes ?? []).some(admitsBoolean)
20
+ }
21
+
22
+ /**
23
+ * Signals, memos and props whose declared type admits a boolean, optional or
24
+ * not, plus signals seeded with a boolean literal and no declared type.
25
+ * `names` holds the bare spellings (a getter, a memo, a destructured prop),
26
+ * `props` the caller-facing keys a `props.<key>` member reads. Whether a
27
+ * binding shadows a name is the caller's scope question.
28
+ */
29
+ export function collectBooleanCarrierNames(
30
+ metadata: Pick<IRMetadata, 'signals' | 'memos' | 'propsParams' | 'propsObjectName'>,
31
+ ): { names: Set<string>; props: Set<string> } {
32
+ const names = new Set<string>()
33
+ const props = new Set<string>()
34
+ for (const signal of metadata.signals) {
35
+ const untyped = !signal.type || signal.type.kind === 'unknown'
36
+ const booleanSeed = signal.parsed?.kind === 'literal' && signal.parsed.literalType === 'boolean'
37
+ if (admitsBoolean(signal.type) || (untyped && booleanSeed)) names.add(signal.getter)
38
+ }
39
+ for (const memo of metadata.memos ?? []) {
40
+ if (admitsBoolean(memo.type)) names.add(memo.name)
41
+ }
42
+ for (const param of metadata.propsParams) {
43
+ // A destructured union-typed prop keeps its written type in `declaredType`.
44
+ if (!admitsBoolean(param.declaredType ?? param.type)) continue
45
+ props.add(param.sourceName ?? param.name)
46
+ if (!metadata.propsObjectName) names.add(param.name)
47
+ }
48
+ return { names, props }
49
+ }
50
+
51
+ /**
52
+ * Whether `expr` may evaluate to the value of a name `isCarrierName`
53
+ * accepts — a zero-argument getter call, a `props.<key>` member or a bare
54
+ * identifier — read directly, as an operand of `??` / `||` / `&&` (JS
55
+ * returns an operand, not a coerced boolean), or as a ternary branch.
56
+ */
57
+ export function mayYieldBooleanCarrier(
58
+ expr: ParsedExpr | null | undefined,
59
+ isCarrierName: (name: string, componentProperty?: boolean) => boolean,
60
+ ): boolean {
61
+ if (!expr) return false
62
+ switch (expr.kind) {
63
+ case 'logical':
64
+ return mayYieldBooleanCarrier(expr.left, isCarrierName) || mayYieldBooleanCarrier(expr.right, isCarrierName)
65
+ case 'conditional':
66
+ return mayYieldBooleanCarrier(expr.consequent, isCarrierName) || mayYieldBooleanCarrier(expr.alternate, isCarrierName)
67
+ case 'call':
68
+ return expr.callee.kind === 'identifier' && expr.args.length === 0 && isCarrierName(expr.callee.name)
69
+ case 'member':
70
+ return !expr.computed && expr.object.kind === 'identifier' && expr.object.name === 'props' && isCarrierName(expr.property, true)
71
+ case 'identifier':
72
+ return isCarrierName(expr.name)
73
+ default:
74
+ return false
75
+ }
76
+ }
@@ -60,6 +60,13 @@ export interface ComponentPropsOptions {
60
60
  propsObjectName: string | null
61
61
  /** The analyzer-extracted props params, which `{...props}` enumerates. */
62
62
  propsParams: ReadonlyArray<ComponentPropsParam>
63
+ /**
64
+ * Whether the backend's runtime records which keys each component's
65
+ * caller passed, so a template can ask it whether a param was passed
66
+ * rather than whether it is nil (the DSL runtimes' `passed(name,
67
+ * fallback)`). See {@link propsSpreadParam}.
68
+ */
69
+ callerKeys?: boolean
63
70
  }
64
71
 
65
72
  /** What a call has set before a `{...props}` spread, as far as the compiler can see. */
@@ -82,14 +89,25 @@ export interface EarlierComponentProps {
82
89
  * - `'present'`: carried only when the caller passed it, so an absent param
83
90
  * leaves the earlier value alone.
84
91
  *
85
- * A template backend reads an absent prop and an explicit `undefined` or
86
- * `null` one as the same nil, so "passed" is spelled "not nil" there: a
87
- * caller that passes `undefined`/`null` keeps the earlier value, where JS
88
- * would override it with the nil (limitation
92
+ * A template engine reads an absent prop and an explicit `undefined` or
93
+ * `null` one as the same nil, so "passed" can't be spelled "not nil": a
94
+ * caller that passes `null` must still override the earlier value, as JS
95
+ * does. With `callerKeys`, the runtime answers "passed" from the keys the
96
+ * caller actually handed over, and every optional param is `'present'`:
97
+ * an `'entry'` would hand the child the key even when the caller left it
98
+ * out, and the child would then read it as passed (a nil overriding its
99
+ * own earlier prop in a further `{...props}`). Without `callerKeys` (Go,
100
+ * whose Input struct can't tell the two nils apart), "passed" is "not
101
+ * nil", and an explicit nil keeps the earlier value (limitation
89
102
  * `props-spread-explicit-null-override`).
90
103
  */
91
- export function propsSpreadParam(param: ComponentPropsParam, earlier: EarlierComponentProps): 'entry' | 'present' {
104
+ export function propsSpreadParam(
105
+ param: ComponentPropsParam,
106
+ earlier: EarlierComponentProps,
107
+ callerKeys = false,
108
+ ): 'entry' | 'present' {
92
109
  if (param.optional === false) return 'entry'
110
+ if (callerKeys) return 'present'
93
111
  return earlier.spread || earlier.keys.has(param.name) ? 'present' : 'entry'
94
112
  }
95
113
 
@@ -130,7 +148,7 @@ export function planComponentProps(
130
148
  // against the params this same spread has already pushed.
131
149
  const before: EarlierComponentProps = { keys: new Set(earlier.keys), spread: earlier.spread }
132
150
  for (const param of options.propsParams) {
133
- if (propsSpreadParam(param, before) === 'entry') {
151
+ if (propsSpreadParam(param, before, options.callerKeys) === 'entry') {
134
152
  push({ kind: 'props-param', name: param.name })
135
153
  } else {
136
154
  earlier.keys.add(param.name)
@@ -173,8 +191,10 @@ export interface ComponentPropSpelling {
173
191
  spread(value: SpreadAttr): string
174
192
  /**
175
193
  * The expression a `present-param` segment folds in like a spread: a
176
- * one-key hash `{ name: <param> }` when the param is not nil, an empty
177
- * hash when it is.
194
+ * one-key hash `{ name: <param> }` when the caller passed the param, an
195
+ * empty hash when it did not. "Passed" is the runtime's
196
+ * `passed('<name>', <param is not nil>)`: the caller's keys when the
197
+ * runtime recorded them, the nil test otherwise.
178
198
  */
179
199
  presentParam(name: string): string
180
200
  }
@@ -19,6 +19,7 @@ import { collectContextConsumers, lookupLiteralConst } from '../augment-inherite
19
19
  import { freeIdentifiers, inlineBinding, parseExpression, stringifyParsedExpr, type ParsedExpr } from '../expression-parser.ts'
20
20
  import type { ConstantInfo, ExpressionAttr, IRMetadata } from '../types.ts'
21
21
  import { componentBindings } from '../relocate.ts'
22
+ import { PROPS_OBJECT_IDENTIFIER } from '../scope/binding-scope.ts'
22
23
 
23
24
  export interface ComputedConstContext {
24
25
  constants: IRMetadata['localConstants'] | undefined
@@ -28,6 +29,23 @@ export interface ComputedConstContext {
28
29
  contextConsumers: ReadonlySet<string>
29
30
  /** Consts a props destructure binds, which the adapter binds as props params. */
30
31
  propsBindings: ReadonlySet<string>
32
+ /**
33
+ * Component-scope names that hold a prop as passed, with the prop's
34
+ * caller-facing key: a destructured signature param (`{ children: kids }`
35
+ * → `kids` → `children`) or a props destructure const. Empty when the
36
+ * props object identifier names something else.
37
+ */
38
+ propReads: ReadonlyMap<string, string>
39
+ /** Component-scope local functions, which shadow a module const of the same name. */
40
+ localFunctions: ReadonlySet<string>
41
+ /**
42
+ * Names the component scope lexically binds (the props object, destructured
43
+ * and rest props, its consts, local functions, signals, memos), which
44
+ * shadow a module binding of the same name. A module const's initializer
45
+ * never reads one of them. A prop reachable only through the props object
46
+ * (`function C(props: { label: string })`) binds no name.
47
+ */
48
+ componentNames: ReadonlySet<string>
31
49
  /** Whether a loop row or callback binds `name` where the expression is read. */
32
50
  isShadowed(name: string): boolean
33
51
  /** Whether the adapter binds the const `name` itself, so a read of it stays as written. */
@@ -52,6 +70,9 @@ export function computedConstContext(
52
70
  getters: new Set([...metadata.signals.map(s => s.getter), ...metadata.memos.map(m => m.name)]),
53
71
  contextConsumers: new Set(collectContextConsumers(metadata).map(c => c.localName)),
54
72
  propsBindings: propsBindingNames(metadata),
73
+ propReads: propReadKeys(metadata, bindings),
74
+ localFunctions: new Set(metadata.localFunctions.filter(f => !f.isModule).map(f => f.name)),
75
+ componentNames: componentScopeNames(metadata),
55
76
  isShadowed,
56
77
  isAdapterBound,
57
78
  isGlobal: name => !bindings.has(name) && name !== metadata.restPropsName && !isShadowed(name),
@@ -83,6 +104,54 @@ function propsBindingNames(metadata: IRMetadata): Set<string> {
83
104
  return names
84
105
  }
85
106
 
107
+ /**
108
+ * {@link ComputedConstContext.componentNames}. Not `componentBindings`, which
109
+ * also lists every typed prop of a props object as a `prop` binding.
110
+ */
111
+ function componentScopeNames(metadata: IRMetadata): Set<string> {
112
+ const names = new Set<string>()
113
+ if (metadata.propsObjectName !== null) names.add(metadata.propsObjectName)
114
+ // With no props object the signature destructures, so every param is bound.
115
+ else for (const p of metadata.propsParams) names.add(p.name)
116
+ if (metadata.restPropsName) names.add(metadata.restPropsName)
117
+ for (const c of metadata.localConstants) if (!c.isModule) names.add(c.name)
118
+ for (const f of metadata.localFunctions) if (!f.isModule) names.add(f.name)
119
+ for (const s of metadata.signals) {
120
+ if (s.isModule) continue
121
+ names.add(s.getter)
122
+ if (s.setter) names.add(s.setter)
123
+ }
124
+ for (const m of metadata.memos) if (!m.isModule) names.add(m.name)
125
+ return names
126
+ }
127
+
128
+ /**
129
+ * {@link ComputedConstContext.propReads}: each component-scope name bound to
130
+ * a prop as passed, with the prop's key, so a read of it can be spelled
131
+ * `props.<key>` where a loop row or callback shadows the name. A template
132
+ * reads that as the prop's own variable, which holds a destructure default
133
+ * already. Only when the props object identifier `props` names the props
134
+ * object or nothing in the component, so the spelling cannot read another
135
+ * binding.
136
+ */
137
+ function propReadKeys(metadata: IRMetadata, bindings: ReadonlyMap<string, unknown>): Map<string, string> {
138
+ const reads = new Map<string, string>()
139
+ const propsObject = metadata.propsObjectName
140
+ // Under another props object name (`function C(p)`) the adapters do not
141
+ // agree on what a read of `props` is, so no prop read is respelled.
142
+ if (propsObject === null ? bindings.has(PROPS_OBJECT_IDENTIFIER) : propsObject !== PROPS_OBJECT_IDENTIFIER) return reads
143
+ const destructures = propsBindingNames(metadata)
144
+ for (const param of metadata.propsParams) {
145
+ if (param.isRest) continue
146
+ // A signature that names the props object binds no param locally; only
147
+ // a props destructure const does.
148
+ if (propsObject !== null && !destructures.has(param.name)) continue
149
+ if (bindings.get(param.name) !== 'prop') continue
150
+ reads.set(param.name, param.sourceName ?? param.name)
151
+ }
152
+ return reads
153
+ }
154
+
86
155
  /** Upper bound on const-of-const chains, a guard against a malformed cycle. */
87
156
  const MAX_DEPTH = 16
88
157
 
@@ -108,11 +177,140 @@ function inlineOnce(expr: ParsedExpr, ctx: ComputedConstContext): ParsedExpr {
108
177
  for (const name of free) {
109
178
  const init = inlinableInitializer(name, ctx)
110
179
  if (!init) continue
111
- result = inlineBinding(result, name, init) ?? result
180
+ result = inlineBinding(result, name, init) ?? inlineUnderCallbacks(result, name, init, ctx) ?? result
112
181
  }
113
182
  return result
114
183
  }
115
184
 
185
+ /**
186
+ * {@link inlineBinding} for an initializer a callback param inside `expr`
187
+ * would capture (`rows.filter(a => a !== b)` with `const b = a`): the
188
+ * initializer resolved in the component scope first
189
+ * ({@link resolveInComponentScope}), so none of its free names is one the
190
+ * expression's callbacks bind.
191
+ */
192
+ function inlineUnderCallbacks(expr: ParsedExpr, name: string, init: ParsedExpr, ctx: ComputedConstContext): ParsedExpr | null {
193
+ const params = arrowParamNames(expr)
194
+ if (params.size === 0) return null
195
+ const resolved = resolveInComponentScope(init, ctx, n => params.has(n) || ctx.isShadowed(n))
196
+ return resolved ? inlineBinding(expr, name, resolved) : null
197
+ }
198
+
199
+ /** Every param name an arrow anywhere in `expr` binds. */
200
+ function arrowParamNames(expr: ParsedExpr): Set<string> {
201
+ const names = new Set<string>()
202
+ const visit = (node: unknown): void => {
203
+ if (node === null || typeof node !== 'object') return
204
+ if (Array.isArray(node)) {
205
+ node.forEach(visit)
206
+ return
207
+ }
208
+ const e = node as ParsedExpr
209
+ if (e.kind === 'arrow') for (const p of e.params) names.add(p)
210
+ for (const value of Object.values(e)) visit(value)
211
+ }
212
+ visit(expr)
213
+ return names
214
+ }
215
+
216
+ /** The scope a const's initializer is written in, which its free names resolve against. */
217
+ type InitScope = 'component' | 'module'
218
+
219
+ /**
220
+ * `init`, an initializer written in `scope`, with each free name replaced
221
+ * where reading it at the use site would reach a different binding: one
222
+ * `captured` holds there (a loop row or callback binds it), or, for a module
223
+ * const's initializer, one the component scope binds. The name becomes what
224
+ * it holds in `scope`: a computed or literal const its own initializer,
225
+ * resolved the same way (`const a = children; const b = a` read in
226
+ * `rows.map(a => …{b}…)` reads `children`), and a component-scope prop
227
+ * binding `props.<key>`, which the adapters read as the prop wherever a row
228
+ * rebinds its bare name (#3696). `null` when such a name holds anything
229
+ * else, or when `props` itself is captured.
230
+ */
231
+ function resolveInitializer(
232
+ init: ParsedExpr,
233
+ ctx: ComputedConstContext,
234
+ captured: (name: string) => boolean,
235
+ scope: InitScope,
236
+ depth = 0,
237
+ ): ParsedExpr | null {
238
+ const free = freeIdentifiers(init)
239
+ if (!free || depth >= MAX_DEPTH) return null
240
+ let result = init
241
+ for (const name of free) {
242
+ if (!captured(name) && !(scope === 'module' && ctx.componentNames.has(name))) continue
243
+ const value = scope === 'module' ? moduleScopeValue(name, ctx, captured, depth) : componentScopeValue(name, ctx, captured, depth)
244
+ const next = value ? inlineBinding(result, name, value) : null
245
+ if (!next) return null
246
+ result = next
247
+ }
248
+ return result
249
+ }
250
+
251
+ /** {@link resolveInitializer} for an initializer written in the component scope. */
252
+ function resolveInComponentScope(init: ParsedExpr, ctx: ComputedConstContext, captured: (name: string) => boolean): ParsedExpr | null {
253
+ return resolveInitializer(init, ctx, captured, 'component')
254
+ }
255
+
256
+ /** What the component-scope name `name` holds, for {@link resolveInitializer}. */
257
+ function componentScopeValue(
258
+ name: string,
259
+ ctx: ComputedConstContext,
260
+ captured: (name: string) => boolean,
261
+ depth: number,
262
+ ): ParsedExpr | null {
263
+ if (ctx.getters.has(name) || ctx.contextConsumers.has(name) || ctx.localFunctions.has(name)) return null
264
+ if (ctx.isAdapterBound(name)) return null
265
+ const key = ctx.propReads.get(name)
266
+ if (key !== undefined) {
267
+ if (captured(PROPS_OBJECT_IDENTIFIER)) return null
268
+ return { kind: 'member', object: { kind: 'identifier', name: PROPS_OBJECT_IDENTIFIER }, property: key, computed: false, optional: false }
269
+ }
270
+ // Any other component binding of the name is not a const this can read.
271
+ if (ctx.componentNames.has(name) && !componentConst(name, ctx)) return null
272
+ return constValue(componentConst(name, ctx) ?? moduleConst(name, ctx), ctx, captured, depth)
273
+ }
274
+
275
+ /**
276
+ * What the module-scope name `name` holds, for {@link resolveInitializer}:
277
+ * only a module const, whatever the component scope binds by that name.
278
+ * `isAdapterBound` names a component-scope binding, so it does not apply.
279
+ */
280
+ function moduleScopeValue(
281
+ name: string,
282
+ ctx: ComputedConstContext,
283
+ captured: (name: string) => boolean,
284
+ depth: number,
285
+ ): ParsedExpr | null {
286
+ return constValue(moduleConst(name, ctx), ctx, captured, depth)
287
+ }
288
+
289
+ /** A const's initializer resolved in the scope it is declared in, or `null` when it is not one a template can inline. */
290
+ function constValue(
291
+ constant: ConstantInfo | undefined,
292
+ ctx: ComputedConstContext,
293
+ captured: (name: string) => boolean,
294
+ depth: number,
295
+ ): ParsedExpr | null {
296
+ const init = constant?.parsed
297
+ // A props destructure const is the component's; a module const of that name is not one.
298
+ if (!constant || !init || (!constant.isModule && ctx.propsBindings.has(constant.name))) return null
299
+ const literal = lookupLiteralConst(constant.name, [constant], () => false) !== null
300
+ if (!literal && !(isPlainComputedConst(constant, init) && callsOnlyGetters(init, constant.isModule ? new Set() : ctx.getters))) return null
301
+ return resolveInitializer(init, ctx, captured, constant.isModule ? 'module' : 'component', depth + 1)
302
+ }
303
+
304
+ /** The component-scope const `name`. */
305
+ function componentConst(name: string, ctx: ComputedConstContext): ConstantInfo | undefined {
306
+ return ctx.constants?.find(c => c.name === name && !c.isModule)
307
+ }
308
+
309
+ /** The module-scope const `name`. */
310
+ function moduleConst(name: string, ctx: ComputedConstContext): ConstantInfo | undefined {
311
+ return ctx.constants?.find(c => c.name === name && c.isModule)
312
+ }
313
+
116
314
  /**
117
315
  * An `{expr}` attribute value read through {@link inlineComputedConsts}, so
118
316
  * the attribute's own plan (a nullable prop read drops the attribute) sees
@@ -131,17 +329,18 @@ export function inlineComputedConstAttr(value: ExpressionAttr, ctx: ComputedCons
131
329
 
132
330
  /** The initializer of a const read `name` stands for, or `null` when the read stays as it is. */
133
331
  function inlinableInitializer(name: string, ctx: ComputedConstContext): ParsedExpr | null {
134
- const constant = ctx.constants?.find(c => c.name === name)
332
+ // A component-scope binding of the name shadows a module const.
333
+ const constant = componentConst(name, ctx) ?? (ctx.componentNames.has(name) ? undefined : moduleConst(name, ctx))
135
334
  const init = constant?.parsed
136
335
  if (!constant || !init || !isPlainComputedConst(constant, init)) return null
137
336
  if (ctx.isShadowed(name) || ctx.getters.has(name) || ctx.contextConsumers.has(name) || ctx.propsBindings.has(name)) return null
138
337
  if (ctx.isAdapterBound(name)) return null
139
338
  // An adapter already inlines a literal const in its own syntax.
140
- if (lookupLiteralConst(name, ctx.constants, ctx.isShadowed) !== null) return null
141
- // A free name the read site rebinds would be captured by the substitution.
142
- const free = freeIdentifiers(init)
143
- if (!free || [...free].some(n => ctx.isShadowed(n))) return null
144
- return callsOnlyGetters(init, ctx.getters) ? init : null
339
+ if (lookupLiteralConst(name, [constant], ctx.isShadowed) !== null) return null
340
+ if (!callsOnlyGetters(init, ctx.getters)) return null
341
+ // A free name the read site rebinds would be captured by the substitution:
342
+ // it is read as what it holds where the const is declared instead.
343
+ return resolveInitializer(init, ctx, n => ctx.isShadowed(n), constant.isModule ? 'module' : 'component')
145
344
  }
146
345
 
147
346
  /**
@@ -8,9 +8,11 @@
8
8
  import { augmentInheritedPropAccesses, collectModuleStringConsts } from '../augment-inherited-props.ts'
9
9
  import { buildImportAliasMap } from '../ir-to-client-js/component-scope.ts'
10
10
  import { prepareLoweringMatchers, type LoweringMatcher } from '../lowering-registry.ts'
11
+ import type { ParsedExpr } from '../expression-parser.ts'
11
12
  import {
12
13
  collectNullableSignalGetters,
13
14
  collectNullishAttrContext,
15
+ type ArithmeticCoercion,
14
16
  type NullishAttrContext,
15
17
  } from '../nullable-signal-attr.ts'
16
18
  import { BindingScope } from '../scope/binding-scope.ts'
@@ -24,6 +26,12 @@ import type {
24
26
  IRMetadata,
25
27
  PreambleValueDeclaration,
26
28
  } from '../types.ts'
29
+ import {
30
+ arithmeticCoercionOrRefuse,
31
+ refuseAmbiguousNilArithmetic,
32
+ refuseAmbiguousNilMemoArithmetic,
33
+ type AmbiguousNilArithmeticSink,
34
+ } from './ambiguous-nil-arithmetic.ts'
27
35
  import { collectImportedLoopChildComponentErrors } from './component-tree.ts'
28
36
  import { computedConstContext, type ComputedConstContext } from './computed-const.ts'
29
37
  import { searchParamsLocalNames } from './env-signal.ts'
@@ -224,6 +232,36 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
224
232
  }
225
233
  }
226
234
 
235
+ /**
236
+ * The coercion an arithmetic operand's emitter spells
237
+ * (`arithmeticOperandCoercion`), refusing an operand whose nil the
238
+ * declared type cannot classify (`arithmeticCoercionOrRefuse`, #3700).
239
+ * `isShadowed` is the adapter's scope test at the emission site.
240
+ */
241
+ protected arithmeticCoercion(
242
+ op: string,
243
+ operand: ParsedExpr,
244
+ other: ParsedExpr | undefined,
245
+ isShadowed: (name: string) => boolean,
246
+ ): ArithmeticCoercion {
247
+ return arithmeticCoercionOrRefuse(op, operand, other, this.nullishAttrCtx, isShadowed, this.ambiguousNilSink())
248
+ }
249
+
250
+ /**
251
+ * Refuse the ambiguous-nil arithmetic (#3700) in a whole expression the
252
+ * adapter lowers through its own renderer rather than per operator: a
253
+ * `.filter()` predicate, read in the current scope with the callback's
254
+ * own `params` (its parameter and block locals) entered as a callback
255
+ * frame.
256
+ */
257
+ protected refuseAmbiguousNilArithmeticIn(expr: ParsedExpr, params: readonly string[]): void {
258
+ refuseAmbiguousNilArithmetic(expr, this.nullishAttrCtx, this.scope.enterCallback(params), this.ambiguousNilSink())
259
+ }
260
+
261
+ private ambiguousNilSink(): AmbiguousNilArithmeticSink {
262
+ return { errors: this.errors, componentName: this.componentName }
263
+ }
264
+
227
265
  /** {@link planLoop} against the current scope and the component's constants. */
228
266
  protected loopPlanFor<Spelled>(loop: IRLoop, spelling: LoopPlanSpelling<Spelled>): LoopPlan<Spelled> {
229
267
  return planLoop(loop, { scope: this.scope, localConstants: this.localConstants ?? [], ...spelling })
@@ -397,5 +435,6 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
397
435
  if (!options?.siblingTemplatesRegistered) {
398
436
  this.errors.push(...collectImportedLoopChildComponentErrors(ir, this.componentName, this.loopChildDiagnosticName))
399
437
  }
438
+ refuseAmbiguousNilMemoArithmetic(ir.metadata.memos ?? [], this.nullishAttrCtx, this.ambiguousNilSink())
400
439
  }
401
440
  }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Which values are JS numbers, for backends whose own number
3
+ * stringification differs from JS's `Number::toString` (Perl prints
4
+ * `%.15g` and spells the infinities `Inf`), and whose equality operators
5
+ * need the operand's type.
6
+ */
7
+
8
+ import type { ParsedExpr } from '../expression-parser.ts'
9
+ import type { SsrSeedPlan } from '../ssr-seed-plan.ts'
10
+ import type { ComponentIR, TypeInfo } from '../types.ts'
11
+ import { isNumericArithmeticResult } from './parsed-expr-emitter.ts'
12
+
13
+ /**
14
+ * Number-typed signals, memos, props and same-file local consts: a strict
15
+ * equality against one of them keeps Perl's numeric `==` / `!=`, where an
16
+ * operand of unknown type goes through the runtime's `strict_eq`
17
+ * (`emitPerlEquality`). `names` holds the bare spellings (a getter, a
18
+ * destructured prop, a const), `props` the caller-facing keys a
19
+ * `props.<key>` member reads. Whether a binding shadows a name is the
20
+ * caller's scope question.
21
+ */
22
+ export function collectNumberValueNames(ir: Pick<ComponentIR, 'metadata'>): { names: Set<string>; props: Set<string> } {
23
+ const isNumber = (type: TypeInfo | null | undefined): boolean =>
24
+ type?.kind === 'primitive' && type.primitive === 'number'
25
+ const names = new Set<string>()
26
+ const props = new Set<string>()
27
+ for (const s of ir.metadata.signals) {
28
+ if (isNumber(s.type)) names.add(s.getter)
29
+ }
30
+ for (const m of ir.metadata.memos ?? []) {
31
+ if (isNumber(m.type)) names.add(m.name)
32
+ }
33
+ for (const p of ir.metadata.propsParams) {
34
+ if (!isNumber(p.type)) continue
35
+ props.add(p.sourceName ?? p.name)
36
+ if (!ir.metadata.propsObjectName) names.add(p.name)
37
+ }
38
+ for (const c of ir.metadata.localConstants) {
39
+ if (isNumber(c.type)) names.add(c.name)
40
+ }
41
+ return { names, props }
42
+ }
43
+
44
+ /**
45
+ * Whether an expression yields a JS NUMBER: arithmetic
46
+ * ({@link isNumericArithmeticResult}), a read of a name `isNumberName`
47
+ * accepts — a zero-argument getter call, a `props.<key>` member, or a bare
48
+ * identifier — or a ternary with such a branch. Backends whose own number
49
+ * stringification differs from JS (Perl spells the infinities `Inf` and
50
+ * prints `%.15g`) route such a value through their `Number::toString`
51
+ * helper wherever JS stringifies it: an output position, or an operand of
52
+ * string concatenation (#3711). Whether a binding shadows the name is
53
+ * `isNumberName`'s scope question.
54
+ */
55
+ export function isNumberValuedExpr(
56
+ expr: ParsedExpr | null | undefined,
57
+ isStringName: (n: string, componentProperty?: boolean) => boolean,
58
+ isNumberName: (n: string, componentProperty?: boolean) => boolean,
59
+ ): boolean {
60
+ if (!expr) return false
61
+ if (isNumericArithmeticResult(expr, isStringName)) return true
62
+ // Either branch may be the value printed; the helper passes a string
63
+ // branch through unchanged.
64
+ if (expr.kind === 'conditional') {
65
+ return isNumberValuedExpr(expr.consequent, isStringName, isNumberName) ||
66
+ isNumberValuedExpr(expr.alternate, isStringName, isNumberName)
67
+ }
68
+ if (expr.kind === 'call') return expr.callee.kind === 'identifier' && expr.args.length === 0 && isNumberName(expr.callee.name)
69
+ if (expr.kind === 'member') {
70
+ return !expr.computed && expr.object.kind === 'identifier' && expr.object.name === 'props' && isNumberName(expr.property, true)
71
+ }
72
+ return expr.kind === 'identifier' && isNumberName(expr.name)
73
+ }
74
+
75
+ /**
76
+ * Signals and memos whose in-template seed (a `derived` step of the SSR seed
77
+ * plan) is a JS number by construction: arithmetic, or a read of a
78
+ * number-typed name or of an earlier such seed (an identity memo). Their
79
+ * declared type is often `unknown` (`createMemo(() => count() / 0)` infers
80
+ * none without a checker), so the seed's shape is the evidence (#3711).
81
+ */
82
+ export function numberValuedSeedNames(
83
+ plan: SsrSeedPlan,
84
+ isStringName: (n: string, componentProperty?: boolean) => boolean,
85
+ isNumberName: (n: string, componentProperty?: boolean) => boolean,
86
+ ): Set<string> {
87
+ const names = new Set<string>()
88
+ const isNumber = (n: string, componentProperty?: boolean) =>
89
+ isNumberName(n, componentProperty) || (!componentProperty && names.has(n))
90
+ for (const step of plan.steps) {
91
+ if (step.kind !== 'derived' || step.origin === 'prop') continue
92
+ if (isNumberValuedExpr(step.parsed, isStringName, isNumber)) names.add(step.name)
93
+ }
94
+ return names
95
+ }
@@ -189,6 +189,13 @@ export interface AnalyzerContext {
189
189
  * extraction. Flushed into `signals` at the end of visitComponentBody.
190
190
  */
191
191
  signalTupleRefs: Map<string, PendingSignalTuple>
192
+ /**
193
+ * Writers of a signal seed's / memo body's client template text
194
+ * (`SignalInfo.templateInitialValue`, `MemoInfo.templateBodyExpr`), run
195
+ * once the whole component body is walked so the props bindings they read
196
+ * live are decided against every body binding (`templatePropReadParams`).
197
+ */
198
+ templatePropReadWriters: Array<() => void>
192
199
 
193
200
  // Props
194
201
  propsType: TypeInfo | null
@@ -291,6 +298,7 @@ export function createAnalyzerContext(
291
298
  reactiveShapedHelpers: new Set(),
292
299
  cleanFactoryImports: new Set(),
293
300
  signalTupleRefs: new Map(),
301
+ templatePropReadWriters: [],
294
302
 
295
303
  propsType: null,
296
304
  propsParams: [],