@barefootjs/jsx 0.39.4 → 0.39.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/adapters/array-method.d.ts +93 -0
  2. package/dist/adapters/array-method.d.ts.map +1 -0
  3. package/dist/adapters/attr-plan.d.ts +135 -0
  4. package/dist/adapters/attr-plan.d.ts.map +1 -0
  5. package/dist/adapters/boolean-result.d.ts +84 -9
  6. package/dist/adapters/boolean-result.d.ts.map +1 -1
  7. package/dist/adapters/callback-method.d.ts +126 -0
  8. package/dist/adapters/callback-method.d.ts.map +1 -0
  9. package/dist/adapters/component-props.d.ts +99 -0
  10. package/dist/adapters/component-props.d.ts.map +1 -0
  11. package/dist/adapters/component-tree.d.ts +25 -0
  12. package/dist/adapters/component-tree.d.ts.map +1 -0
  13. package/dist/adapters/filter-capture-collisions.d.ts +17 -0
  14. package/dist/adapters/filter-capture-collisions.d.ts.map +1 -0
  15. package/dist/adapters/literal-value.d.ts +22 -0
  16. package/dist/adapters/literal-value.d.ts.map +1 -0
  17. package/dist/adapters/loop-plan.d.ts +53 -0
  18. package/dist/adapters/loop-plan.d.ts.map +1 -0
  19. package/dist/adapters/parsed-expr-emitter.d.ts +8 -0
  20. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  21. package/dist/adapters/prop-classes.d.ts +37 -0
  22. package/dist/adapters/prop-classes.d.ts.map +1 -0
  23. package/dist/adapters/template-name-collisions.d.ts +21 -0
  24. package/dist/adapters/template-name-collisions.d.ts.map +1 -0
  25. package/dist/analyzer-context.d.ts.map +1 -1
  26. package/dist/expression-parser.d.ts +48 -0
  27. package/dist/expression-parser.d.ts.map +1 -1
  28. package/dist/index.d.ts +20 -4
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +2077 -1000
  31. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +8 -0
  33. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts +3 -2
  35. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/utils.d.ts +39 -1
  39. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  40. package/dist/jsx-to-ir.d.ts +465 -1
  41. package/dist/jsx-to-ir.d.ts.map +1 -1
  42. package/dist/nullable-signal-attr.d.ts +31 -0
  43. package/dist/nullable-signal-attr.d.ts.map +1 -1
  44. package/dist/scope/binding-scope.d.ts +10 -0
  45. package/dist/scope/binding-scope.d.ts.map +1 -1
  46. package/dist/types.d.ts +7 -0
  47. package/dist/types.d.ts.map +1 -1
  48. package/package.json +2 -2
  49. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +1 -1
  50. package/src/__tests__/action-accessor.test.ts +6 -24
  51. package/src/__tests__/array-method-catalogue.test.ts +99 -0
  52. package/src/__tests__/attr-plan.test.ts +121 -0
  53. package/src/__tests__/binding-scope-ratchet.test.ts +13 -13
  54. package/src/__tests__/binding-scope.test.ts +11 -0
  55. package/src/__tests__/boolean-result-expr.test.ts +106 -0
  56. package/src/__tests__/boolean-result.test.ts +34 -1
  57. package/src/__tests__/callback-method.test.ts +189 -0
  58. package/src/__tests__/compile-without-node-process.test.ts +78 -0
  59. package/src/__tests__/component-props.test.ts +148 -0
  60. package/src/__tests__/delegated-handler-preamble.test.ts +4 -4
  61. package/src/__tests__/doc-examples.test.ts +1 -0
  62. package/src/__tests__/dsl-shared-helpers.test.ts +166 -0
  63. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +1 -1
  64. package/src/__tests__/loop-plan.test.ts +104 -0
  65. package/src/__tests__/map-call-decisions.test.ts +521 -0
  66. package/src/__tests__/nested-row-shadowing.test.ts +57 -0
  67. package/src/__tests__/nullable-signal-attr.test.ts +45 -0
  68. package/src/__tests__/rename-free-identifiers.test.ts +26 -0
  69. package/src/__tests__/template-name-collisions.test.ts +81 -0
  70. package/src/adapters/array-method.ts +193 -0
  71. package/src/adapters/attr-plan.ts +200 -0
  72. package/src/adapters/boolean-result.ts +208 -12
  73. package/src/adapters/callback-method.ts +301 -0
  74. package/src/adapters/component-props.ts +144 -0
  75. package/src/adapters/component-tree.ts +118 -0
  76. package/src/adapters/filter-capture-collisions.ts +29 -0
  77. package/src/adapters/literal-value.ts +36 -0
  78. package/src/adapters/loop-plan.ts +88 -0
  79. package/src/adapters/parsed-expr-emitter.ts +18 -0
  80. package/src/adapters/prop-classes.ts +73 -0
  81. package/src/adapters/template-name-collisions.ts +120 -0
  82. package/src/analyzer-context.ts +15 -1
  83. package/src/expression-parser.ts +569 -374
  84. package/src/index.ts +58 -3
  85. package/src/ir-to-client-js/collect-elements.ts +11 -7
  86. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +31 -10
  87. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +12 -5
  88. package/src/ir-to-client-js/control-flow/plan/build-reactive-effects.ts +2 -2
  89. package/src/ir-to-client-js/control-flow/shared.ts +4 -1
  90. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +9 -7
  91. package/src/ir-to-client-js/html-template.ts +13 -7
  92. package/src/ir-to-client-js/index.ts +7 -2
  93. package/src/ir-to-client-js/utils.ts +81 -7
  94. package/src/jsx-to-ir.ts +1328 -991
  95. package/src/nullable-signal-attr.ts +116 -6
  96. package/src/scope/binding-scope.ts +19 -0
  97. package/src/types.ts +7 -0
@@ -868,6 +868,52 @@ export const CALLBACK_METHODS: ReadonlySet<string> = new Set([
868
868
  'sort', 'toSorted', 'reduce', 'reduceRight', 'flatMap',
869
869
  ])
870
870
 
871
+ /**
872
+ * Who binds a callback's params. `'template'`: the adapter lowers the call to
873
+ * an evaluator helper (`map_eval`, `sort_eval`, …) or a native form. In
874
+ * `'evaluator'`: the call sits inside such a callback's body, and the runtime
875
+ * evaluator runs it itself, binding a nested `.map` / `.filter` callback's
876
+ * `(item, index)` (`eval-reference.ts`, #2094).
877
+ */
878
+ export type CallbackScope = 'template' | 'evaluator'
879
+
880
+ /**
881
+ * How many leading callback params the DSL runtimes bind, per
882
+ * {@link CALLBACK_METHODS} member and {@link CallbackScope}: a comparator's
883
+ * `(a, b)`, a reducer's `(acc, item)`, a nested `.map` / `.filter`'s
884
+ * `(item, index)`, every other callback's element. The params after them (the
885
+ * element index, the array itself) have no binding.
886
+ */
887
+ function evaluatorBoundParamCount(method: string, scope: CallbackScope): number {
888
+ if (method === 'sort' || method === 'toSorted' || method === 'reduce' || method === 'reduceRight') return 2
889
+ return scope === 'evaluator' && (method === 'map' || method === 'filter') ? 2 : 1
890
+ }
891
+
892
+ /**
893
+ * The first callback param past {@link evaluatorBoundParamCount} that the
894
+ * callback body reads (`items.map((x, i) => i)` → `'i'`), or `null` when the
895
+ * body reads none of them. A DSL adapter would otherwise resolve such a name
896
+ * from the enclosing SSR scope, or leave it undefined, instead of the index /
897
+ * array the JS reference binds. A body this walk cannot analyze counts as
898
+ * reading the first extra param, so the check fails safe.
899
+ */
900
+ export function unboundCallbackParamRead(
901
+ method: string,
902
+ arrow: Extract<ParsedExpr, { kind: 'arrow' }>,
903
+ scope: CallbackScope = 'template',
904
+ ): string | null {
905
+ const extra = arrow.params.slice(evaluatorBoundParamCount(method, scope))
906
+ if (extra.length === 0) return null
907
+ const free = freeIdentifiers(arrow.body)
908
+ if (free === null) return extra[0]!
909
+ return extra.find(name => free.has(name)) ?? null
910
+ }
911
+
912
+ /** The refusal reason for {@link unboundCallbackParamRead}'s finding. */
913
+ export function unboundCallbackParamReason(method: string, name: string): string {
914
+ return `'.${method}()' callback reads '${name}', its index or array parameter, which a template evaluator does not bind. Pre-compute the value, or add /* @client */ for client-only (no SSR).`
915
+ }
916
+
871
917
  /**
872
918
  * A recognised higher-order callback method call: `<object>.<method>(<arrow>,
873
919
  * …rest)` where `method ∈` {@link CALLBACK_METHODS} and the first argument is a
@@ -942,345 +988,26 @@ function convertNode(node: ts.Node, raw: string): ParsedExpr {
942
988
  if (ts.isCallExpression(node)) {
943
989
  const callee = convertNode(node.expression, raw)
944
990
  const args = node.arguments.map(arg => convertNode(arg, raw))
945
-
946
- // Higher-order callback methods (`.filter`/`.find`/`.every`/`.some`/
947
- // `.sort`/`.reduce`/`.flatMap`/…) are NOT folded here (#2018 P5): they
948
- // flow through as a generic `call` whose argument is a generic `arrow`,
949
- // and the adapter recognises the callback shape at dispatch and serializes
950
- // the arrow body to the runtime evaluator. The one exception is the
951
- // non-arrow `.filter(Boolean)` callable: synthesise the equivalent
952
- // identity arrow `_ => _` so it flows through the same callback lowering
953
- // (the adapter keeps a dedicated truthiness fallback for the identity body).
954
- if (
955
- callee.kind === 'member' &&
956
- !callee.computed &&
957
- callee.property === 'filter' &&
958
- args.length === 1 &&
959
- args[0].kind === 'identifier' &&
960
- args[0].name === 'Boolean'
961
- ) {
991
+ // `recv?.method(args)` is `undefined` when `recv` is nullish (#3435).
992
+ // The lowerings below (an `array-method` node above all) model a plain
993
+ // call, so the optional hop becomes an explicit guard every adapter
994
+ // already lowers: `recv === null || recv === undefined ? undefined :
995
+ // recv.method(args)`. Strict comparisons: several backends compare a
996
+ // loose `== null` as falsy-equal, which would swallow a present `0`.
997
+ if (callee.kind === 'member' && callee.optional) {
962
998
  return {
963
- kind: 'call',
964
- callee,
965
- args: [{ kind: 'arrow', params: ['_'], body: { kind: 'identifier', name: '_' } }],
966
- }
967
- }
968
-
969
- // Non-higher-order array methods (#1443). Lifting these into an
970
- // `array-method` IR node — instead of detecting at each adapter's
971
- // `call()` emitter — keeps the abstraction at the IR layer where
972
- // it belongs: an array supports `.join`, and the per-target
973
- // lowering is the adapter's choice. Adding `.concat` / `.slice` /
974
- // etc. later means widening the IR discriminator, not adding more
975
- // branches to every adapter's call dispatch.
976
- if (callee.kind === 'member' && !callee.computed) {
977
- // `.join()` / `.join(sep)` — JS defaults the separator to `,` when
978
- // omitted and ignores any extra arguments. Accept every arity; the
979
- // adapters supply the default separator and read only `args[0]`.
980
- if (callee.property === 'join') {
981
- return { kind: 'array-method', method: 'join', object: callee.object, args }
982
- }
983
- // `.includes(x)` — shared between `Array.prototype.includes` and
984
- // `String.prototype.includes`. The parser can't tell the receiver
985
- // type without TS inference, so both shapes lower through the
986
- // same IR node and each adapter dispatches at the runtime level
987
- // (`bf_includes` on Go uses `reflect.Kind()`; `$bf->includes`
988
- // on Mojo uses `ref()`). See #1448 Tier A.
989
- if (callee.property === 'includes' && args.length === 1) {
990
- return { kind: 'array-method', method: 'includes', object: callee.object, args }
991
- }
992
- // `.indexOf(x)` / `.lastIndexOf(x)` — value-equality search,
993
- // both adapters dispatch through a runtime helper that walks
994
- // the slice (forward / backward) and compares with `DeepEqual`
995
- // (Go) / `eq` (Perl). The existing `bf_find_index` (Go)
996
- // operates on struct-field equality and stays — see the
997
- // higher-order `.find` lowering. See #1448 Tier A.
998
- if ((callee.property === 'indexOf' || callee.property === 'lastIndexOf') && args.length === 1) {
999
- return { kind: 'array-method', method: callee.property, object: callee.object, args }
1000
- }
1001
- // `.at(i)` — negative-index support (`.at(-1)` is the last
1002
- // element). Go has `bf_at` registered already (see runtime
1003
- // FuncMap); Mojo's `bf->at` wraps the same arithmetic.
1004
- // See #1448 Tier A.
1005
- // `.at(i)` — JS ignores any argument past the first, and `.at()`
1006
- // with no argument is `.at(0)` (the first element). Accept every
1007
- // arity; the adapters read `args[0]` (defaulting the index to 0).
1008
- if (callee.property === 'at') {
1009
- return { kind: 'array-method', method: 'at', object: callee.object, args }
1010
- }
1011
- // `.concat()` / `.concat(other)` — `.concat()` returns a shallow
1012
- // copy (indistinguishable from the receiver in an SSR snapshot),
1013
- // and `.concat(other)` merges the two arrays. Go uses `bf_concat`
1014
- // (reflect-based append into `[]any`); Mojo uses `bf->concat`
1015
- // (Perl list builder). The VARIADIC form (`.concat(a, b, …)`) is
1016
- // not lowered yet — it's refused by the guard below rather than
1017
- // silently dropping the extra arrays.
1018
- if (callee.property === 'concat' && args.length <= 1) {
1019
- return { kind: 'array-method', method: 'concat', object: callee.object, args }
1020
- }
1021
- // `.slice()` / `.slice(start)` / `.slice(start, end)` — route
1022
- // through `bf_slice` (Go) / `bf->slice` (Mojo). A missing `start`
1023
- // defaults to 0 (full copy), a missing / undef `end` means "to
1024
- // length", and JS ignores any third+ argument. Accept every arity;
1025
- // the adapters read only `args[0]` / `args[1]`.
1026
- if (callee.property === 'slice') {
1027
- return { kind: 'array-method', method: 'slice', object: callee.object, args }
1028
- }
1029
- // `.reverse()` and `.toReversed()` — both zero-arg shapes
1030
- // share the runtime lowering. SSR templates render a snapshot
1031
- // of state, so JS's mutate-and-return-receiver (`reverse`)
1032
- // vs return-new-array (`toReversed`) distinction has no
1033
- // template-level meaning; both produce a new reversed array.
1034
- // JS takes no argument and ignores any that are passed.
1035
- if (callee.property === 'reverse' || callee.property === 'toReversed') {
1036
- return { kind: 'array-method', method: callee.property, object: callee.object, args }
1037
- }
1038
- // `.flat(depth?)` — flatten nested arrays `depth` levels deep
1039
- // (default 1). The depth is validated to a literal and normalised
1040
- // into a structured `FlatDepth` here: `Infinity` becomes the
1041
- // full-depth form, a 0 / negative JS depth normalises to 0 ("no
1042
- // flatten" → shallow copy), and a fractional literal truncates
1043
- // toward zero (JS ToIntegerOrInfinity). A NON-literal depth can't be
1044
- // resolved at template time, so it refuses with BF101 rather than
1045
- // emitting a broken helper call. Go uses `bf_flat`; Mojo uses
1046
- // `bf->flat`. See #1448 Tier C.
1047
- if (callee.property === 'flat') {
1048
- const depthNode = node.arguments[0]
1049
- let flatDepth: FlatDepth
1050
- let depthExpr: ParsedExpr | undefined
1051
- if (depthNode === undefined) {
1052
- flatDepth = 1
1053
- } else if (ts.isIdentifier(depthNode) && depthNode.text === 'Infinity') {
1054
- flatDepth = 'infinity'
1055
- } else {
1056
- let n: number | undefined
1057
- if (ts.isNumericLiteral(depthNode)) {
1058
- n = Number(depthNode.text)
1059
- } else if (
1060
- ts.isPrefixUnaryExpression(depthNode) &&
1061
- depthNode.operator === ts.SyntaxKind.MinusToken &&
1062
- ts.isNumericLiteral(depthNode.operand)
1063
- ) {
1064
- n = -Number(depthNode.operand.text)
1065
- }
1066
- if (n === undefined || Number.isNaN(n)) {
1067
- // Not a literal — try a DYNAMIC depth: an expression that
1068
- // itself resolves to a supported `ParsedExpr` (a numeric prop,
1069
- // signal read, arithmetic, …) can be lowered through a runtime
1070
- // helper that coerces it at render time (JS
1071
- // `ToIntegerOrInfinity`; see the `depthExpr` doc on the
1072
- // `array-method`/`flat` type). Still refuse with BF101 when
1073
- // the depth expression itself is outside the supported
1074
- // surface — the depth must be *expressible*, even if not
1075
- // known until render time.
1076
- const parsedDepth = convertNode(depthNode, raw)
1077
- if (checkSupport(parsedDepth, 'rendered', []).supported) {
1078
- depthExpr = parsedDepth
1079
- flatDepth = 1 // unused placeholder — consumers must check `depthExpr` first
1080
- } else {
1081
- return {
1082
- kind: 'unsupported',
1083
- raw,
1084
- reason: `\`.flat(depth)\` needs a literal integer, \`Infinity\`, or a supported dynamic depth expression — this depth can't be resolved. Use a literal depth, a supported expression (prop/signal/arithmetic), or pre-compute the value before the template.`,
1085
- }
1086
- }
1087
- } else {
1088
- const truncated = Math.trunc(n)
1089
- flatDepth = truncated < 0 ? 0 : truncated
1090
- }
1091
- }
1092
- return depthExpr !== undefined
1093
- ? { kind: 'array-method', method: 'flat', object: callee.object, args: [], flatDepth, depthExpr }
1094
- : { kind: 'array-method', method: 'flat', object: callee.object, args: [], flatDepth }
1095
- }
1096
- // `.toLowerCase()` — string-only (the IR carries a value-builtin
1097
- // tag, not a receiver-type discriminator, so the `array-method`
1098
- // label is a misnomer for string methods but the mechanical
1099
- // pipeline matches). Go uses the existing `bf_lower` helper;
1100
- // Mojo uses Perl's native `lc`. See #1448 Tier A.
1101
- if (callee.property === 'toLowerCase') {
1102
- return { kind: 'array-method', method: 'toLowerCase', object: callee.object, args }
1103
- }
1104
- // `.toUpperCase()` — Go uses the existing `bf_upper` helper;
1105
- // Mojo uses Perl's native `uc`.
1106
- if (callee.property === 'toUpperCase') {
1107
- return { kind: 'array-method', method: 'toUpperCase', object: callee.object, args }
1108
- }
1109
- // `.trim()` — Go uses the existing `bf_trim` helper; Mojo uses
1110
- // a new `bf->trim` method that mirrors JS's "strip leading +
1111
- // trailing whitespace" semantic via a Perl regex.
1112
- if (callee.property === 'trim') {
1113
- return { kind: 'array-method', method: 'trim', object: callee.object, args }
1114
- }
1115
- // `.trimStart()` / `.trimEnd()` — the one-sided siblings of
1116
- // `.trim()` (#2183 follow-up). No array equivalent exists, so
1117
- // there's no receiver-type ambiguity to resolve (unlike `.slice`);
1118
- // each is a dedicated `array-method` variant (matching the
1119
- // `padStart`/`padEnd` precedent — separate members, not a shared
1120
- // member with a `side` flag) lowering to its own runtime helper
1121
- // per adapter, not `.trim()` with a flag.
1122
- if (callee.property === 'trimStart' || callee.property === 'trimEnd') {
1123
- return { kind: 'array-method', method: callee.property, object: callee.object, args }
1124
- }
1125
- // `.toFixed(digits?)` — Number → fixed-decimal string. The digit
1126
- // count (default 0) travels as the single arg; all adapters route
1127
- // through a `to_fixed` runtime helper (Perl) / `fmt.Sprintf` (Go)
1128
- // so JS's rounding + zero-padding semantics match. #1897
1129
- // (data-table's `payment.amount.toFixed(2)`).
1130
- if (callee.property === 'toFixed') {
1131
- return { kind: 'array-method', method: 'toFixed', object: callee.object, args }
1132
- }
1133
- // `.split()` / `.split(sep)` / `.split(sep, limit)` — string →
1134
- // array, full JS arity. `.split()` (no separator) returns the
1135
- // whole string as a single element; `.split(sep)` splits on the
1136
- // (literal) separator; the optional `limit` caps the number of
1137
- // pieces. JS ignores a third+ argument. Go uses `bf_split`
1138
- // (`strings.Split`, optional limit, normalised to `[]any`) and
1139
- // `bf_arr` for the no-separator whole-string case; Mojo uses
1140
- // `bf->split`. The regex-separator form stays refused (the parser
1141
- // never reaches here for it — a regex literal arg is `unsupported`
1142
- // and propagates). See #1448 Tier B.
1143
- if (callee.property === 'split') {
1144
- return { kind: 'array-method', method: 'split', object: callee.object, args }
1145
- }
1146
- // Arity guard for the forms whose EXTRA argument changes the
1147
- // result and is not yet lowered: the `fromIndex` of `.includes` /
1148
- // `.indexOf` / `.lastIndexOf` (the 2-arg form), and the additional
1149
- // arrays of a variadic `.concat(a, b, …)`. Silently dropping those
1150
- // would make the SSR output *differ* from the client (worse than a
1151
- // build error), so they refuse with BF101 until lowered. (The
1152
- // single-argument forms, zero-arg defaults, and JS-ignored
1153
- // trailing arguments of every method are accepted by the relaxed
1154
- // arms above.) See #1448.
1155
- if (LOWERED_ARRAY_METHODS.has(callee.property)) {
1156
- const argName = callee.property === 'concat' ? 'other' : 'x'
1157
- const detail =
1158
- callee.property === 'concat'
1159
- ? 'the variadic `.concat(a, b, …)` form'
1160
- : `\`.${callee.property}(…)\` with ${args.length} argument(s)`
1161
- return {
1162
- kind: 'unsupported',
1163
- raw,
1164
- reason: `${detail} is not yet lowered to the Go/Mojo template adapters. Use the single-argument \`.${callee.property}(${argName})\` form, or pre-compute the value before the template.`,
1165
- }
1166
- }
1167
- // `.startsWith(search, position?)` / `.endsWith(search, endPosition?)`
1168
- // — string → boolean, full JS arity. Go uses `bf_starts_with` /
1169
- // `bf_ends_with` (wrapping `strings.HasPrefix` / `strings.HasSuffix`,
1170
- // with an optional position that re-anchors the comparison); Mojo
1171
- // uses `bf->starts_with` / `bf->ends_with` (substr comparison). JS
1172
- // ignores a third+ argument. The zero-arg form (`.startsWith()`) is
1173
- // refused: JS coerces the missing search to the literal string
1174
- // "undefined", a degenerate result not worth lowering (mirrors the
1175
- // `.includes()` zero-arg refusal). See #1448 Tier B.
1176
- if (callee.property === 'startsWith' || callee.property === 'endsWith') {
1177
- if (args.length === 0) {
1178
- return {
1179
- kind: 'unsupported',
1180
- raw,
1181
- reason: `\`.${callee.property}()\` with no search string is not lowered — JS coerces the missing argument to the string "undefined", a degenerate result. Pass an explicit search string, or pre-compute the value before the template.`,
1182
- }
1183
- }
1184
- return { kind: 'array-method', method: callee.property, object: callee.object, args }
1185
- }
1186
- // `.replace(pattern, replacement)` — string-pattern form,
1187
- // replacing the FIRST occurrence (JS semantics for a string
1188
- // pattern). Go uses `bf_replace` (`strings.Replace` with n=1);
1189
- // Mojo uses `bf->replace` (index/substr splice, no regex). A
1190
- // regex-literal pattern is the deferred form — its `regex` first
1191
- // arg is carried STRUCTURALLY (not collapsed to `unsupported`) so
1192
- // the Go ctor lowering can recover the one trailing-slash pattern
1193
- // it supports without re-parsing (#2039). Template use stays
1194
- // refused: `isSupported` maps a regex-pattern `.replace` to the
1195
- // deferred-form BF101 reason — the Perl `s///` vs Go
1196
- // `regexp.ReplaceAllString` flavour gap is the open design
1197
- // question in #1448. `.replaceAll(pattern, replacement)` shares
1198
- // this arm (#2182 follow-up): same arity/regex/object-literal
1199
- // gates, only the `method` tag and its runtime helper differ —
1200
- // `bf_replace_all` (Go, `strings.ReplaceAll`) / `bf->replace_all`
1201
- // (Mojo) replace EVERY occurrence, where `.replace`'s helpers
1202
- // replace only the first.
1203
- //
1204
- // Full JS arity: a third+ argument is ignored (the adapter reads
1205
- // only the pattern + replacement). The one- and zero-argument
1206
- // forms are refused: JS coerces the missing replacement (and
1207
- // pattern) to the literal string "undefined", a degenerate result
1208
- // (mirrors the `.includes()` / `.startsWith()` zero-arg refusal).
1209
- if (callee.property === 'replace' || callee.property === 'replaceAll') {
1210
- const method = callee.property
1211
- if (args.length < 2) {
1212
- return {
1213
- kind: 'unsupported',
1214
- raw,
1215
- reason: `\`.${method}(${args.length === 0 ? '' : 'pattern'})\` needs both a pattern and a replacement — JS coerces the missing argument to the string "undefined", a degenerate result. Pass both arguments, or pre-compute the value before the template.`,
1216
- }
1217
- }
1218
- // A regex-literal pattern is the deferred form (the Perl `s///`
1219
- // vs Go `regexp.ReplaceAllString` flavour gap, #1448). Its shape
1220
- // is carried structurally — `args[0]` is a `regex` node (convertNode
1221
- // line ~1127) — so a consumer that recognises one fixed pattern (the
1222
- // Go ctor's `/\/+$/` trailing-slash strip → `strings.TrimRight`) reads
1223
- // it from the tree instead of re-parsing the raw (#2039). Returned
1224
- // before the object-literal `badArg` check below so the regex form
1225
- // keeps its dedicated diagnostic precedence; `isSupported` then refuses
1226
- // any template use with the deferred-form reason.
1227
- const patternNode = node.arguments[0]
1228
- if (patternNode && ts.isRegularExpressionLiteral(patternNode)) {
1229
- return { kind: 'array-method', method, object: callee.object, args }
1230
- }
1231
- // Treat an object-literal argument like `unsupported` — a `.replace`
1232
- // with an object pattern/replacement isn't lowerable, same as before
1233
- // the `object-literal` kind existed (byte-identical; Roadmap A-1).
1234
- const badArg =
1235
- args[0].kind === 'unsupported' || args[0].kind === 'object-literal'
1236
- ? args[0]
1237
- : args[1].kind === 'unsupported' || args[1].kind === 'object-literal'
1238
- ? args[1]
1239
- : undefined
1240
- if (badArg) {
1241
- const reason = badArg.kind === 'unsupported' ? badArg.reason : 'Unsupported syntax: ObjectLiteralExpression'
1242
- return { kind: 'unsupported', raw, reason }
1243
- }
1244
- return { kind: 'array-method', method, object: callee.object, args }
1245
- }
1246
- // `.repeat(n)` — string → string (the receiver concatenated `n`
1247
- // times). Go uses `bf_repeat` (`strings.Repeat`, clamping a
1248
- // negative count to "" instead of panicking); Mojo uses
1249
- // `bf->repeat` (Perl's `x` operator). JS throws RangeError for a
1250
- // negative count, but SSR templates degrade to the empty string
1251
- // rather than crashing the render. See #1448 Tier B.
1252
- // Full JS arity: `.repeat()` (no count) is `repeat(0)` → "" (JS
1253
- // coerces the missing count to 0, not a RangeError), and a
1254
- // second+ argument is ignored. The adapter supplies the `0` for
1255
- // the no-argument form. See #1448 Tier B.
1256
- if (callee.property === 'repeat') {
1257
- return { kind: 'array-method', method: 'repeat', object: callee.object, args }
1258
- }
1259
- // `.padStart(target, pad?)` / `.padEnd(target, pad?)` — string →
1260
- // string, padded to `target` length with `pad` (default a single
1261
- // space) repeated + truncated to fill. Go uses `bf_pad_start` /
1262
- // `bf_pad_end`; Mojo uses `bf->pad_start` / `bf->pad_end`. Both
1263
- // count length in code points (Go runes / Perl chars) so they
1264
- // stay byte-equal — this differs from JS's UTF-16-unit length
1265
- // only for astral-plane receivers, which are vanishingly rare in
1266
- // numeric / space padding. See #1448 Tier B.
1267
- // Full JS arity: `.padStart()` (no target) is `padStart(0)` → the
1268
- // receiver unchanged (JS coerces the missing target to 0), and a
1269
- // third+ argument is ignored. The adapter supplies the `0` for the
1270
- // no-argument form and reads only target + padString.
1271
- if (callee.property === 'padStart' || callee.property === 'padEnd') {
1272
- return { kind: 'array-method', method: callee.property, object: callee.object, args }
999
+ kind: 'conditional',
1000
+ test: {
1001
+ kind: 'logical',
1002
+ op: '||',
1003
+ left: { kind: 'binary', op: '===', left: callee.object, right: { kind: 'literal', value: null, literalType: 'null' } },
1004
+ right: { kind: 'binary', op: '===', left: callee.object, right: { kind: 'identifier', name: 'undefined' } },
1005
+ },
1006
+ consequent: { kind: 'identifier', name: 'undefined' },
1007
+ alternate: convertCallExpression(node, raw, { ...callee, optional: false }, args),
1273
1008
  }
1274
- // `.sort` / `.toSorted` / `.reduce` / `.reduceRight` / `.flatMap`
1275
- // (callback methods) are NOT folded here (#2018 P5): they fall through
1276
- // to the generic `call` construction below (callee = member, arg =
1277
- // generic `arrow`), and the adapter serializes the arrow body to the
1278
- // runtime evaluator. The localeCompare-sort fallback recovers a
1279
- // structured comparator from the generic arrow via
1280
- // `sortComparatorFromArrow`.
1281
1009
  }
1282
-
1283
- return { kind: 'call', callee, args }
1010
+ return convertCallExpression(node, raw, callee, args)
1284
1011
  }
1285
1012
 
1286
1013
  // Array literal: [a, b, c]
@@ -2475,6 +2202,45 @@ export function isSupportedValue(
2475
2202
  return checkSupport(expr, 'value', opts?.loweringMatchers ?? [])
2476
2203
  }
2477
2204
 
2205
+ /**
2206
+ * {@link checkSupport} for a higher-order callback method call (`<recv>.<m>(arrow,
2207
+ * …rest)`): the receiver, the callback's params (an index or array param it
2208
+ * reads has no binding in the {@link CallbackScope} it runs in), its body, and
2209
+ * the trailing args. The body runs in the evaluator, so a callback nested in
2210
+ * it is checked in `'evaluator'` scope.
2211
+ */
2212
+ function checkCallbackMethodSupport(
2213
+ cb: NonNullable<ReturnType<typeof asCallbackMethodCall>>,
2214
+ pos: ExprPos,
2215
+ matchers: readonly LoweringMatcher[],
2216
+ scope: CallbackScope,
2217
+ ): SupportResult {
2218
+ const objSupport = checkSupport(cb.object, pos, matchers, scope)
2219
+ if (!objSupport.supported) return objSupport
2220
+ const unbound = unboundCallbackParamRead(cb.method, cb.arrow, scope)
2221
+ if (unbound !== null) {
2222
+ return {
2223
+ supported: false,
2224
+ level: 'L5_UNSUPPORTED',
2225
+ selfContained: true,
2226
+ reason: unboundCallbackParamReason(cb.method, unbound),
2227
+ }
2228
+ }
2229
+ const bodySupport = checkSupport(cb.arrow.body, pos, matchers, 'evaluator')
2230
+ if (!bodySupport.supported) {
2231
+ return {
2232
+ supported: false,
2233
+ level: 'L5_UNSUPPORTED',
2234
+ reason: `Higher-order method '.${cb.method}()' with complex callback. ${bodySupport.reason || 'Simplify the callback.'}`,
2235
+ }
2236
+ }
2237
+ for (const rest of cb.args) {
2238
+ const restSupport = checkSupport(rest, pos, matchers, scope)
2239
+ if (!restSupport.supported) return restSupport
2240
+ }
2241
+ return { supported: true, level: 'L5' }
2242
+ }
2243
+
2478
2244
  /**
2479
2245
  * Where in the expression tree a node sits, for the ONE shape whose support
2480
2246
  * depends on it: `object-literal` (refused at `rendered`, admitted at `value`
@@ -2492,7 +2258,12 @@ export function isSupportedValue(
2492
2258
  */
2493
2259
  type ExprPos = 'rendered' | 'value'
2494
2260
 
2495
- function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly LoweringMatcher[]): SupportResult {
2261
+ function checkSupport(
2262
+ expr: ParsedExpr,
2263
+ pos: ExprPos,
2264
+ matchers: readonly LoweringMatcher[],
2265
+ scope: CallbackScope = 'template',
2266
+ ): SupportResult {
2496
2267
  switch (expr.kind) {
2497
2268
  case 'unsupported':
2498
2269
  return { supported: false, reason: expr.reason }
@@ -2510,7 +2281,7 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2510
2281
  // A spread entry's SOURCE must itself be supported at `value`
2511
2282
  // position — the same criterion as an explicit property's value,
2512
2283
  // since the spread source is read (not rendered) at merge time.
2513
- const propSupport = checkSupport(prop.kind === 'spread' ? prop.expr : prop.value, pos, matchers)
2284
+ const propSupport = checkSupport(prop.kind === 'spread' ? prop.expr : prop.value, pos, matchers, scope)
2514
2285
  if (!propSupport.supported) return propSupport
2515
2286
  }
2516
2287
  return { supported: true, level: 'L2' }
@@ -2537,7 +2308,7 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2537
2308
  // method, not here, because we can't see which adapter is consuming
2538
2309
  // the IR at this point.
2539
2310
  for (const el of expr.elements) {
2540
- const elSupport = checkSupport(el, pos, matchers)
2311
+ const elSupport = checkSupport(el, pos, matchers, scope)
2541
2312
  if (!elSupport.supported) return elSupport
2542
2313
  }
2543
2314
  return { supported: true, level: 'L2' }
@@ -2557,10 +2328,10 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2557
2328
  }
2558
2329
  }
2559
2330
  // Receiver/args inherit `pos` (see `ExprPos`'s doc).
2560
- const objSupport = checkSupport(expr.object, pos, matchers)
2331
+ const objSupport = checkSupport(expr.object, pos, matchers, scope)
2561
2332
  if (!objSupport.supported) return objSupport
2562
2333
  for (const arg of expr.args) {
2563
- const argSupport = checkSupport(arg, pos, matchers)
2334
+ const argSupport = checkSupport(arg, pos, matchers, scope)
2564
2335
  if (!argSupport.supported) return argSupport
2565
2336
  }
2566
2337
  // A dynamic `.flat(depth)` carries its depth expression outside
@@ -2571,7 +2342,7 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2571
2342
  // any `array-method`/`flat` node regardless of how it was constructed
2572
2343
  // (e.g. by a rewrite walker).
2573
2344
  if (expr.method === 'flat' && expr.depthExpr) {
2574
- const depthSupport = checkSupport(expr.depthExpr, pos, matchers)
2345
+ const depthSupport = checkSupport(expr.depthExpr, pos, matchers, scope)
2575
2346
  if (!depthSupport.supported) return depthSupport
2576
2347
  }
2577
2348
  return { supported: true, level: 'L2' }
@@ -2593,7 +2364,7 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2593
2364
  const node = matcher(expr.callee, expr.args)
2594
2365
  if (!node) continue
2595
2366
  for (const child of loweringNodeChildren(node)) {
2596
- const childSupport = checkSupport(child, pos, matchers)
2367
+ const childSupport = checkSupport(child, pos, matchers, scope)
2597
2368
  if (!childSupport.supported) return childSupport
2598
2369
  }
2599
2370
  return { supported: true, level: 'L2' }
@@ -2615,27 +2386,11 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2615
2386
  // (the body value is what ends up rendered), while a VALUE-entered
2616
2387
  // one (a signal/memo initializer) admits it.
2617
2388
  const cb = asCallbackMethodCall(expr)
2618
- if (cb) {
2619
- const objSupport = checkSupport(cb.object, pos, matchers)
2620
- if (!objSupport.supported) return objSupport
2621
- const bodySupport = checkSupport(cb.arrow.body, pos, matchers)
2622
- if (!bodySupport.supported) {
2623
- return {
2624
- supported: false,
2625
- level: 'L5_UNSUPPORTED',
2626
- reason: `Higher-order method '.${cb.method}()' with complex callback. ${bodySupport.reason || 'Simplify the callback.'}`,
2627
- }
2628
- }
2629
- for (const rest of cb.args) {
2630
- const restSupport = checkSupport(rest, pos, matchers)
2631
- if (!restSupport.supported) return restSupport
2632
- }
2633
- return { supported: true, level: 'L5' }
2634
- }
2389
+ if (cb) return checkCallbackMethodSupport(cb, pos, matchers, scope)
2635
2390
 
2636
2391
  // Check if callee is supported. Not container contents — inherits
2637
2392
  // the CURRENT `pos` (see `ExprPos`'s doc).
2638
- const calleeSupport = checkSupport(expr.callee, pos, matchers)
2393
+ const calleeSupport = checkSupport(expr.callee, pos, matchers, scope)
2639
2394
  if (!calleeSupport.supported) {
2640
2395
  return calleeSupport
2641
2396
  }
@@ -2668,7 +2423,7 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2668
2423
  // recognised callback/array-method (that path returned above) —
2669
2424
  // inherits the CURRENT `pos` (see `ExprPos`'s doc).
2670
2425
  for (const arg of expr.args) {
2671
- const argSupport = checkSupport(arg, pos, matchers)
2426
+ const argSupport = checkSupport(arg, pos, matchers, scope)
2672
2427
  if (!argSupport.supported) {
2673
2428
  return argSupport
2674
2429
  }
@@ -2678,7 +2433,7 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2678
2433
 
2679
2434
  case 'member': {
2680
2435
  // Not container contents — inherits the CURRENT `pos`.
2681
- const objSupport = checkSupport(expr.object, pos, matchers)
2436
+ const objSupport = checkSupport(expr.object, pos, matchers, scope)
2682
2437
  if (!objSupport.supported) {
2683
2438
  return objSupport
2684
2439
  }
@@ -2694,9 +2449,9 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2694
2449
  // expression are themselves supported (the index is typically a
2695
2450
  // loop variable or arithmetic over one). #1897 (data-table). Neither
2696
2451
  // is container contents — both inherit the CURRENT `pos`.
2697
- const objSupport = checkSupport(expr.object, pos, matchers)
2452
+ const objSupport = checkSupport(expr.object, pos, matchers, scope)
2698
2453
  if (!objSupport.supported) return objSupport
2699
- const indexSupport = checkSupport(expr.index, pos, matchers)
2454
+ const indexSupport = checkSupport(expr.index, pos, matchers, scope)
2700
2455
  if (!indexSupport.supported) return indexSupport
2701
2456
  return { supported: true, level: 'L2' }
2702
2457
  }
@@ -2704,9 +2459,9 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2704
2459
  case 'binary': {
2705
2460
  // Operands inherit the CURRENT `pos` (see `ExprPos`'s doc) — a binary
2706
2461
  // operand isn't container contents.
2707
- const leftSupport = checkSupport(expr.left, pos, matchers)
2462
+ const leftSupport = checkSupport(expr.left, pos, matchers, scope)
2708
2463
  if (!leftSupport.supported) return leftSupport
2709
- const rightSupport = checkSupport(expr.right, pos, matchers)
2464
+ const rightSupport = checkSupport(expr.right, pos, matchers, scope)
2710
2465
  if (!rightSupport.supported) return rightSupport
2711
2466
 
2712
2467
  // Comparison operators are L3
@@ -2724,7 +2479,7 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2724
2479
 
2725
2480
  case 'unary': {
2726
2481
  // Inherits the CURRENT `pos` — not container contents.
2727
- const argSupport = checkSupport(expr.argument, pos, matchers)
2482
+ const argSupport = checkSupport(expr.argument, pos, matchers, scope)
2728
2483
  if (!argSupport.supported) return argSupport
2729
2484
 
2730
2485
  // Negation is L4
@@ -2741,7 +2496,7 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2741
2496
 
2742
2497
  case 'logical': {
2743
2498
  // Operands inherit the CURRENT `pos` — not container contents.
2744
- const leftSupport = checkSupport(expr.left, pos, matchers)
2499
+ const leftSupport = checkSupport(expr.left, pos, matchers, scope)
2745
2500
  if (!leftSupport.supported) return leftSupport
2746
2501
 
2747
2502
  // `x ?? {}` — admit an EMPTY object-literal fallback as the right
@@ -2768,7 +2523,7 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2768
2523
  return { supported: true, level: 'L4' }
2769
2524
  }
2770
2525
 
2771
- const rightSupport = checkSupport(expr.right, pos, matchers)
2526
+ const rightSupport = checkSupport(expr.right, pos, matchers, scope)
2772
2527
  if (!rightSupport.supported) return rightSupport
2773
2528
 
2774
2529
  return { supported: true, level: 'L4' }
@@ -2780,11 +2535,11 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2780
2535
  // position both branches are themselves rendered — `cond ? {a:1} :
2781
2536
  // {b:2}` stays refused there, not admitted just for being a
2782
2537
  // sub-expression.
2783
- const testSupport = checkSupport(expr.test, pos, matchers)
2538
+ const testSupport = checkSupport(expr.test, pos, matchers, scope)
2784
2539
  if (!testSupport.supported) return testSupport
2785
- const consSupport = checkSupport(expr.consequent, pos, matchers)
2540
+ const consSupport = checkSupport(expr.consequent, pos, matchers, scope)
2786
2541
  if (!consSupport.supported) return consSupport
2787
- const altSupport = checkSupport(expr.alternate, pos, matchers)
2542
+ const altSupport = checkSupport(expr.alternate, pos, matchers, scope)
2788
2543
  if (!altSupport.supported) return altSupport
2789
2544
 
2790
2545
  return { supported: true, level: 'L4' }
@@ -2796,7 +2551,7 @@ function checkSupport(expr: ParsedExpr, pos: ExprPos, matchers: readonly Lowerin
2796
2551
  // object-literal hole has no sensible rendering either way).
2797
2552
  for (const part of expr.parts) {
2798
2553
  if (part.type === 'expression') {
2799
- const partSupport = checkSupport(part.expr, pos, matchers)
2554
+ const partSupport = checkSupport(part.expr, pos, matchers, scope)
2800
2555
  if (!partSupport.supported) return partSupport
2801
2556
  }
2802
2557
  }
@@ -3801,6 +3556,38 @@ export function freeVarsInBody(body: ParsedExpr, params: ReadonlySet<string>): s
3801
3556
  return [...found].sort()
3802
3557
  }
3803
3558
 
3559
+ /**
3560
+ * `expr` with each free reference to a name in `renames` replaced by its
3561
+ * mapped name. An `arrow` param of the same name shadows the rename inside
3562
+ * its body; string literals, member property names and object-literal keys
3563
+ * are never touched, because they are not `identifier` nodes. Used to point a
3564
+ * `.filter()` predicate's captured enclosing names at loop-scoped aliases
3565
+ * before an adapter emits it, so target-language name mangling still applies
3566
+ * (#3402).
3567
+ */
3568
+ export function renameFreeIdentifiers(expr: ParsedExpr, renames: ReadonlyMap<string, string>): ParsedExpr {
3569
+ if (renames.size === 0) return expr
3570
+ const walk = (value: unknown, active: ReadonlyMap<string, string>): unknown => {
3571
+ if (Array.isArray(value)) return value.map(v => walk(v, active))
3572
+ if (value === null || typeof value !== 'object') return value
3573
+ const node = value as { kind?: unknown } & Record<string, unknown>
3574
+ if (node.kind === 'identifier' && typeof node.name === 'string') {
3575
+ const renamed = active.get(node.name)
3576
+ return renamed === undefined ? node : { ...node, name: renamed }
3577
+ }
3578
+ let inner = active
3579
+ if (node.kind === 'arrow' && Array.isArray(node.params)) {
3580
+ const shadowed = new Map(active)
3581
+ for (const p of node.params as string[]) shadowed.delete(p)
3582
+ inner = shadowed
3583
+ }
3584
+ const out: Record<string, unknown> = {}
3585
+ for (const [k, v] of Object.entries(node)) out[k] = walk(v, inner)
3586
+ return out
3587
+ }
3588
+ return walk(expr, renames) as ParsedExpr
3589
+ }
3590
+
3804
3591
  /**
3805
3592
  * Every value-position identifier in `expr` NOT bound by an enclosing arrow's
3806
3593
  * own parameters — with proper lexical scoping: an arrow's params bind only
@@ -3927,6 +3714,71 @@ function evalBuiltinCalleeName(callee: ParsedExpr): string | null {
3927
3714
  return null
3928
3715
  }
3929
3716
 
3717
+ /**
3718
+ * Whether `expr` calls something a DSL predicate emitter has no lowering for:
3719
+ * a call that is neither an evaluator builtin (`String(x)`, `Math.abs(x)`), a
3720
+ * zero-arg signal getter (`limit()`), nor a higher-order callback method. A
3721
+ * filter emitter lowers such a call to a read of its callee
3722
+ * (`x.localeCompare('m')` → `x.localeCompare`, `isOk(x)` → `isOk`), so the
3723
+ * native predicate fallback must not take it (#3477).
3724
+ */
3725
+ export function hasOpaqueCall(expr: ParsedExpr): boolean {
3726
+ let found = false
3727
+ const visit = (node: unknown): void => {
3728
+ if (found || node === null || typeof node !== 'object') return
3729
+ if (Array.isArray(node)) {
3730
+ node.forEach(visit)
3731
+ return
3732
+ }
3733
+ const e = node as ParsedExpr
3734
+ if (e.kind === 'call') {
3735
+ const cb = asCallbackMethodCall(e)
3736
+ if (cb) {
3737
+ visit(cb.object)
3738
+ visit(cb.arrow.body)
3739
+ cb.args.forEach(visit)
3740
+ return
3741
+ }
3742
+ const getter = e.callee.kind === 'identifier' && e.args.length === 0
3743
+ if (!getter && evalBuiltinCalleeName(e.callee) === null) {
3744
+ found = true
3745
+ return
3746
+ }
3747
+ e.args.forEach(visit)
3748
+ return
3749
+ }
3750
+ for (const value of Object.values(e)) visit(value)
3751
+ }
3752
+ visit(expr)
3753
+ return found
3754
+ }
3755
+
3756
+ /**
3757
+ * Whether a callback nested anywhere in `expr` reads a param past the one a
3758
+ * native form binds (`row.filter((x, i) => i > 0)`): Ruby blocks and Perl
3759
+ * `grep` bind the element only, while the runtime evaluator also binds a
3760
+ * nested `.map` / `.filter` index (`CallbackScope`). A predicate that does
3761
+ * must not take a native form.
3762
+ */
3763
+ export function readsNestedCallbackIndex(expr: ParsedExpr): boolean {
3764
+ let found = false
3765
+ const visit = (node: unknown): void => {
3766
+ if (found || node === null || typeof node !== 'object') return
3767
+ if (Array.isArray(node)) {
3768
+ node.forEach(visit)
3769
+ return
3770
+ }
3771
+ const cb = (node as ParsedExpr).kind === 'call' ? asCallbackMethodCall(node as ParsedExpr) : null
3772
+ if (cb && unboundCallbackParamRead(cb.method, cb.arrow) !== null) {
3773
+ found = true
3774
+ return
3775
+ }
3776
+ for (const value of Object.values(node)) visit(value)
3777
+ }
3778
+ visit(expr)
3779
+ return found
3780
+ }
3781
+
3930
3782
  /** Build the evaluator's minimal node object, or null for an out-of-surface kind. */
3931
3783
  function toEvalNode(e: ParsedExpr): Record<string, unknown> | null {
3932
3784
  switch (e.kind) {
@@ -4129,3 +3981,346 @@ export function identifierPath(callee: ParsedExpr): string | null {
4129
3981
  }
4130
3982
  return null
4131
3983
  }
3984
+
3985
+ /** A call expression `node` with its converted `callee` and `args` (see `convertNode`). */
3986
+ function convertCallExpression(node: ts.CallExpression, raw: string, callee: ParsedExpr, args: ParsedExpr[]): ParsedExpr {
3987
+
3988
+ // Higher-order callback methods (`.filter`/`.find`/`.every`/`.some`/
3989
+ // `.sort`/`.reduce`/`.flatMap`/…) are NOT folded here (#2018 P5): they
3990
+ // flow through as a generic `call` whose argument is a generic `arrow`,
3991
+ // and the adapter recognises the callback shape at dispatch and serializes
3992
+ // the arrow body to the runtime evaluator. The one exception is the
3993
+ // non-arrow `.filter(Boolean)` callable: synthesise the equivalent
3994
+ // identity arrow `_ => _` so it flows through the same callback lowering
3995
+ // (the adapter keeps a dedicated truthiness fallback for the identity body).
3996
+ if (
3997
+ callee.kind === 'member' &&
3998
+ !callee.computed &&
3999
+ callee.property === 'filter' &&
4000
+ args.length === 1 &&
4001
+ args[0].kind === 'identifier' &&
4002
+ args[0].name === 'Boolean'
4003
+ ) {
4004
+ return {
4005
+ kind: 'call',
4006
+ callee,
4007
+ args: [{ kind: 'arrow', params: ['_'], body: { kind: 'identifier', name: '_' } }],
4008
+ }
4009
+ }
4010
+
4011
+ // Non-higher-order array methods (#1443). Lifting these into an
4012
+ // `array-method` IR node — instead of detecting at each adapter's
4013
+ // `call()` emitter — keeps the abstraction at the IR layer where
4014
+ // it belongs: an array supports `.join`, and the per-target
4015
+ // lowering is the adapter's choice. Adding `.concat` / `.slice` /
4016
+ // etc. later means widening the IR discriminator, not adding more
4017
+ // branches to every adapter's call dispatch.
4018
+ if (callee.kind === 'member' && !callee.computed) {
4019
+ // `.join()` / `.join(sep)` — JS defaults the separator to `,` when
4020
+ // omitted and ignores any extra arguments. Accept every arity; the
4021
+ // adapters supply the default separator and read only `args[0]`.
4022
+ if (callee.property === 'join') {
4023
+ return { kind: 'array-method', method: 'join', object: callee.object, args }
4024
+ }
4025
+ // `.includes(x)` — shared between `Array.prototype.includes` and
4026
+ // `String.prototype.includes`. The parser can't tell the receiver
4027
+ // type without TS inference, so both shapes lower through the
4028
+ // same IR node and each adapter dispatches at the runtime level
4029
+ // (`bf_includes` on Go uses `reflect.Kind()`; `$bf->includes`
4030
+ // on Mojo uses `ref()`). See #1448 Tier A.
4031
+ if (callee.property === 'includes' && args.length === 1) {
4032
+ return { kind: 'array-method', method: 'includes', object: callee.object, args }
4033
+ }
4034
+ // `.indexOf(x)` / `.lastIndexOf(x)` — value-equality search,
4035
+ // both adapters dispatch through a runtime helper that walks
4036
+ // the slice (forward / backward) and compares with `DeepEqual`
4037
+ // (Go) / `eq` (Perl). The existing `bf_find_index` (Go)
4038
+ // operates on struct-field equality and stays — see the
4039
+ // higher-order `.find` lowering. See #1448 Tier A.
4040
+ if ((callee.property === 'indexOf' || callee.property === 'lastIndexOf') && args.length === 1) {
4041
+ return { kind: 'array-method', method: callee.property, object: callee.object, args }
4042
+ }
4043
+ // `.at(i)` — negative-index support (`.at(-1)` is the last
4044
+ // element). Go has `bf_at` registered already (see runtime
4045
+ // FuncMap); Mojo's `bf->at` wraps the same arithmetic.
4046
+ // See #1448 Tier A.
4047
+ // `.at(i)` — JS ignores any argument past the first, and `.at()`
4048
+ // with no argument is `.at(0)` (the first element). Accept every
4049
+ // arity; the adapters read `args[0]` (defaulting the index to 0).
4050
+ if (callee.property === 'at') {
4051
+ return { kind: 'array-method', method: 'at', object: callee.object, args }
4052
+ }
4053
+ // `.concat()` / `.concat(other)` — `.concat()` returns a shallow
4054
+ // copy (indistinguishable from the receiver in an SSR snapshot),
4055
+ // and `.concat(other)` merges the two arrays. Go uses `bf_concat`
4056
+ // (reflect-based append into `[]any`); Mojo uses `bf->concat`
4057
+ // (Perl list builder). The VARIADIC form (`.concat(a, b, …)`) is
4058
+ // not lowered yet — it's refused by the guard below rather than
4059
+ // silently dropping the extra arrays.
4060
+ if (callee.property === 'concat' && args.length <= 1) {
4061
+ return { kind: 'array-method', method: 'concat', object: callee.object, args }
4062
+ }
4063
+ // `.slice()` / `.slice(start)` / `.slice(start, end)` — route
4064
+ // through `bf_slice` (Go) / `bf->slice` (Mojo). A missing `start`
4065
+ // defaults to 0 (full copy), a missing / undef `end` means "to
4066
+ // length", and JS ignores any third+ argument. Accept every arity;
4067
+ // the adapters read only `args[0]` / `args[1]`.
4068
+ if (callee.property === 'slice') {
4069
+ return { kind: 'array-method', method: 'slice', object: callee.object, args }
4070
+ }
4071
+ // `.reverse()` and `.toReversed()` — both zero-arg shapes
4072
+ // share the runtime lowering. SSR templates render a snapshot
4073
+ // of state, so JS's mutate-and-return-receiver (`reverse`)
4074
+ // vs return-new-array (`toReversed`) distinction has no
4075
+ // template-level meaning; both produce a new reversed array.
4076
+ // JS takes no argument and ignores any that are passed.
4077
+ if (callee.property === 'reverse' || callee.property === 'toReversed') {
4078
+ return { kind: 'array-method', method: callee.property, object: callee.object, args }
4079
+ }
4080
+ // `.flat(depth?)` — flatten nested arrays `depth` levels deep
4081
+ // (default 1). The depth is validated to a literal and normalised
4082
+ // into a structured `FlatDepth` here: `Infinity` becomes the
4083
+ // full-depth form, a 0 / negative JS depth normalises to 0 ("no
4084
+ // flatten" → shallow copy), and a fractional literal truncates
4085
+ // toward zero (JS ToIntegerOrInfinity). A NON-literal depth can't be
4086
+ // resolved at template time, so it refuses with BF101 rather than
4087
+ // emitting a broken helper call. Go uses `bf_flat`; Mojo uses
4088
+ // `bf->flat`. See #1448 Tier C.
4089
+ if (callee.property === 'flat') {
4090
+ const depthNode = node.arguments[0]
4091
+ let flatDepth: FlatDepth
4092
+ let depthExpr: ParsedExpr | undefined
4093
+ if (depthNode === undefined) {
4094
+ flatDepth = 1
4095
+ } else if (ts.isIdentifier(depthNode) && depthNode.text === 'Infinity') {
4096
+ flatDepth = 'infinity'
4097
+ } else {
4098
+ let n: number | undefined
4099
+ if (ts.isNumericLiteral(depthNode)) {
4100
+ n = Number(depthNode.text)
4101
+ } else if (
4102
+ ts.isPrefixUnaryExpression(depthNode) &&
4103
+ depthNode.operator === ts.SyntaxKind.MinusToken &&
4104
+ ts.isNumericLiteral(depthNode.operand)
4105
+ ) {
4106
+ n = -Number(depthNode.operand.text)
4107
+ }
4108
+ if (n === undefined || Number.isNaN(n)) {
4109
+ // Not a literal — try a DYNAMIC depth: an expression that
4110
+ // itself resolves to a supported `ParsedExpr` (a numeric prop,
4111
+ // signal read, arithmetic, …) can be lowered through a runtime
4112
+ // helper that coerces it at render time (JS
4113
+ // `ToIntegerOrInfinity`; see the `depthExpr` doc on the
4114
+ // `array-method`/`flat` type). Still refuse with BF101 when
4115
+ // the depth expression itself is outside the supported
4116
+ // surface — the depth must be *expressible*, even if not
4117
+ // known until render time.
4118
+ const parsedDepth = convertNode(depthNode, raw)
4119
+ if (checkSupport(parsedDepth, 'rendered', []).supported) {
4120
+ depthExpr = parsedDepth
4121
+ flatDepth = 1 // unused placeholder — consumers must check `depthExpr` first
4122
+ } else {
4123
+ return {
4124
+ kind: 'unsupported',
4125
+ raw,
4126
+ reason: `\`.flat(depth)\` needs a literal integer, \`Infinity\`, or a supported dynamic depth expression — this depth can't be resolved. Use a literal depth, a supported expression (prop/signal/arithmetic), or pre-compute the value before the template.`,
4127
+ }
4128
+ }
4129
+ } else {
4130
+ const truncated = Math.trunc(n)
4131
+ flatDepth = truncated < 0 ? 0 : truncated
4132
+ }
4133
+ }
4134
+ return depthExpr !== undefined
4135
+ ? { kind: 'array-method', method: 'flat', object: callee.object, args: [], flatDepth, depthExpr }
4136
+ : { kind: 'array-method', method: 'flat', object: callee.object, args: [], flatDepth }
4137
+ }
4138
+ // `.toLowerCase()` — string-only (the IR carries a value-builtin
4139
+ // tag, not a receiver-type discriminator, so the `array-method`
4140
+ // label is a misnomer for string methods but the mechanical
4141
+ // pipeline matches). Go uses the existing `bf_lower` helper;
4142
+ // Mojo uses Perl's native `lc`. See #1448 Tier A.
4143
+ if (callee.property === 'toLowerCase') {
4144
+ return { kind: 'array-method', method: 'toLowerCase', object: callee.object, args }
4145
+ }
4146
+ // `.toUpperCase()` — Go uses the existing `bf_upper` helper;
4147
+ // Mojo uses Perl's native `uc`.
4148
+ if (callee.property === 'toUpperCase') {
4149
+ return { kind: 'array-method', method: 'toUpperCase', object: callee.object, args }
4150
+ }
4151
+ // `.trim()` — Go uses the existing `bf_trim` helper; Mojo uses
4152
+ // a new `bf->trim` method that mirrors JS's "strip leading +
4153
+ // trailing whitespace" semantic via a Perl regex.
4154
+ if (callee.property === 'trim') {
4155
+ return { kind: 'array-method', method: 'trim', object: callee.object, args }
4156
+ }
4157
+ // `.trimStart()` / `.trimEnd()` — the one-sided siblings of
4158
+ // `.trim()` (#2183 follow-up). No array equivalent exists, so
4159
+ // there's no receiver-type ambiguity to resolve (unlike `.slice`);
4160
+ // each is a dedicated `array-method` variant (matching the
4161
+ // `padStart`/`padEnd` precedent — separate members, not a shared
4162
+ // member with a `side` flag) lowering to its own runtime helper
4163
+ // per adapter, not `.trim()` with a flag.
4164
+ if (callee.property === 'trimStart' || callee.property === 'trimEnd') {
4165
+ return { kind: 'array-method', method: callee.property, object: callee.object, args }
4166
+ }
4167
+ // `.toFixed(digits?)` — Number → fixed-decimal string. The digit
4168
+ // count (default 0) travels as the single arg; all adapters route
4169
+ // through a `to_fixed` runtime helper (Perl) / `fmt.Sprintf` (Go)
4170
+ // so JS's rounding + zero-padding semantics match. #1897
4171
+ // (data-table's `payment.amount.toFixed(2)`).
4172
+ if (callee.property === 'toFixed') {
4173
+ return { kind: 'array-method', method: 'toFixed', object: callee.object, args }
4174
+ }
4175
+ // `.split()` / `.split(sep)` / `.split(sep, limit)` — string →
4176
+ // array, full JS arity. `.split()` (no separator) returns the
4177
+ // whole string as a single element; `.split(sep)` splits on the
4178
+ // (literal) separator; the optional `limit` caps the number of
4179
+ // pieces. JS ignores a third+ argument. Go uses `bf_split`
4180
+ // (`strings.Split`, optional limit, normalised to `[]any`) and
4181
+ // `bf_arr` for the no-separator whole-string case; Mojo uses
4182
+ // `bf->split`. The regex-separator form stays refused (the parser
4183
+ // never reaches here for it — a regex literal arg is `unsupported`
4184
+ // and propagates). See #1448 Tier B.
4185
+ if (callee.property === 'split') {
4186
+ return { kind: 'array-method', method: 'split', object: callee.object, args }
4187
+ }
4188
+ // Arity guard for the forms whose EXTRA argument changes the
4189
+ // result and is not yet lowered: the `fromIndex` of `.includes` /
4190
+ // `.indexOf` / `.lastIndexOf` (the 2-arg form), and the additional
4191
+ // arrays of a variadic `.concat(a, b, …)`. Silently dropping those
4192
+ // would make the SSR output *differ* from the client (worse than a
4193
+ // build error), so they refuse with BF101 until lowered. (The
4194
+ // single-argument forms, zero-arg defaults, and JS-ignored
4195
+ // trailing arguments of every method are accepted by the relaxed
4196
+ // arms above.) See #1448.
4197
+ if (LOWERED_ARRAY_METHODS.has(callee.property)) {
4198
+ const argName = callee.property === 'concat' ? 'other' : 'x'
4199
+ const detail =
4200
+ callee.property === 'concat'
4201
+ ? 'the variadic `.concat(a, b, …)` form'
4202
+ : `\`.${callee.property}(…)\` with ${args.length} argument(s)`
4203
+ return {
4204
+ kind: 'unsupported',
4205
+ raw,
4206
+ reason: `${detail} is not yet lowered to the Go/Mojo template adapters. Use the single-argument \`.${callee.property}(${argName})\` form, or pre-compute the value before the template.`,
4207
+ }
4208
+ }
4209
+ // `.startsWith(search, position?)` / `.endsWith(search, endPosition?)`
4210
+ // — string → boolean, full JS arity. Go uses `bf_starts_with` /
4211
+ // `bf_ends_with` (wrapping `strings.HasPrefix` / `strings.HasSuffix`,
4212
+ // with an optional position that re-anchors the comparison); Mojo
4213
+ // uses `bf->starts_with` / `bf->ends_with` (substr comparison). JS
4214
+ // ignores a third+ argument. The zero-arg form (`.startsWith()`) is
4215
+ // refused: JS coerces the missing search to the literal string
4216
+ // "undefined", a degenerate result not worth lowering (mirrors the
4217
+ // `.includes()` zero-arg refusal). See #1448 Tier B.
4218
+ if (callee.property === 'startsWith' || callee.property === 'endsWith') {
4219
+ if (args.length === 0) {
4220
+ return {
4221
+ kind: 'unsupported',
4222
+ raw,
4223
+ reason: `\`.${callee.property}()\` with no search string is not lowered — JS coerces the missing argument to the string "undefined", a degenerate result. Pass an explicit search string, or pre-compute the value before the template.`,
4224
+ }
4225
+ }
4226
+ return { kind: 'array-method', method: callee.property, object: callee.object, args }
4227
+ }
4228
+ // `.replace(pattern, replacement)` — string-pattern form,
4229
+ // replacing the FIRST occurrence (JS semantics for a string
4230
+ // pattern). Go uses `bf_replace` (`strings.Replace` with n=1);
4231
+ // Mojo uses `bf->replace` (index/substr splice, no regex). A
4232
+ // regex-literal pattern is the deferred form — its `regex` first
4233
+ // arg is carried STRUCTURALLY (not collapsed to `unsupported`) so
4234
+ // the Go ctor lowering can recover the one trailing-slash pattern
4235
+ // it supports without re-parsing (#2039). Template use stays
4236
+ // refused: `isSupported` maps a regex-pattern `.replace` to the
4237
+ // deferred-form BF101 reason — the Perl `s///` vs Go
4238
+ // `regexp.ReplaceAllString` flavour gap is the open design
4239
+ // question in #1448. `.replaceAll(pattern, replacement)` shares
4240
+ // this arm (#2182 follow-up): same arity/regex/object-literal
4241
+ // gates, only the `method` tag and its runtime helper differ —
4242
+ // `bf_replace_all` (Go, `strings.ReplaceAll`) / `bf->replace_all`
4243
+ // (Mojo) replace EVERY occurrence, where `.replace`'s helpers
4244
+ // replace only the first.
4245
+ //
4246
+ // Full JS arity: a third+ argument is ignored (the adapter reads
4247
+ // only the pattern + replacement). The one- and zero-argument
4248
+ // forms are refused: JS coerces the missing replacement (and
4249
+ // pattern) to the literal string "undefined", a degenerate result
4250
+ // (mirrors the `.includes()` / `.startsWith()` zero-arg refusal).
4251
+ if (callee.property === 'replace' || callee.property === 'replaceAll') {
4252
+ const method = callee.property
4253
+ if (args.length < 2) {
4254
+ return {
4255
+ kind: 'unsupported',
4256
+ raw,
4257
+ reason: `\`.${method}(${args.length === 0 ? '' : 'pattern'})\` needs both a pattern and a replacement — JS coerces the missing argument to the string "undefined", a degenerate result. Pass both arguments, or pre-compute the value before the template.`,
4258
+ }
4259
+ }
4260
+ // A regex-literal pattern is the deferred form (the Perl `s///`
4261
+ // vs Go `regexp.ReplaceAllString` flavour gap, #1448). Its shape
4262
+ // is carried structurally — `args[0]` is a `regex` node (convertNode
4263
+ // line ~1127) — so a consumer that recognises one fixed pattern (the
4264
+ // Go ctor's `/\/+$/` trailing-slash strip → `strings.TrimRight`) reads
4265
+ // it from the tree instead of re-parsing the raw (#2039). Returned
4266
+ // before the object-literal `badArg` check below so the regex form
4267
+ // keeps its dedicated diagnostic precedence; `isSupported` then refuses
4268
+ // any template use with the deferred-form reason.
4269
+ const patternNode = node.arguments[0]
4270
+ if (patternNode && ts.isRegularExpressionLiteral(patternNode)) {
4271
+ return { kind: 'array-method', method, object: callee.object, args }
4272
+ }
4273
+ // Treat an object-literal argument like `unsupported` — a `.replace`
4274
+ // with an object pattern/replacement isn't lowerable, same as before
4275
+ // the `object-literal` kind existed (byte-identical; Roadmap A-1).
4276
+ const badArg =
4277
+ args[0].kind === 'unsupported' || args[0].kind === 'object-literal'
4278
+ ? args[0]
4279
+ : args[1].kind === 'unsupported' || args[1].kind === 'object-literal'
4280
+ ? args[1]
4281
+ : undefined
4282
+ if (badArg) {
4283
+ const reason = badArg.kind === 'unsupported' ? badArg.reason : 'Unsupported syntax: ObjectLiteralExpression'
4284
+ return { kind: 'unsupported', raw, reason }
4285
+ }
4286
+ return { kind: 'array-method', method, object: callee.object, args }
4287
+ }
4288
+ // `.repeat(n)` — string → string (the receiver concatenated `n`
4289
+ // times). Go uses `bf_repeat` (`strings.Repeat`, clamping a
4290
+ // negative count to "" instead of panicking); Mojo uses
4291
+ // `bf->repeat` (Perl's `x` operator). JS throws RangeError for a
4292
+ // negative count, but SSR templates degrade to the empty string
4293
+ // rather than crashing the render. See #1448 Tier B.
4294
+ // Full JS arity: `.repeat()` (no count) is `repeat(0)` → "" (JS
4295
+ // coerces the missing count to 0, not a RangeError), and a
4296
+ // second+ argument is ignored. The adapter supplies the `0` for
4297
+ // the no-argument form. See #1448 Tier B.
4298
+ if (callee.property === 'repeat') {
4299
+ return { kind: 'array-method', method: 'repeat', object: callee.object, args }
4300
+ }
4301
+ // `.padStart(target, pad?)` / `.padEnd(target, pad?)` — string →
4302
+ // string, padded to `target` length with `pad` (default a single
4303
+ // space) repeated + truncated to fill. Go uses `bf_pad_start` /
4304
+ // `bf_pad_end`; Mojo uses `bf->pad_start` / `bf->pad_end`. Both
4305
+ // count length in code points (Go runes / Perl chars) so they
4306
+ // stay byte-equal — this differs from JS's UTF-16-unit length
4307
+ // only for astral-plane receivers, which are vanishingly rare in
4308
+ // numeric / space padding. See #1448 Tier B.
4309
+ // Full JS arity: `.padStart()` (no target) is `padStart(0)` → the
4310
+ // receiver unchanged (JS coerces the missing target to 0), and a
4311
+ // third+ argument is ignored. The adapter supplies the `0` for the
4312
+ // no-argument form and reads only target + padString.
4313
+ if (callee.property === 'padStart' || callee.property === 'padEnd') {
4314
+ return { kind: 'array-method', method: callee.property, object: callee.object, args }
4315
+ }
4316
+ // `.sort` / `.toSorted` / `.reduce` / `.reduceRight` / `.flatMap`
4317
+ // (callback methods) are NOT folded here (#2018 P5): they fall through
4318
+ // to the generic `call` construction below (callee = member, arg =
4319
+ // generic `arrow`), and the adapter serializes the arrow body to the
4320
+ // runtime evaluator. The localeCompare-sort fallback recovers a
4321
+ // structured comparator from the generic arrow via
4322
+ // `sortComparatorFromArrow`.
4323
+ }
4324
+
4325
+ return { kind: 'call', callee, args }
4326
+ }