@barefootjs/jsx 0.40.2 → 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 (88) hide show
  1. package/dist/adapters/callback-method.d.ts +8 -1
  2. package/dist/adapters/callback-method.d.ts.map +1 -1
  3. package/dist/adapters/component-props.d.ts +3 -4
  4. package/dist/adapters/component-props.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +3 -12
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  7. package/dist/adapters/loop-row-type.d.ts +7 -0
  8. package/dist/adapters/loop-row-type.d.ts.map +1 -1
  9. package/dist/adapters/nil-reading.d.ts +15 -20
  10. package/dist/adapters/nil-reading.d.ts.map +1 -1
  11. package/dist/adapters/non-primitive-equality.d.ts +1 -1
  12. package/dist/adapters/parsed-expr-emitter.d.ts +11 -1
  13. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  14. package/dist/adapters/primitive-plan.d.ts +40 -11
  15. package/dist/adapters/primitive-plan.d.ts.map +1 -1
  16. package/dist/adapters/prop-classes.d.ts +5 -0
  17. package/dist/adapters/prop-classes.d.ts.map +1 -1
  18. package/dist/analyzer.d.ts.map +1 -1
  19. package/dist/index.d.ts +5 -6
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +390 -228
  22. package/dist/ir-to-client-js/child-props-object.d.ts +43 -1
  23. package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  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-loop-child-arm.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/imports.d.ts +2 -2
  29. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/phases/props-extraction.d.ts +3 -3
  31. package/dist/ir-to-client-js/plan/build-declaration-emit.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +3 -1
  33. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  34. package/dist/jsx-to-ir.d.ts.map +1 -1
  35. package/dist/nullable-signal-attr.d.ts +4 -46
  36. package/dist/nullable-signal-attr.d.ts.map +1 -1
  37. package/dist/props-binding.d.ts +58 -13
  38. package/dist/props-binding.d.ts.map +1 -1
  39. package/dist/ssr-defaults.d.ts +39 -3
  40. package/dist/ssr-defaults.d.ts.map +1 -1
  41. package/package.json +2 -2
  42. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +6 -6
  43. package/src/__tests__/body-destructured-prop-default-arrow.test.ts +2 -2
  44. package/src/__tests__/body-destructured-props-live.test.ts +5 -5
  45. package/src/__tests__/client-js-generation.test.ts +3 -3
  46. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +7 -7
  47. package/src/__tests__/destructured-props-live.test.ts +1 -1
  48. package/src/__tests__/issue-3861-object-spread-child.test.ts +102 -0
  49. package/src/__tests__/memo-body-expr.test.ts +2 -2
  50. package/src/__tests__/nil-reading.test.ts +3 -2
  51. package/src/__tests__/nullable-signal-attr.test.ts +30 -103
  52. package/src/__tests__/primitive-plan.test.ts +90 -12
  53. package/src/__tests__/prop-default-undefined-only.test.ts +115 -0
  54. package/src/__tests__/prop-references.test.ts +2 -2
  55. package/src/__tests__/props-destructuring.test.ts +17 -0
  56. package/src/__tests__/prune-unused-prop-extractions.test.ts +3 -3
  57. package/src/__tests__/renamed-body-destructure-template.test.ts +7 -7
  58. package/src/__tests__/rewrite-destructured-props.test.ts +1 -1
  59. package/src/__tests__/ssr-defaults.test.ts +113 -25
  60. package/src/__tests__/written-binding-substitution.test.ts +8 -8
  61. package/src/adapters/callback-method.ts +13 -5
  62. package/src/adapters/component-props.ts +3 -4
  63. package/src/adapters/dsl-template-adapter.ts +26 -28
  64. package/src/adapters/loop-row-type.ts +10 -0
  65. package/src/adapters/nil-reading.ts +23 -25
  66. package/src/adapters/non-primitive-equality.ts +1 -1
  67. package/src/adapters/parsed-expr-emitter.ts +31 -2
  68. package/src/adapters/primitive-plan.ts +84 -15
  69. package/src/adapters/prop-classes.ts +16 -3
  70. package/src/analyzer.ts +27 -7
  71. package/src/index.ts +4 -11
  72. package/src/ir-to-client-js/child-props-object.ts +140 -6
  73. package/src/ir-to-client-js/collect-elements.ts +7 -14
  74. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +4 -2
  75. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +4 -2
  76. package/src/ir-to-client-js/html-template.ts +18 -9
  77. package/src/ir-to-client-js/imports.ts +1 -1
  78. package/src/ir-to-client-js/phases/props-extraction.ts +11 -7
  79. package/src/ir-to-client-js/plan/build-declaration-emit.ts +40 -7
  80. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +58 -5
  81. package/src/ir-to-client-js/rewrite-destructured-props.ts +31 -1
  82. package/src/jsx-to-ir.ts +15 -2
  83. package/src/nullable-signal-attr.ts +11 -138
  84. package/src/props-binding.ts +84 -19
  85. package/src/ssr-defaults.ts +100 -11
  86. package/dist/adapters/ambiguous-nil-arithmetic.d.ts +0 -42
  87. package/dist/adapters/ambiguous-nil-arithmetic.d.ts.map +0 -1
  88. package/src/adapters/ambiguous-nil-arithmetic.ts +0 -103
@@ -10,14 +10,15 @@ import { buildImportAliasMap } from '../ir-to-client-js/component-scope.ts'
10
10
  import { prepareLoweringMatchers, type LoweringMatcher } from '../lowering-registry.ts'
11
11
  import type { ParsedExpr } from '../expression-parser.ts'
12
12
  import {
13
+ arithmeticOperandCoercion,
13
14
  collectNullableSignalGetters,
14
15
  collectNullishAttrContext,
15
16
  type ArithmeticCoercion,
16
17
  type NullishAttrContext,
17
18
  } from '../nullable-signal-attr.ts'
18
19
  import { BindingScope } from '../scope/binding-scope.ts'
19
- import { declaredValueTypes, loopRowType, type DeclaredValueTypes } from './loop-row-type.ts'
20
- import { collectOperandTyping, EMPTY_OPERAND_TYPING, type OperandTyping, type ScopedOperandTyping } from './operand-typing.ts'
20
+ import { declaredValueType, declaredValueTypes, loopRowType, type DeclaredValueTypes } from './loop-row-type.ts'
21
+ import { collectOperandTyping, EMPTY_OPERAND_TYPING, factsOfType, type OperandTyping, type ScopedOperandTyping } from './operand-typing.ts'
21
22
  import { rootPropAliasesForLoop, rootPropAliasNames } from '../scope/root-prop-alias.ts'
22
23
  import type {
23
24
  CompilerError,
@@ -28,13 +29,7 @@ import type {
28
29
  IRMetadata,
29
30
  PreambleValueDeclaration,
30
31
  } from '../types.ts'
31
- import {
32
- arithmeticCoercionOrRefuse,
33
- refuseAmbiguousNilArithmetic,
34
- refuseAmbiguousNilMemoArithmetic,
35
- type AmbiguousNilArithmeticSink,
36
- } from './ambiguous-nil-arithmetic.ts'
37
- import { refuseNonPrimitiveStrictEquality } from './non-primitive-equality.ts'
32
+ import { refuseNonPrimitiveStrictEquality, type NonPrimitiveEqualitySink } from './non-primitive-equality.ts'
38
33
  import { collectImportedLoopChildComponentErrors } from './component-tree.ts'
39
34
  import { computedConstContext, type ComputedConstContext } from './computed-const.ts'
40
35
  import { searchParamsLocalNames } from './env-signal.ts'
@@ -267,9 +262,8 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
267
262
 
268
263
  /**
269
264
  * The coercion an arithmetic operand's emitter spells
270
- * (`arithmeticOperandCoercion`), refusing an operand whose nil the
271
- * declared type cannot classify (`arithmeticCoercionOrRefuse`, #3700).
272
- * `isShadowed` is the adapter's scope test at the emission site.
265
+ * (`arithmeticOperandCoercion`). `isShadowed` is the adapter's scope test
266
+ * at the emission site.
273
267
  */
274
268
  protected arithmeticCoercion(
275
269
  op: string,
@@ -277,21 +271,10 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
277
271
  other: ParsedExpr | undefined,
278
272
  isShadowed: (name: string) => boolean,
279
273
  ): ArithmeticCoercion {
280
- return arithmeticCoercionOrRefuse(op, operand, other, this.nullishAttrCtx, isShadowed, this.ambiguousNilSink())
281
- }
282
-
283
- /**
284
- * Refuse the ambiguous-nil arithmetic (#3700) in a whole expression the
285
- * adapter lowers through its own renderer rather than per operator: a
286
- * `.filter()` predicate, read in the current scope with the callback's
287
- * own `params` (its parameter and block locals) entered as a callback
288
- * frame.
289
- */
290
- protected refuseAmbiguousNilArithmeticIn(expr: ParsedExpr, params: readonly string[]): void {
291
- refuseAmbiguousNilArithmetic(expr, this.nullishAttrCtx, this.scope.enterCallback(params), this.ambiguousNilSink())
274
+ return arithmeticOperandCoercion(op, operand, other, this.nullishAttrCtx, isShadowed)
292
275
  }
293
276
 
294
- private ambiguousNilSink(): AmbiguousNilArithmeticSink {
277
+ private errorSink(): NonPrimitiveEqualitySink {
295
278
  return { errors: this.errors, componentName: this.componentName }
296
279
  }
297
280
 
@@ -440,10 +423,13 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
440
423
  this.rootPropAliases = rootPropAliasNames(ir, this.propsParams.map(p => p.name))
441
424
  this.scope = BindingScope.forComponent(this.propsObjectName)
442
425
  this.nullableOptionalProps = collectNullableOptionalProps(ir)
443
- this.nullableSignalGetters = collectNullableSignalGetters(ir)
444
426
  this.nullishAttrCtx = collectNullishAttrContext(ir)
445
427
  this.stringValueNames = this.stringValueNamesFor(ir)
446
428
  this.declaredTypes = declaredValueTypes(ir)
429
+ this.nullableSignalGetters = new Set([
430
+ ...collectNullableSignalGetters(ir),
431
+ ...memberSeededNilSignals(ir, this.declaredTypes, this.scope),
432
+ ])
447
433
  this.operandTyping = collectOperandTyping(ir.metadata, { namedFields: this.declaredTypes.namedFields })
448
434
  this.moduleStringConsts = collectModuleStringConsts(ir.metadata.localConstants)
449
435
  this._searchParamsLocals = searchParamsLocalNames(ir.metadata)
@@ -471,8 +457,20 @@ export abstract class DslTemplateAdapter extends BaseAdapter {
471
457
  if (!options?.siblingTemplatesRegistered) {
472
458
  this.errors.push(...collectImportedLoopChildComponentErrors(ir, this.componentName, this.loopChildDiagnosticName))
473
459
  }
474
- refuseAmbiguousNilMemoArithmetic(ir.metadata.memos ?? [], this.nullishAttrCtx, this.ambiguousNilSink())
475
460
  // `===` / `!==` over an object or array (#3774, #3824 step 8).
476
- refuseNonPrimitiveStrictEquality(ir, this.operandTyping, this.ambiguousNilSink())
461
+ refuseNonPrimitiveStrictEquality(ir, this.operandTyping, this.errorSink())
477
462
  }
478
463
  }
464
+
465
+ /**
466
+ * Getters of signals seeded from a member of a prop whose declared type
467
+ * admits `null` or `undefined` (`type Init = { label?: string }`,
468
+ * `createSignal(initial.label)`): the signal holds the field's JS value, so
469
+ * an attribute bound to it is omitted when that value is nullish, as for any
470
+ * other nullable signal (`collectNullableSignalGetters`).
471
+ */
472
+ function memberSeededNilSignals(ir: ComponentIR, types: DeclaredValueTypes, scope: BindingScope): string[] {
473
+ return (ir.metadata.signals ?? [])
474
+ .filter(s => s.parsed?.kind === 'member' && factsOfType(declaredValueType(types, s.parsed, scope)).types.has('nil'))
475
+ .map(s => s.getter)
476
+ }
@@ -67,6 +67,16 @@ export function loopRowType(
67
67
  return arrayElementType(type) ?? null
68
68
  }
69
69
 
70
+ /**
71
+ * The declared type of the value `expr` reads in `scope` (a prop, a member
72
+ * path below one, a loop row, a signal or memo getter), or null when the
73
+ * declarations do not say. An optional field below the root admits
74
+ * `undefined` (`loopValueTypeAt`).
75
+ */
76
+ export function declaredValueType(types: DeclaredValueTypes, expr: ParsedExpr, scope: BindingScope): LoopValueType | null {
77
+ return valueType(types, expr, scope)
78
+ }
79
+
70
80
  function valueType(types: DeclaredValueTypes, expr: ParsedExpr, scope: BindingScope): LoopValueType | null {
71
81
  switch (expr.kind) {
72
82
  case 'identifier': {
@@ -2,11 +2,12 @@
2
2
  * The nil-reading rewrite (`spec/js-primitive-semantics.md`, "Nil reading is
3
3
  * a tree rewrite"; #3824 step 4a in `spec/js-undefined-value.md`).
4
4
  *
5
- * Every runtime holds JS `null` and `undefined` as one nil, and its
6
- * primitive helpers (`to_number`, `to_string`, `plus`, the relational ones)
7
- * read that nil as `null`. Where Phase-1 types say which value a nil stands
8
- * for, and the consumer's coercion is known statically, the operand is
9
- * rewritten before planning so that it is never nil:
5
+ * Every runtime carries JS `null` and `undefined` as two values
6
+ * (`spec/js-undefined-value.md`), and its primitive helpers (`to_number`,
7
+ * `to_string`, `plus`, the relational ones) read each exactly. Where
8
+ * Phase-1 types say which value a nil stands for, and the consumer's
9
+ * coercion is known statically, the operand is rewritten before planning so
10
+ * that it is never nil:
10
11
  *
11
12
  * | Consumer | nil reads as `null` | nil reads as `undefined` |
12
13
  * | --- | --- | --- |
@@ -14,8 +15,7 @@
14
15
  * | string (`+` concatenation, template-literal part) | `x ?? 'null'` | `x ?? 'undefined'` |
15
16
  *
16
17
  * After the rewrite the operand is non-nil, so the plan can name the native
17
- * operator (`(n ?? NaN) * 2` stays native) and the helpers never need to
18
- * know about `undefined`.
18
+ * operator (`(n ?? NaN) * 2` stays native).
19
19
  *
20
20
  * A `+` whose present branch concatenates and whose nil branch adds
21
21
  * (`o.id + 1` with `id?: string`) is split on nil by the numeric row:
@@ -24,21 +24,16 @@
24
24
  * the runtime's `plus`, which decides per value. With a `null` reading the
25
25
  * nil branch is `0 + 1`, as JS's `null + 1`.
26
26
  *
27
- * What the rewrite leaves alone (`spec/js-undefined-value.md` §7 (4)):
27
+ * What the rewrite leaves alone, to the runtime's helpers, which read the
28
+ * value, `null` or `UNDEF`, exactly:
28
29
  *
29
- * - A numeric operand whose nil may be either (`n?: number | null`): the
30
- * template adapters refuse it with BF101 (#3700) where the coercion is
31
- * static, and keep today's output elsewhere.
30
+ * - An operand whose nil may be either (`n?: number | null`,
31
+ * `c?: string | null`).
32
32
  * - A `+` whose other operand is neither a proven number nor a proven
33
- * string: numeric addition or concatenation is decided at run time, and a
34
- * nil reading as `undefined` cannot be told from `null` there. It keeps
35
- * today's output (the runtime's `plus` reads the nil as `null`) until the
36
- * runtimes carry `undefined` (#3848).
37
- * - A string operand whose nil may be either (`c?: string | null`): it keeps
38
- * today's display reading, the empty string, until the runtimes carry
39
- * `undefined` (#3848).
40
- * - A nil Phase 1 cannot type (an index read, an untyped value): the
41
- * runtime's helpers read it as `null`.
33
+ * string: numeric addition or concatenation is decided at run time
34
+ * (the runtime's `plus`).
35
+ * - A nil Phase 1 cannot type (an index read, an untyped value): a missing
36
+ * key or an out-of-range index is `UNDEF`, data `null` is `null`.
42
37
  */
43
38
 
44
39
  import type { ParsedExpr, TemplatePart } from '../expression-parser.ts'
@@ -99,13 +94,13 @@ function numericOperand(operand: ParsedExpr, facts: OperandFacts): ParsedExpr {
99
94
  }
100
95
 
101
96
  /**
102
- * An operand of a string consumer: its nil as `'null'` / `'undefined'`, and
103
- * an `either` nil as today's display reading, the empty string (#3848).
97
+ * An operand of a string consumer: its nil as `'null'` / `'undefined'`; an
98
+ * `either` operand is left to the runtime's helper.
104
99
  */
105
100
  function stringOperand(operand: ParsedExpr, facts: OperandFacts): ParsedExpr {
106
101
  const reading = readingOf(facts)
107
- if (reading === null) return operand
108
- return coalesce(operand, facts, stringLiteral(reading === 'either' ? '' : reading))
102
+ if (reading === null || reading === 'either') return operand
103
+ return coalesce(operand, facts, stringLiteral(reading))
109
104
  }
110
105
 
111
106
  const PRIMITIVE_TYPES: ReadonlySet<string> = new Set(['number', 'string', 'boolean'])
@@ -143,7 +138,10 @@ function rewriteBinary(expr: Extract<ParsedExpr, { kind: 'binary' }>, typing: Sc
143
138
  return left === expr.left && right === expr.right ? expr : { ...expr, left, right }
144
139
  }
145
140
 
146
- function rewriteTemplateLiteral(expr: Extract<ParsedExpr, { kind: 'template-literal' }>, typing: ScopedOperandTyping): ParsedExpr {
141
+ function rewriteTemplateLiteral(
142
+ expr: Extract<ParsedExpr, { kind: 'template-literal' }>,
143
+ typing: ScopedOperandTyping,
144
+ ): ParsedExpr {
147
145
  let changed = false
148
146
  const parts: TemplatePart[] = expr.parts.map(part => {
149
147
  if (part.type !== 'expression') return part
@@ -10,7 +10,7 @@
10
10
  * therefore refuses the comparison with BF101, as the callback evaluator
11
11
  * contract already does (`spec/compiler.md`, "ParsedExpr Evaluator
12
12
  * Semantics"). A nullish test (`x === null`, `x === undefined`) is not a
13
- * strict equality and keeps the target's nil test.
13
+ * strict equality: it plans as the runtime's nil test.
14
14
  *
15
15
  * The primitive plan names the refusal per node (`mode: 'refuse'`), and
16
16
  * every emitter spells the runtime's `strict_eq` for it; the error itself
@@ -36,7 +36,7 @@
36
36
  import type { ParsedExpr, FlatDepth, TemplatePart, ObjectLiteralProperty } from '../expression-parser.ts'
37
37
  import { asCallbackMethodCall } from '../expression-parser.ts'
38
38
  import type { LoweringMatcher, LoweringNode } from '../lowering-registry.ts'
39
- import { booleanValueSites, foldNegatedNumberLiteral, planPrimitive, planToString, type PrimitiveInputs, type PrimitivePlan } from './primitive-plan.ts'
39
+ import { booleanValueSites, foldNegatedNumberLiteral, nilTestOperand, planPrimitive, planToString, refuseUnspelledNilTest, type NilTestHelper, type PrimitiveInputs, type PrimitivePlan } from './primitive-plan.ts'
40
40
  import { rewriteNilReadings, rewriteNilReadingsDeep } from './nil-reading.ts'
41
41
 
42
42
  export type HigherOrderMethod = 'filter' | 'every' | 'some' | 'find' | 'findIndex' | 'findLast' | 'findLastIndex'
@@ -185,6 +185,16 @@ export interface ParsedExprEmitter {
185
185
  plan: PrimitivePlan | null,
186
186
  ): string
187
187
  binary(op: string, left: ParsedExpr, right: ParsedExpr, emit: (e: ParsedExpr) => string, plan: PrimitivePlan | null): string
188
+ /**
189
+ * A nil-test plan (`spec/js-undefined-value.md`, "Decisions" (3) and (7)):
190
+ * on a target that carries `undefined`, `x === null`, `x === undefined`
191
+ * and the loose `x == null` plan as the runtime's `is_null`,
192
+ * `is_undefined` and `is_nullish` over `operand` (the side that is not the
193
+ * nil literal, {@link nilTestOperand}), `negated` for `!==` / `!=`. An
194
+ * emitter without it refuses the plan ({@link refuseUnspelledNilTest});
195
+ * only the emitter of a target that carries `undefined` receives one.
196
+ */
197
+ nilTest?(helper: NilTestHelper, negated: boolean, operand: ParsedExpr, emit: (e: ParsedExpr) => string): string
188
198
  unary(op: string, argument: ParsedExpr, emit: (e: ParsedExpr) => string, plan: PrimitivePlan | null): string
189
199
  logical(
190
200
  op: '&&' | '||' | '??',
@@ -547,6 +557,25 @@ export function withNilReadings(expr: ParsedExpr, emitter: Pick<ParsedExprEmitte
547
557
  return rewriteNilReadings(expr, emitter.primitives.typing())
548
558
  }
549
559
 
560
+ /**
561
+ * A `binary` node. A nil test (a target that carries `undefined`) goes to
562
+ * the emitter's `nilTest`; an emitter without one refuses it here, so no
563
+ * emitter's own `==` lowering sees it.
564
+ */
565
+ function dispatchBinary(
566
+ expr: Extract<ParsedExpr, { kind: 'binary' }>,
567
+ emitter: ParsedExprEmitter,
568
+ emit: (e: ParsedExpr) => string,
569
+ ): string {
570
+ const plan = primitivePlanFor(expr, emitter)
571
+ if (plan?.op === 'nil-test' && plan.mode === 'helper' && emitter.nilTest) {
572
+ const operand = nilTestOperand(expr.left, expr.right, emitter.primitives.typing())
573
+ return emitter.nilTest(plan.helper as NilTestHelper, expr.op === '!==' || expr.op === '!=', operand, emit)
574
+ }
575
+ refuseUnspelledNilTest(plan)
576
+ return emitter.binary(expr.op, expr.left, expr.right, emit, plan)
577
+ }
578
+
550
579
  /**
551
580
  * A callback's arrow with the nil-reading rewrite run over its whole body:
552
581
  * the body reaches the runtime evaluator (or the adapter's own predicate
@@ -609,7 +638,7 @@ function dispatchParsedExpr(
609
638
  case 'index-access':
610
639
  return emitter.indexAccess(expr.object, expr.index, emit, primitivePlanFor(expr, emitter))
611
640
  case 'binary':
612
- return emitter.binary(expr.op, expr.left, expr.right, emit, primitivePlanFor(expr, emitter))
641
+ return dispatchBinary(expr, emitter, emit)
613
642
  case 'unary': {
614
643
  // `-1.5` is the literal `-1.5` (#3824 step 6): a unary minus over a
615
644
  // non-zero number literal is spelled as the literal it folds into.
@@ -43,15 +43,16 @@ export type PrimitiveOp =
43
43
  | 'neg'
44
44
  | 'number-literal'
45
45
  | 'nullish'
46
+ | 'nil-test'
46
47
 
47
48
  /**
48
49
  * What Phase 1 proved about the operands of one operation.
49
50
  *
50
51
  * `unproven` is not in the design note's sketch: it is the proof of an
51
- * operation whose operands Phase 1 proves nothing about. A target that
52
- * spells its native operator for EVERY operand today (an "N" cell of the
53
- * note's status table) claims it, so the step-0 table can describe today's
54
- * output; each rollout step removes it from the table it graduates.
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.
55
56
  */
56
57
  export type Proof =
57
58
  | 'boolean'
@@ -65,8 +66,19 @@ export type Proof =
65
66
  | 'non-nil'
66
67
  | 'unproven'
67
68
 
68
- /** The (op, proof) pairs a target's native operators are pinned for. */
69
- export type NativeSafeTable = Readonly<Partial<Record<PrimitiveOp, readonly Proof[]>>>
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
70
82
 
71
83
  /**
72
84
  * The runtime helper a plan names, by its catalogue id
@@ -93,6 +105,14 @@ export type PrimitiveHelper =
93
105
  | 'coalesce'
94
106
  | 'get'
95
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'
96
116
 
97
117
  export type PrimitivePlan =
98
118
  | {
@@ -218,7 +238,17 @@ export function operandFacts(expr: ParsedExpr, typing: ScopedOperandTyping): Ope
218
238
  // ---------------------------------------------------------------------------
219
239
 
220
240
  function decide(op: PrimitiveOp, proof: Proof, target: NativeSafeTable, helper: PrimitiveHelper): PrimitivePlan {
221
- return target[op]?.includes(proof) ? { mode: 'native', op, proof } : { mode: 'helper', op, helper, proof }
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
222
252
  }
223
253
 
224
254
  /** A pair proof when both operands are proven the same non-nil primitive. */
@@ -249,6 +279,44 @@ export function isNullishTest(op: string, left: ParsedExpr, right: ParsedExpr, t
249
279
  (isNilLiteralOperand(left, typing) || isNilLiteralOperand(right, typing))
250
280
  }
251
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
+
252
320
  /** The array element reads whose value is one element of their receiver. */
253
321
  const ELEMENT_READ_METHODS: ReadonlySet<string> = new Set(['at', 'find', 'findLast'])
254
322
 
@@ -299,8 +367,10 @@ export const NON_PRIMITIVE_EQUALITY_REASON = 'non-primitive-strict-equality'
299
367
  * spells it too: the refusal itself is recorded once per component by
300
368
  * `refuseNonPrimitiveStrictEquality`.
301
369
  * - `const`: the folded answer for operands proven of different types.
302
- * - `nullish`: a nullish test (`x === null`), which keeps the target's nil
303
- * test.
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).
304
374
  *
305
375
  * Null for any other operator (loose `==` keeps its own lowering). A null
306
376
  * plan takes the helper, which is never wrong.
@@ -312,6 +382,7 @@ export type StrictEqSpelling =
312
382
  | { readonly kind: 'nullish' }
313
383
 
314
384
  export function strictEqSpelling(op: string, left: ParsedExpr, right: ParsedExpr, plan: PrimitivePlan | null): StrictEqSpelling | null {
385
+ refuseUnspelledNilTest(plan)
315
386
  if (op !== '===' && op !== '!==') return null
316
387
  if (isNilLiteralOperand(left) || isNilLiteralOperand(right)) return { kind: 'nullish' }
317
388
  const negated = op === '!=='
@@ -390,13 +461,13 @@ function planNumericBinary(op: string, left: OperandFacts, right: OperandFacts,
390
461
 
391
462
  function planBinary(expr: Extract<ParsedExpr, { kind: 'binary' }>, typing: ScopedOperandTyping, target: NativeSafeTable): PrimitivePlan | null {
392
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)
393
466
  const isPrimitiveOp = op === '===' || op === '!==' || op === '+' || op in RELATIONAL_HELPERS || op === '-' || op === '*' || op === '/' || op === '%'
394
467
  if (!isPrimitiveOp) return null
395
468
  const left = operandFacts(expr.left, typing)
396
469
  const right = operandFacts(expr.right, typing)
397
470
  if (op === '===' || op === '!==') {
398
- // `x === null` is a nullish test, lowered by each target's nil test.
399
- if (isNullishTest(op, expr.left, expr.right, typing)) return null
400
471
  if (mayHoldObject(expr.left, typing) || mayHoldObject(expr.right, typing)) {
401
472
  return { mode: 'refuse', op: 'strict-eq', reason: NON_PRIMITIVE_EQUALITY_REASON }
402
473
  }
@@ -464,9 +535,7 @@ function planUnary(expr: Extract<ParsedExpr, { kind: 'unary' }>, typing: ScopedO
464
535
  if (expr.op === '+') {
465
536
  // A unary `+` is ToNumber itself, and no target's native `+x` converts a
466
537
  // string (Python, Ruby and Java raise; Perl, Go and the PHP engines drop
467
- // it), so only a proven number is a claimable proof (#3824 step 3). The
468
- // table's `unproven` claim for `to-number` describes binary `-` / `*`
469
- // over unproven operands, which keep their native operator until step 4.
538
+ // it), so only a proven number is a claimable proof (#3824 step 3).
470
539
  return isExactly(operandFacts(expr.argument, typing), 'number')
471
540
  ? decide('to-number', 'number', target, 'to_number')
472
541
  : { mode: 'helper', op: 'to-number', helper: 'to_number', proof: 'unproven' }
@@ -571,7 +640,7 @@ export function numberLiteralSpelling(value: number, plan: PrimitivePlan | null)
571
640
  * non-computed member, …).
572
641
  *
573
642
  * Planned kinds: `binary` (`===` `!==` `<` `<=` `>` `>=` `+` `-` `*` `/`
574
- * `%`), `unary` (`!` `-` `+`), `logical` (its left operand's test, or `??`),
643
+ * `%`, and a nullish test with `==` / `!=` too, {@link planNilTest}), `unary` (`!` `-` `+`), `logical` (its left operand's test, or `??`),
575
644
  * `conditional` (its test), `index-access`, computed `member` and number
576
645
  * `literal`.
577
646
  */
@@ -5,7 +5,7 @@
5
5
  * adapter consults during lowering; no adapter instance state.
6
6
  */
7
7
 
8
- import type { ComponentIR } from '../types.ts'
8
+ import type { ComponentIR, TypeInfo } from '../types.ts'
9
9
 
10
10
  /**
11
11
  * Props whose declared TS type is boolean. A bare binding of one
@@ -26,15 +26,21 @@ export function collectBooleanTypedProps(ir: ComponentIR): Set<string> {
26
26
  * declared optional (#2259, e.g. textarea's `rows`). A bare reference to one
27
27
  * is absent (`None` / `nil` / `null` / `undef`) when the caller omits it, so
28
28
  * each adapter guards it with its own presence test before rendering.
29
+ *
30
+ * A destructure default applies to an absent or `undefined` prop only, so a
31
+ * defaulted prop whose declared type admits `null` is still `null` when the
32
+ * caller passes one (`spec/js-undefined-value.md`, "Decisions" (6)), and is
33
+ * guarded too.
29
34
  */
30
35
  export function collectNullableOptionalProps(ir: ComponentIR): Set<string> {
31
36
  return new Set([
32
37
  ...ir.metadata.propsParams
33
38
  .filter(
34
39
  p =>
35
- p.defaultValue === undefined &&
36
40
  !p.isRest &&
37
- (p.type?.kind !== 'primitive' || p.optional),
41
+ (p.defaultValue === undefined
42
+ ? p.type?.kind !== 'primitive' || p.optional
43
+ : admitsNull(p.declaredType ?? p.type)),
38
44
  )
39
45
  .map(p => p.name),
40
46
  // A closed-type `{...rest}` key (#3057) is never destructured with its
@@ -47,6 +53,13 @@ export function collectNullableOptionalProps(ir: ComponentIR): Set<string> {
47
53
  ])
48
54
  }
49
55
 
56
+ /** Whether a declared type admits `null` (`T | null`, or `null` itself). */
57
+ function admitsNull(type: TypeInfo | undefined): boolean {
58
+ if (!type) return false
59
+ if (type.kind === 'primitive') return type.primitive === 'null'
60
+ return type.kind === 'union' && (type.unionTypes ?? []).some(admitsNull)
61
+ }
62
+
50
63
  export interface BooleanTypedPropContext {
51
64
  /** The SolidJS-style props identifier (`function C(props: P)`), if any. */
52
65
  propsObjectName: string | null
package/src/analyzer.ts CHANGED
@@ -4803,9 +4803,10 @@ function collectKeysFromMembers(
4803
4803
  * same check, recursively. A same-file object type referenced by name
4804
4804
  * (`Item` in `items: Item[]`) is checked through its declaration's members
4805
4805
  * (`LocalObjectMemberTypes`) the same way an inline object literal's are.
4806
- * A union, a function, or any other named
4807
- * type reachable ANYWHERE inside the shape declines the WHOLE member (not
4808
- * just that one leaf): `collectMemberTypes` is an all-or-nothing gate per
4806
+ * A leaf typed `T | null` / `T | undefined` inside the shape resolves when
4807
+ * `T` does (`isNilUnionOfResolvable`). Any other union, a function, or any
4808
+ * other named type reachable ANYWHERE inside the shape declines the WHOLE
4809
+ * member (not just that one leaf): `collectMemberTypes` is an all-or-nothing gate per
4809
4810
  * member, so a partially-resolvable structural type must still decline —
4810
4811
  * per-field graceful degradation is `typeInfoToGo`'s job downstream, not
4811
4812
  * this gate's.
@@ -4832,8 +4833,9 @@ function isResolvableMemberType(
4832
4833
  info: TypeInfo,
4833
4834
  localObjectMembers?: LocalObjectMemberTypes,
4834
4835
  visiting: ReadonlySet<string> = new Set(),
4836
+ nested = false,
4835
4837
  ): boolean {
4836
- const recurse = (t: TypeInfo): boolean => isResolvableMemberType(t, localObjectMembers, visiting)
4838
+ const recurse = (t: TypeInfo): boolean => isResolvableMemberType(t, localObjectMembers, visiting, true)
4837
4839
  switch (info.kind) {
4838
4840
  case 'primitive':
4839
4841
  return info.primitive === 'string' || info.primitive === 'number' || info.primitive === 'boolean'
@@ -4847,18 +4849,35 @@ function isResolvableMemberType(
4847
4849
  const members = localObjectMembers(info.raw)
4848
4850
  if (!members) return false
4849
4851
  const inner = new Set(visiting).add(info.raw)
4850
- return members.every(t => isResolvableMemberType(t, localObjectMembers, inner))
4852
+ return members.every(t => isResolvableMemberType(t, localObjectMembers, inner, true))
4851
4853
  }
4852
4854
  case 'array':
4853
4855
  return !!info.elementType && recurse(info.elementType)
4854
4856
  case 'object':
4855
4857
  return info.properties !== undefined && info.properties.every(prop => recurse(prop.type))
4856
- // Unions, functions, and `unknown` all decline — see docstring.
4858
+ case 'union':
4859
+ // A field or element of a structural shape typed `T | null` /
4860
+ // `T | undefined` (`{ label?: string | null }`): the shape itself is
4861
+ // resolvable when `T` is, exactly as the `props`-object form already
4862
+ // resolves it. Every runtime carries `null` and `undefined` as values
4863
+ // (spec/js-undefined-value.md), and the field keeps its union type, so
4864
+ // a reader still sees that it may be nil. A top-level member typed
4865
+ // with a union still declines.
4866
+ return nested && isNilUnionOfResolvable(info, recurse)
4867
+ // Functions, other unions and `unknown` all decline — see docstring.
4857
4868
  default:
4858
4869
  return false
4859
4870
  }
4860
4871
  }
4861
4872
 
4873
+ /** A union of `null` / `undefined` with at least one other member, every other member resolvable. */
4874
+ function isNilUnionOfResolvable(info: TypeInfo, resolves: (t: TypeInfo) => boolean): boolean {
4875
+ const isNil = (t: TypeInfo) => t.kind === 'primitive' && (t.primitive === 'null' || t.primitive === 'undefined')
4876
+ const members = info.unionTypes ?? []
4877
+ const present = members.filter(t => !isNil(t))
4878
+ return present.length > 0 && present.length < members.length && present.every(resolves)
4879
+ }
4880
+
4862
4881
  /**
4863
4882
  * Member types of a same-file, non-generic object type declared by name —
4864
4883
  * an `interface` with no `extends` clause, or a `type X = { … }` alias —
@@ -4930,7 +4949,8 @@ function localObjectMemberTypesFor(ctx: AnalyzerContext): LocalObjectMemberTypes
4930
4949
  * - A member resolves a type when it is a PRIMITIVE (string/number/boolean),
4931
4950
  * a CATALOGUED rich type (`Date`), or a STRUCTURAL shape (array/object,
4932
4951
  * inline or a same-file object type referenced by name) built entirely
4933
- * out of those, recursively (#2677). Unions, functions, and other named
4952
+ * out of those, recursively (#2677), a field of one possibly typed
4953
+ * `T | null` / `T | undefined`. Other unions, functions, and other named
4934
4954
  * types (imports, generics, `Map`, `Set`, …) are left as `unknown` — see
4935
4955
  * `isResolvableMemberType`'s own docstring for why the structural cases
4936
4956
  * are safe to admit and why those three still are not.
package/src/index.ts CHANGED
@@ -9,7 +9,7 @@ export { compileJSX, buildMetadata } from './compiler.ts'
9
9
  export type { CompileResult, CompileOptions, CompileOptionsWithAdapter, FileOutput } from './compiler.ts'
10
10
 
11
11
  // SSR template-variable defaults (manifest seeds for stash-based adapters)
12
- export { extractSsrDefaults, deriveStashFromDefaults } from './ssr-defaults.ts'
12
+ export { extractSsrDefaults, deriveStashFromDefaults, encodeUndefinedMembers, decodeUndefinedMembers, UNDEFINED_SENTINEL } from './ssr-defaults.ts'
13
13
 
14
14
  // #3144: shared "is this a component-body local bound to an opaque call"
15
15
  // check, consulted by every non-JS-runtime adapter's `call()` fallback
@@ -134,10 +134,10 @@ export { emitParsedExpr, emitParsedValue, primitivePlanFor, arithmeticHelper, gr
134
134
  export type { StringNameTest } from './adapters/parsed-expr-emitter.ts'
135
135
  export { concatType, declaredValueTypes, loopRowType, type DeclaredValueTypes } from './adapters/loop-row-type.ts'
136
136
  export { collectNumberValueNames, isNumberValuedExpr, numberValuedSeedNames } from './adapters/number-value.ts'
137
- export { operandFacts, planPrimitive, planTest, spellTest, primitivesAt, isNativePlan, relationalHelper, isNativeToNumber, booleanValueSites, planTextDisplay, foldNegatedNumberLiteral, numberLiteralSpelling, isRuntimeNumberLiteral, plusSpelling, planToString, needsToString, strictEqSpelling, mayHoldObject, isNullishTest, isNilLiteralOperand, NON_PRIMITIVE_EQUALITY_REASON } from './adapters/primitive-plan.ts'
137
+ export { operandFacts, planPrimitive, planTest, spellTest, primitivesAt, isNativePlan, relationalHelper, isNativeToNumber, booleanValueSites, planTextDisplay, foldNegatedNumberLiteral, numberLiteralSpelling, isRuntimeNumberLiteral, plusSpelling, planToString, needsToString, strictEqSpelling, mayHoldObject, isNullishTest, isNilLiteralOperand, nilTestOperand, refuseUnspelledNilTest, NON_PRIMITIVE_EQUALITY_REASON } from './adapters/primitive-plan.ts'
138
138
  export { refuseNonPrimitiveStrictEquality, type NonPrimitiveEqualitySink } from './adapters/non-primitive-equality.ts'
139
139
  export { rewriteNilReadings, rewriteNilReadingsDeep, isNilReadingFallback, NAN_LITERAL } from './adapters/nil-reading.ts'
140
- export type { PrimitiveOp, Proof, NativeSafeTable, PrimitiveHelper, PrimitivePlan, PrimitiveInputs, TextDisplay, NumberLiteralSpelling, PlusSpelling, StrictEqSpelling } from './adapters/primitive-plan.ts'
140
+ export type { PrimitiveOp, Proof, NativeSafeClaims, NativeSafeTable, PrimitiveHelper, NilTestHelper, PrimitivePlan, PrimitiveInputs, TextDisplay, NumberLiteralSpelling, PlusSpelling, StrictEqSpelling } from './adapters/primitive-plan.ts'
141
141
  export {
142
142
  collectOperandTyping,
143
143
  EMPTY_OPERAND_TYPING,
@@ -157,12 +157,6 @@ export { collectLoopBoundNames } from './adapters/loop-bound-names.ts'
157
157
  export { planStyleObject, type StyleObjectPlanEntry } from './adapters/style-object.ts'
158
158
  export { filterCaptureCollisions } from './adapters/filter-capture-collisions.ts'
159
159
  export { templateNameCollisionErrors } from './adapters/template-name-collisions.ts'
160
- export {
161
- arithmeticCoercionOrRefuse,
162
- refuseAmbiguousNilArithmetic,
163
- refuseAmbiguousNilMemoArithmetic,
164
- type AmbiguousNilArithmeticSink,
165
- } from './adapters/ambiguous-nil-arithmetic.ts'
166
160
  export {
167
161
  collectBooleanValueNames,
168
162
  isAriaBooleanAttr,
@@ -204,6 +198,7 @@ export type {
204
198
  CallbackLoweringOptions,
205
199
  CallbackPlan,
206
200
  EvalBody,
201
+ NilReadingSite,
207
202
  PredicateMethod,
208
203
  SortPlan,
209
204
  } from './adapters/callback-method.ts'
@@ -241,8 +236,6 @@ export {
241
236
  arithmeticOperandIsNull,
242
237
  arithmeticOperandIsUndefined,
243
238
  arithmeticOperandCoercion,
244
- arithmeticOperandNilIsAmbiguous,
245
- ambiguousNilArithmeticOperands,
246
239
  bareGetterCallName,
247
240
  attrValueMayBeNullish,
248
241
  collectAbsentPropSeedReads,