@geastack/compiler 1.0.20 → 1.0.22

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 (543) hide show
  1. package/dist/cli-emit.js +11 -1
  2. package/dist/cli-package-source.d.ts +0 -4
  3. package/dist/cli-package-source.js +8 -112
  4. package/dist/cli-refusal-location.d.ts +6 -0
  5. package/dist/cli-refusal-location.js +5 -0
  6. package/dist/cli.js +2 -1
  7. package/dist/compiler.d.ts +4 -0
  8. package/dist/compiler.js +120 -29
  9. package/dist/conversion/algebra.d.ts +16 -1
  10. package/dist/conversion/algebra.js +2 -0
  11. package/dist/conversion/build.d.ts +12 -0
  12. package/dist/conversion/build.js +31 -6
  13. package/dist/conversion/constructor-identity-family.d.ts +49 -0
  14. package/dist/conversion/constructor-identity-family.js +67 -0
  15. package/dist/conversion/derive.js +39 -6
  16. package/dist/conversion/iterable-object-view.d.ts +44 -0
  17. package/dist/conversion/iterable-object-view.js +55 -0
  18. package/dist/conversion/iterator-object-view.d.ts +77 -0
  19. package/dist/conversion/iterator-object-view.js +112 -0
  20. package/dist/conversion/nodes.d.ts +93 -0
  21. package/dist/conversion/nodes.js +262 -5
  22. package/dist/conversion/operand-view.js +41 -0
  23. package/dist/conversion/protocol-iterator.d.ts +84 -0
  24. package/dist/conversion/protocol-iterator.js +88 -0
  25. package/dist/conversion/record-view.d.ts +152 -8
  26. package/dist/conversion/record-view.js +518 -37
  27. package/dist/conversion/registry.d.ts +32 -0
  28. package/dist/ir/borrowed-call-arguments.d.ts +22 -1
  29. package/dist/ir/borrowed-call-arguments.js +102 -1
  30. package/dist/ir/borrowed-callable-uses.d.ts +62 -0
  31. package/dist/ir/borrowed-callable-uses.js +135 -0
  32. package/dist/ir/boxed-bind-assumptions.d.ts +24 -0
  33. package/dist/ir/boxed-bind-assumptions.js +93 -0
  34. package/dist/ir/build.d.ts +18 -7
  35. package/dist/ir/build.js +71 -13
  36. package/dist/ir/call-dispatch.js +474 -10
  37. package/dist/ir/call-entry.d.ts +24 -1
  38. package/dist/ir/call-entry.js +106 -1
  39. package/dist/ir/callable-class-flow.d.ts +3 -1
  40. package/dist/ir/callable-class-flow.js +42 -6
  41. package/dist/ir/callable-identity-demand.d.ts +20 -1
  42. package/dist/ir/callable-identity-demand.js +157 -18
  43. package/dist/ir/callable-member-candidates.d.ts +11 -1
  44. package/dist/ir/callable-member-candidates.js +82 -3
  45. package/dist/ir/callable-records.js +2 -2
  46. package/dist/ir/callable-site-escape.d.ts +4 -0
  47. package/dist/ir/callable-site-escape.js +228 -0
  48. package/dist/ir/captures.d.ts +10 -1
  49. package/dist/ir/captures.js +219 -4
  50. package/dist/ir/certificate.js +87 -16
  51. package/dist/ir/certify/carrier-keys.d.ts +58 -1
  52. package/dist/ir/certify/carrier-keys.js +160 -6
  53. package/dist/ir/certify/property-access-keys.d.ts +17 -0
  54. package/dist/ir/certify/property-access-keys.js +36 -0
  55. package/dist/ir/certify/property-access.js +49 -4
  56. package/dist/ir/certify/runtime-helper.d.ts +4 -0
  57. package/dist/ir/certify/runtime-helper.js +17 -5
  58. package/dist/ir/certify.js +132 -79
  59. package/dist/ir/class-static-fields.d.ts +11 -0
  60. package/dist/ir/class-static-fields.js +28 -0
  61. package/dist/ir/construct-entry.d.ts +2 -1
  62. package/dist/ir/construct-entry.js +3 -2
  63. package/dist/ir/construction-only-fields.d.ts +73 -0
  64. package/dist/ir/construction-only-fields.js +211 -0
  65. package/dist/ir/dominance.d.ts +14 -0
  66. package/dist/ir/dominance.js +18 -4
  67. package/dist/ir/emission-representations.js +4 -1
  68. package/dist/ir/exception-edges.d.ts +17 -0
  69. package/dist/ir/exception-edges.js +75 -0
  70. package/dist/ir/facts.d.ts +54 -3
  71. package/dist/ir/facts.js +182 -5
  72. package/dist/ir/generator-split.js +2 -2
  73. package/dist/ir/instance-reparenting.d.ts +83 -0
  74. package/dist/ir/instance-reparenting.js +167 -0
  75. package/dist/ir/integer-storage.d.ts +29 -0
  76. package/dist/ir/integer-storage.js +188 -79
  77. package/dist/ir/integers.d.ts +16 -0
  78. package/dist/ir/integers.js +327 -8
  79. package/dist/ir/integrity-restrictions.d.ts +42 -9
  80. package/dist/ir/integrity-restrictions.js +335 -42
  81. package/dist/ir/key-order-observation.d.ts +38 -0
  82. package/dist/ir/key-order-observation.js +173 -0
  83. package/dist/ir/literal-set-membership.d.ts +30 -0
  84. package/dist/ir/literal-set-membership.js +277 -0
  85. package/dist/ir/lower-allocation.js +68 -8
  86. package/dist/ir/lower-completion.d.ts +0 -9
  87. package/dist/ir/lower-completion.js +14 -5
  88. package/dist/ir/lower-destructuring.js +24 -2
  89. package/dist/ir/lower-exceptions.js +4 -4
  90. package/dist/ir/lower-flow.d.ts +21 -0
  91. package/dist/ir/lower-flow.js +37 -3
  92. package/dist/ir/lower-graph.d.ts +19 -1
  93. package/dist/ir/lower-graph.js +91 -67
  94. package/dist/ir/lower-invocation.d.ts +16 -0
  95. package/dist/ir/lower-invocation.js +189 -29
  96. package/dist/ir/lower-narrow.d.ts +0 -46
  97. package/dist/ir/lower-narrow.js +63 -1
  98. package/dist/ir/lower-operands.d.ts +52 -2
  99. package/dist/ir/lower-operands.js +491 -8
  100. package/dist/ir/lower-property.d.ts +2 -1
  101. package/dist/ir/lower-property.js +140 -31
  102. package/dist/ir/lower-protocol.js +16 -4
  103. package/dist/ir/lower-proxy.d.ts +65 -0
  104. package/dist/ir/lower-proxy.js +181 -0
  105. package/dist/ir/lower.js +112 -17
  106. package/dist/ir/model.d.ts +228 -18
  107. package/dist/ir/native-class-accessor.d.ts +9 -2
  108. package/dist/ir/native-class-accessor.js +12 -3
  109. package/dist/ir/native-class-construction.d.ts +1 -1
  110. package/dist/ir/native-class-construction.js +2 -1
  111. package/dist/ir/native-class-initialization.js +2 -2
  112. package/dist/ir/object-value-conversions.js +20 -5
  113. package/dist/ir/operation-index.d.ts +16 -0
  114. package/dist/ir/operation-index.js +17 -0
  115. package/dist/ir/pcm-loops.d.ts +11 -0
  116. package/dist/ir/pcm-loops.js +284 -0
  117. package/dist/ir/presence-proof.js +5 -0
  118. package/dist/ir/program-facts.d.ts +10 -20
  119. package/dist/ir/program-facts.js +80 -6
  120. package/dist/ir/proven-branches.d.ts +2 -2
  121. package/dist/ir/proven-branches.js +198 -3
  122. package/dist/ir/queries.js +35 -1
  123. package/dist/ir/reflection-demand.d.ts +9 -4
  124. package/dist/ir/reflection-demand.js +410 -28
  125. package/dist/ir/refusal.d.ts +1 -0
  126. package/dist/ir/refusal.js +2 -1
  127. package/dist/ir/shake.d.ts +94 -1
  128. package/dist/ir/shake.js +209 -12
  129. package/dist/ir/shared-empty-records.d.ts +12 -0
  130. package/dist/ir/shared-empty-records.js +301 -0
  131. package/dist/ir/spread-copy-elision.d.ts +59 -0
  132. package/dist/ir/spread-copy-elision.js +431 -0
  133. package/dist/ir/stable-cell-reads.d.ts +40 -0
  134. package/dist/ir/stable-cell-reads.js +123 -0
  135. package/dist/ir/static-callables.js +50 -0
  136. package/dist/ir/string-layout-reuse.d.ts +16 -1
  137. package/dist/ir/string-layout-reuse.js +66 -0
  138. package/dist/ir/transfer.d.ts +72 -3
  139. package/dist/ir/transfer.js +511 -19
  140. package/dist/ir/typed-property-access.d.ts +18 -2
  141. package/dist/ir/typed-property-access.js +109 -12
  142. package/dist/ir/verify.js +2 -1
  143. package/dist/plugins/apple/plugin.js +3 -2
  144. package/dist/plugins/gea/host.d.ts +7 -0
  145. package/dist/plugins/gea/host.js +30 -1
  146. package/dist/plugins/gea/lower.js +6 -1
  147. package/dist/plugins/gea/plugin.js +7 -4
  148. package/dist/plugins/gea/render-bridge.d.ts +4 -2
  149. package/dist/plugins/gea/render-bridge.js +23 -7
  150. package/dist/plugins/model.d.ts +2 -0
  151. package/dist/project-preparation.d.ts +5 -1
  152. package/dist/project-preparation.js +184 -7
  153. package/dist/projection/bindings.d.ts +5 -2
  154. package/dist/projection/bindings.js +40 -1
  155. package/dist/projection/callee.d.ts +16 -0
  156. package/dist/projection/callee.js +35 -6
  157. package/dist/projection/class-prototype.js +5 -1
  158. package/dist/projection/classes.d.ts +65 -2
  159. package/dist/projection/classes.js +159 -2
  160. package/dist/projection/dispatch.d.ts +69 -18
  161. package/dist/projection/dispatch.js +391 -19
  162. package/dist/projection/fields.d.ts +4 -3
  163. package/dist/projection/fields.js +89 -21
  164. package/dist/projection/instance-test.d.ts +12 -0
  165. package/dist/projection/instance-test.js +40 -10
  166. package/dist/projection/method-value-escapes.d.ts +43 -0
  167. package/dist/projection/method-value-escapes.js +113 -0
  168. package/dist/projection/slots.d.ts +34 -1
  169. package/dist/projection/slots.js +82 -5
  170. package/dist/representation/any-null-record-members.d.ts +41 -0
  171. package/dist/representation/any-null-record-members.js +115 -0
  172. package/dist/representation/collections.d.ts +3 -1
  173. package/dist/representation/collections.js +5 -2
  174. package/dist/representation/derive.d.ts +9 -1
  175. package/dist/representation/derive.js +366 -25
  176. package/dist/representation/difference.js +14 -0
  177. package/dist/representation/embedded-carriers.js +1 -0
  178. package/dist/representation/host-abi.d.ts +15 -0
  179. package/dist/representation/host-abi.js +28 -0
  180. package/dist/representation/host-templates.d.ts +1 -1
  181. package/dist/representation/host-templates.js +7 -3
  182. package/dist/representation/intersection.js +22 -0
  183. package/dist/representation/json-nullable.d.ts +18 -0
  184. package/dist/representation/json-nullable.js +22 -0
  185. package/dist/representation/model.d.ts +141 -0
  186. package/dist/representation/model.js +47 -3
  187. package/dist/representation/object-shape.d.ts +5 -1
  188. package/dist/representation/object-shape.js +5 -2
  189. package/dist/representation/policies.d.ts +66 -1
  190. package/dist/representation/proxy-carriers.d.ts +71 -0
  191. package/dist/representation/proxy-carriers.js +330 -0
  192. package/dist/representation/publish.d.ts +9 -1
  193. package/dist/representation/publish.js +186 -18
  194. package/dist/representation/record-fields.d.ts +5 -0
  195. package/dist/representation/record-fields.js +7 -1
  196. package/dist/representation/static-field-cells.d.ts +61 -0
  197. package/dist/representation/static-field-cells.js +80 -0
  198. package/dist/representation/unassigned-binding-cells.d.ts +32 -0
  199. package/dist/representation/unassigned-binding-cells.js +44 -0
  200. package/dist/representation/union.js +17 -1
  201. package/dist/representation/unwritten-record-members.d.ts +54 -0
  202. package/dist/representation/unwritten-record-members.js +167 -0
  203. package/dist/representation/value-records.js +153 -11
  204. package/dist/semantics/ambient.d.ts +102 -0
  205. package/dist/semantics/ambient.js +183 -0
  206. package/dist/semantics/any-null-member-declarations.d.ts +32 -0
  207. package/dist/semantics/any-null-member-declarations.js +90 -0
  208. package/dist/semantics/borrowed-builtin-call-bind-source-transform.js +14 -0
  209. package/dist/semantics/borrowed-method-receiver-copy-source-transform.d.ts +51 -0
  210. package/dist/semantics/borrowed-method-receiver-copy-source-transform.js +367 -0
  211. package/dist/semantics/call-invalidated-narrowing.d.ts +3 -0
  212. package/dist/semantics/call-invalidated-narrowing.js +715 -0
  213. package/dist/semantics/callable-origins.d.ts +39 -0
  214. package/dist/semantics/callable-origins.js +73 -2
  215. package/dist/semantics/class-alias.d.ts +36 -0
  216. package/dist/semantics/class-alias.js +64 -14
  217. package/dist/semantics/class-heritage.d.ts +64 -0
  218. package/dist/semantics/class-heritage.js +278 -2
  219. package/dist/semantics/commonjs-wrapper.d.ts +1 -1
  220. package/dist/semantics/commonjs-wrapper.js +24 -7
  221. package/dist/semantics/constructor-function-class-source-transform.d.ts +4 -0
  222. package/dist/semantics/constructor-function-class-source-transform.js +327 -0
  223. package/dist/semantics/constructor-slot-subclasses.js +163 -4
  224. package/dist/semantics/declaration-overlay-transform.js +197 -3
  225. package/dist/semantics/frontend.d.ts +31 -0
  226. package/dist/semantics/frontend.js +212 -26
  227. package/dist/semantics/host-methods.d.ts +27 -2
  228. package/dist/semantics/host-methods.js +57 -4
  229. package/dist/semantics/host-protocols.d.ts +19 -8
  230. package/dist/semantics/host-protocols.js +145 -31
  231. package/dist/semantics/interface-families.d.ts +51 -2
  232. package/dist/semantics/interface-families.js +609 -23
  233. package/dist/semantics/interface-implementors.d.ts +20 -0
  234. package/dist/semantics/interface-implementors.js +130 -6
  235. package/dist/semantics/known-caller-predicate-parameters.d.ts +2 -0
  236. package/dist/semantics/known-caller-predicate-parameters.js +161 -0
  237. package/dist/semantics/model/intrinsic-accessor-getters.d.ts +10 -0
  238. package/dist/semantics/model/intrinsic-accessor-getters.js +4 -0
  239. package/dist/semantics/model/operands.d.ts +10 -0
  240. package/dist/semantics/model/operations.d.ts +107 -0
  241. package/dist/semantics/model/selected-signature.d.ts +33 -0
  242. package/dist/semantics/model/structural-type-table.d.ts +15 -0
  243. package/dist/semantics/model/structural-type-table.js +19 -1
  244. package/dist/semantics/model/structural-types.d.ts +99 -0
  245. package/dist/semantics/model/structural-types.js +31 -2
  246. package/dist/semantics/normalize/absent-globals.d.ts +1 -1
  247. package/dist/semantics/normalize/absent-globals.js +3 -3
  248. package/dist/semantics/normalize/bivariant-slot-parameter.d.ts +46 -0
  249. package/dist/semantics/normalize/bivariant-slot-parameter.js +372 -0
  250. package/dist/semantics/normalize/callback-parameter-contracts.d.ts +2 -0
  251. package/dist/semantics/normalize/callback-parameter-contracts.js +21 -0
  252. package/dist/semantics/normalize/census.d.ts +2 -1
  253. package/dist/semantics/normalize/census.js +25 -2
  254. package/dist/semantics/normalize/class-instance-record-statement.d.ts +37 -0
  255. package/dist/semantics/normalize/class-instance-record-statement.js +74 -0
  256. package/dist/semantics/normalize/collection-bindings.js +242 -5
  257. package/dist/semantics/normalize/commonjs-require.d.ts +35 -5
  258. package/dist/semantics/normalize/commonjs-require.js +464 -147
  259. package/dist/semantics/normalize/dead-event-emissions.d.ts +6 -0
  260. package/dist/semantics/normalize/dead-event-emissions.js +866 -0
  261. package/dist/semantics/normalize/dead-method-copies.d.ts +56 -0
  262. package/dist/semantics/normalize/dead-method-copies.js +239 -0
  263. package/dist/semantics/normalize/derived-expression-type.d.ts +149 -2
  264. package/dist/semantics/normalize/derived-expression-type.js +418 -14
  265. package/dist/semantics/normalize/field-bindings.js +139 -4
  266. package/dist/semantics/normalize/flow/callable-reach.js +162 -9
  267. package/dist/semantics/normalize/flow/member-call-forwarding.js +6 -0
  268. package/dist/semantics/normalize/flow/owned-class-receivers.js +40 -2
  269. package/dist/semantics/normalize/flow/source-class-data.d.ts +7 -1
  270. package/dist/semantics/normalize/flow/source-class-data.js +28 -9
  271. package/dist/semantics/normalize/flow/source-value-session.js +32 -13
  272. package/dist/semantics/normalize/flow/targets.d.ts +32 -0
  273. package/dist/semantics/normalize/flow/targets.js +65 -6
  274. package/dist/semantics/normalize/flow/value-flow.d.ts +7 -0
  275. package/dist/semantics/normalize/flow/value-flow.js +30 -2
  276. package/dist/semantics/normalize/fresh-array-result.d.ts +32 -0
  277. package/dist/semantics/normalize/fresh-array-result.js +125 -0
  278. package/dist/semantics/normalize/gating.js +2 -0
  279. package/dist/semantics/normalize/global-host-mutations.d.ts +11 -1
  280. package/dist/semantics/normalize/global-host-mutations.js +691 -27
  281. package/dist/semantics/normalize/host-effect-contracts.d.ts +43 -1
  282. package/dist/semantics/normalize/host-effect-contracts.js +60 -3
  283. package/dist/semantics/normalize/host-mutation-key-reader.js +35 -10
  284. package/dist/semantics/normalize/identities.js +64 -3
  285. package/dist/semantics/normalize/intrinsic-accessor-getter.d.ts +59 -0
  286. package/dist/semantics/normalize/intrinsic-accessor-getter.js +129 -0
  287. package/dist/semantics/normalize/local-bindings.js +117 -21
  288. package/dist/semantics/normalize/merged-declaration.d.ts +41 -0
  289. package/dist/semantics/normalize/merged-declaration.js +81 -0
  290. package/dist/semantics/normalize/never-override-result.d.ts +21 -0
  291. package/dist/semantics/normalize/never-override-result.js +64 -0
  292. package/dist/semantics/normalize/null-blind-parameter.d.ts +21 -0
  293. package/dist/semantics/normalize/null-blind-parameter.js +77 -0
  294. package/dist/semantics/normalize/object-bag-bindings.js +26 -2
  295. package/dist/semantics/normalize/omitted-stated-parameter.d.ts +1 -1
  296. package/dist/semantics/normalize/omitted-stated-parameter.js +34 -4
  297. package/dist/semantics/normalize/override-field-arms.d.ts +33 -0
  298. package/dist/semantics/normalize/override-field-arms.js +362 -0
  299. package/dist/semantics/normalize/parameter-bindings.d.ts +64 -1
  300. package/dist/semantics/normalize/parameter-bindings.js +827 -81
  301. package/dist/semantics/normalize/parameter-slot.d.ts +1 -0
  302. package/dist/semantics/normalize/parameter-slot.js +69 -0
  303. package/dist/semantics/normalize/physical-overload-result.d.ts +45 -0
  304. package/dist/semantics/normalize/physical-overload-result.js +132 -0
  305. package/dist/semantics/normalize/producer-context.d.ts +23 -0
  306. package/dist/semantics/normalize/producers/allocations.d.ts +13 -0
  307. package/dist/semantics/normalize/producers/allocations.js +8 -15
  308. package/dist/semantics/normalize/producers/binding-kind.d.ts +11 -0
  309. package/dist/semantics/normalize/producers/binding-kind.js +31 -0
  310. package/dist/semantics/normalize/producers/bindings.js +16 -1
  311. package/dist/semantics/normalize/producers/boundary.js +21 -1
  312. package/dist/semantics/normalize/producers/class-lifecycle.js +23 -14
  313. package/dist/semantics/normalize/producers/computations.js +8 -67
  314. package/dist/semantics/normalize/producers/control-loops.d.ts +1 -1
  315. package/dist/semantics/normalize/producers/control-loops.js +25 -1
  316. package/dist/semantics/normalize/producers/control.js +87 -60
  317. package/dist/semantics/normalize/producers/declaration-lifecycle.js +5 -0
  318. package/dist/semantics/normalize/producers/enums.d.ts +10 -0
  319. package/dist/semantics/normalize/producers/enums.js +169 -0
  320. package/dist/semantics/normalize/producers/erasure.d.ts +10 -0
  321. package/dist/semantics/normalize/producers/erasure.js +23 -0
  322. package/dist/semantics/normalize/producers/intrinsic-accessor-getter.d.ts +15 -0
  323. package/dist/semantics/normalize/producers/intrinsic-accessor-getter.js +33 -0
  324. package/dist/semantics/normalize/producers/invocations.js +255 -18
  325. package/dist/semantics/normalize/producers/iteration-yield.js +6 -1
  326. package/dist/semantics/normalize/producers/logical-merge-type.d.ts +36 -0
  327. package/dist/semantics/normalize/producers/logical-merge-type.js +163 -0
  328. package/dist/semantics/normalize/producers/properties.js +207 -18
  329. package/dist/semantics/normalize/producers/protocol.d.ts +4 -0
  330. package/dist/semantics/normalize/producers/protocol.js +147 -12
  331. package/dist/semantics/normalize/producers/references.js +50 -9
  332. package/dist/semantics/normalize/producers/shared.d.ts +120 -0
  333. package/dist/semantics/normalize/producers/shared.js +359 -10
  334. package/dist/semantics/normalize/producers/spread-arguments.js +85 -4
  335. package/dist/semantics/normalize/producers/tuple-spread.d.ts +1 -0
  336. package/dist/semantics/normalize/producers/tuple-spread.js +1 -1
  337. package/dist/semantics/normalize/property-key-domain.js +6 -0
  338. package/dist/semantics/normalize/reachability.d.ts +7 -0
  339. package/dist/semantics/normalize/reachability.js +166 -9
  340. package/dist/semantics/normalize/record-home-arms.d.ts +25 -0
  341. package/dist/semantics/normalize/record-home-arms.js +87 -0
  342. package/dist/semantics/normalize/record-link-families.d.ts +74 -0
  343. package/dist/semantics/normalize/record-link-families.js +327 -0
  344. package/dist/semantics/normalize/record-stand-in-arms.d.ts +56 -0
  345. package/dist/semantics/normalize/record-stand-in-arms.js +484 -0
  346. package/dist/semantics/normalize/return-bindings.d.ts +6 -2
  347. package/dist/semantics/normalize/return-bindings.js +60 -7
  348. package/dist/semantics/normalize/script-global-redefinition.js +5 -0
  349. package/dist/semantics/normalize/shared-array-storage.d.ts +42 -0
  350. package/dist/semantics/normalize/shared-array-storage.js +373 -0
  351. package/dist/semantics/normalize/sloppy-absence.d.ts +41 -0
  352. package/dist/semantics/normalize/sloppy-absence.js +199 -0
  353. package/dist/semantics/normalize/specialization.d.ts +40 -0
  354. package/dist/semantics/normalize/specialization.js +770 -36
  355. package/dist/semantics/normalize/structural-array-element.js +196 -6
  356. package/dist/semantics/normalize/structural-array-read.js +12 -0
  357. package/dist/semantics/normalize/structural-creation-order.d.ts +15 -0
  358. package/dist/semantics/normalize/structural-creation-order.js +51 -48
  359. package/dist/semantics/normalize/structural-declarations.d.ts +16 -0
  360. package/dist/semantics/normalize/structural-declarations.js +43 -0
  361. package/dist/semantics/normalize/structural-generics.d.ts +13 -0
  362. package/dist/semantics/normalize/structural-generics.js +22 -0
  363. package/dist/semantics/normalize/structural-indexed-access.js +16 -0
  364. package/dist/semantics/normalize/structural-instantiated-member.js +68 -2
  365. package/dist/semantics/normalize/structural-joins.js +2 -0
  366. package/dist/semantics/normalize/structural-layout-relevance.d.ts +30 -0
  367. package/dist/semantics/normalize/structural-layout-relevance.js +164 -0
  368. package/dist/semantics/normalize/structural-layout-type.js +270 -14
  369. package/dist/semantics/normalize/structural-leaves.d.ts +1 -1
  370. package/dist/semantics/normalize/structural-leaves.js +17 -3
  371. package/dist/semantics/normalize/structural-mutable-method.js +5 -1
  372. package/dist/semantics/normalize/structural-parts.d.ts +18 -5
  373. package/dist/semantics/normalize/structural-parts.js +68 -19
  374. package/dist/semantics/normalize/structural-receiver.d.ts +1 -1
  375. package/dist/semantics/normalize/structural-receiver.js +23 -1
  376. package/dist/semantics/normalize/structural-self-reference.d.ts +1 -1
  377. package/dist/semantics/normalize/structural-self-reference.js +23 -2
  378. package/dist/semantics/normalize/structural.d.ts +12 -1
  379. package/dist/semantics/normalize/structural.js +1437 -53
  380. package/dist/semantics/normalize/suppressed-write-arms.d.ts +47 -0
  381. package/dist/semantics/normalize/suppressed-write-arms.js +393 -0
  382. package/dist/semantics/normalize/unresolvable-names.d.ts +15 -2
  383. package/dist/semantics/normalize/unresolvable-names.js +30 -6
  384. package/dist/semantics/normalize/unshared-array-result.d.ts +32 -0
  385. package/dist/semantics/normalize/unshared-array-result.js +125 -0
  386. package/dist/semantics/package-sources.d.ts +1 -1
  387. package/dist/semantics/package-sources.js +120 -8
  388. package/dist/semantics/program.d.ts +20 -0
  389. package/dist/semantics/program.js +179 -26
  390. package/dist/semantics/shared-declaration-files.d.ts +44 -0
  391. package/dist/semantics/shared-declaration-files.js +42 -0
  392. package/dist/semantics/stable-checker.d.ts +1 -1
  393. package/dist/semantics/stable-checker.js +7 -2
  394. package/dist/semantics/subclass-member-overlay-transform.js +95 -53
  395. package/dist/semantics/unchecked-guard-argument-copies.d.ts +67 -0
  396. package/dist/semantics/unchecked-guard-argument-copies.js +163 -0
  397. package/dist/semantics/unchecked-write-member-declarations.d.ts +46 -0
  398. package/dist/semantics/unchecked-write-member-declarations.js +331 -0
  399. package/dist/targets/cpp/balanced-units.d.ts +31 -0
  400. package/dist/targets/cpp/balanced-units.js +57 -0
  401. package/dist/targets/cpp/borrowed-arm-projections.d.ts +31 -0
  402. package/dist/targets/cpp/borrowed-arm-projections.js +106 -0
  403. package/dist/targets/cpp/borrowed-call-entry.d.ts +1 -1
  404. package/dist/targets/cpp/borrowed-call-entry.js +24 -20
  405. package/dist/targets/cpp/captures.js +314 -8
  406. package/dist/targets/cpp/char-code-buffers.d.ts +36 -0
  407. package/dist/targets/cpp/char-code-buffers.js +214 -0
  408. package/dist/targets/cpp/class-layout.d.ts +7 -1
  409. package/dist/targets/cpp/class-layout.js +42 -17
  410. package/dist/targets/cpp/class-properties/computed-method-value.d.ts +17 -2
  411. package/dist/targets/cpp/class-properties/computed-method-value.js +50 -4
  412. package/dist/targets/cpp/class-properties/emit-class-properties.d.ts +31 -1
  413. package/dist/targets/cpp/class-properties/emit-class-properties.js +174 -17
  414. package/dist/targets/cpp/class-ref-transport.d.ts +32 -0
  415. package/dist/targets/cpp/class-ref-transport.js +56 -1
  416. package/dist/targets/cpp/conversions.js +1827 -1502
  417. package/dist/targets/cpp/coroutine-bodies.d.ts +97 -0
  418. package/dist/targets/cpp/coroutine-bodies.js +187 -0
  419. package/dist/targets/cpp/document.js +11 -1
  420. package/dist/targets/cpp/emit-allocation.js +568 -21
  421. package/dist/targets/cpp/emit-arrays.d.ts +10 -0
  422. package/dist/targets/cpp/emit-arrays.js +147 -16
  423. package/dist/targets/cpp/emit-binding-reference.d.ts +26 -2
  424. package/dist/targets/cpp/emit-binding-reference.js +97 -5
  425. package/dist/targets/cpp/emit-bindings.d.ts +9 -1
  426. package/dist/targets/cpp/emit-bindings.js +108 -8
  427. package/dist/targets/cpp/emit-buffers.d.ts +2 -16
  428. package/dist/targets/cpp/emit-buffers.js +124 -25
  429. package/dist/targets/cpp/emit-callable.d.ts +35 -72
  430. package/dist/targets/cpp/emit-callable.js +647 -82
  431. package/dist/targets/cpp/emit-carrier-members.d.ts +13 -2
  432. package/dist/targets/cpp/emit-carrier-members.js +50 -9
  433. package/dist/targets/cpp/emit-constructor-identity-family.d.ts +20 -0
  434. package/dist/targets/cpp/emit-constructor-identity-family.js +45 -0
  435. package/dist/targets/cpp/emit-context.d.ts +329 -15
  436. package/dist/targets/cpp/emit-context.js +104 -13
  437. package/dist/targets/cpp/emit-dynamic-properties.d.ts +44 -0
  438. package/dist/targets/cpp/emit-dynamic-properties.js +256 -37
  439. package/dist/targets/cpp/emit-equality.js +117 -2
  440. package/dist/targets/cpp/emit-error-constructor.d.ts +19 -0
  441. package/dist/targets/cpp/emit-error-constructor.js +73 -0
  442. package/dist/targets/cpp/emit-exceptions.d.ts +25 -3
  443. package/dist/targets/cpp/emit-exceptions.js +215 -26
  444. package/dist/targets/cpp/emit-in.js +52 -5
  445. package/dist/targets/cpp/emit-instanceof.js +59 -11
  446. package/dist/targets/cpp/emit-integers.d.ts +6 -0
  447. package/dist/targets/cpp/emit-integers.js +10 -0
  448. package/dist/targets/cpp/emit-iterable-object-view.d.ts +15 -0
  449. package/dist/targets/cpp/emit-iterable-object-view.js +51 -0
  450. package/dist/targets/cpp/emit-iterator-object-view.d.ts +15 -0
  451. package/dist/targets/cpp/emit-iterator-object-view.js +125 -0
  452. package/dist/targets/cpp/emit-iterator.d.ts +7 -10
  453. package/dist/targets/cpp/emit-iterator.js +361 -24
  454. package/dist/targets/cpp/emit-json.d.ts +7 -1
  455. package/dist/targets/cpp/emit-json.js +595 -55
  456. package/dist/targets/cpp/emit-jsx.d.ts +0 -37
  457. package/dist/targets/cpp/emit-jsx.js +70 -8
  458. package/dist/targets/cpp/emit-narrowing.d.ts +192 -28
  459. package/dist/targets/cpp/emit-narrowing.js +1595 -120
  460. package/dist/targets/cpp/emit-native-selection.js +8 -2
  461. package/dist/targets/cpp/emit-presence.js +13 -0
  462. package/dist/targets/cpp/emit-properties.d.ts +3 -1
  463. package/dist/targets/cpp/emit-properties.js +303 -54
  464. package/dist/targets/cpp/emit-protocol-iterator.d.ts +14 -0
  465. package/dist/targets/cpp/emit-protocol-iterator.js +203 -0
  466. package/dist/targets/cpp/emit-proxy.d.ts +17 -0
  467. package/dist/targets/cpp/emit-proxy.js +35 -0
  468. package/dist/targets/cpp/emit-record-view.d.ts +12 -1
  469. package/dist/targets/cpp/emit-record-view.js +429 -18
  470. package/dist/targets/cpp/emit-return.d.ts +38 -0
  471. package/dist/targets/cpp/emit-return.js +143 -21
  472. package/dist/targets/cpp/emit-scopes.d.ts +78 -0
  473. package/dist/targets/cpp/emit-scopes.js +196 -0
  474. package/dist/targets/cpp/emit-sum-widening.js +6 -3
  475. package/dist/targets/cpp/emit-tonumber.d.ts +40 -1
  476. package/dist/targets/cpp/emit-tonumber.js +75 -4
  477. package/dist/targets/cpp/emit-tostring.d.ts +28 -2
  478. package/dist/targets/cpp/emit-tostring.js +115 -12
  479. package/dist/targets/cpp/emit-typeof.js +2 -2
  480. package/dist/targets/cpp/emit-union-properties.d.ts +9 -0
  481. package/dist/targets/cpp/emit-union-properties.js +391 -49
  482. package/dist/targets/cpp/emit.d.ts +3 -1
  483. package/dist/targets/cpp/emit.js +725 -90
  484. package/dist/targets/cpp/evaluated-once.d.ts +51 -0
  485. package/dist/targets/cpp/evaluated-once.js +140 -0
  486. package/dist/targets/cpp/host/core-globals.d.ts +0 -21
  487. package/dist/targets/cpp/host/core-globals.js +10 -2
  488. package/dist/targets/cpp/host/emit-host-invoke.d.ts +0 -10
  489. package/dist/targets/cpp/host/emit-host-invoke.js +454 -36
  490. package/dist/targets/cpp/host/emit-host-object.js +733 -88
  491. package/dist/targets/cpp/host/emit-host-properties.js +26 -2
  492. package/dist/targets/cpp/host/emit-host-reflect.d.ts +1 -0
  493. package/dist/targets/cpp/host/emit-host-reflect.js +26 -7
  494. package/dist/targets/cpp/host/emit-host-value.d.ts +13 -0
  495. package/dist/targets/cpp/host/emit-host-value.js +47 -3
  496. package/dist/targets/cpp/host/host-members.d.ts +11 -0
  497. package/dist/targets/cpp/host/host-members.js +50 -4
  498. package/dist/targets/cpp/host/native-protocols.js +3 -0
  499. package/dist/targets/cpp/host/object-protocol.d.ts +8 -0
  500. package/dist/targets/cpp/host/object-protocol.js +55 -13
  501. package/dist/targets/cpp/key-order-tracking.d.ts +11 -0
  502. package/dist/targets/cpp/key-order-tracking.js +18 -0
  503. package/dist/targets/cpp/manifest/capabilities.js +117 -9
  504. package/dist/targets/cpp/manifest.js +14 -0
  505. package/dist/targets/cpp/native-collection-base.d.ts +27 -0
  506. package/dist/targets/cpp/native-collection-base.js +202 -0
  507. package/dist/targets/cpp/native-error-base.d.ts +14 -0
  508. package/dist/targets/cpp/native-error-base.js +19 -4
  509. package/dist/targets/cpp/native-promise-base.d.ts +23 -0
  510. package/dist/targets/cpp/native-promise-base.js +30 -0
  511. package/dist/targets/cpp/native-symbol-keys.js +1 -1
  512. package/dist/targets/cpp/prototype/emit-prototype-array.js +258 -20
  513. package/dist/targets/cpp/prototype/emit-prototype-date.js +5 -4
  514. package/dist/targets/cpp/prototype/emit-prototype-invoke.d.ts +9 -1
  515. package/dist/targets/cpp/prototype/emit-prototype-invoke.js +232 -26
  516. package/dist/targets/cpp/prototype/emit-prototype-iterator.d.ts +1 -1
  517. package/dist/targets/cpp/prototype/emit-prototype-iterator.js +111 -13
  518. package/dist/targets/cpp/prototype/emit-prototype-promise.d.ts +33 -4
  519. package/dist/targets/cpp/prototype/emit-prototype-promise.js +218 -10
  520. package/dist/targets/cpp/prototype/emit-prototype-regexp.js +8 -5
  521. package/dist/targets/cpp/prototype/emit-prototype-string.js +24 -7
  522. package/dist/targets/cpp/prototype/prototype-method-reads.js +18 -3
  523. package/dist/targets/cpp/reactive-dependencies.d.ts +2 -0
  524. package/dist/targets/cpp/reactive-dependencies.js +94 -3
  525. package/dist/targets/cpp/realm-storage.d.ts +5 -0
  526. package/dist/targets/cpp/realm-storage.js +12 -0
  527. package/dist/targets/cpp/records.d.ts +151 -1
  528. package/dist/targets/cpp/records.js +1328 -122
  529. package/dist/targets/cpp/recursive-containers.d.ts +4 -1
  530. package/dist/targets/cpp/recursive-containers.js +28 -9
  531. package/dist/targets/cpp/translation-unit.d.ts +10 -0
  532. package/dist/targets/cpp/translation-unit.js +686 -140
  533. package/dist/targets/cpp/types.d.ts +56 -6
  534. package/dist/targets/cpp/types.js +218 -12
  535. package/dist/targets/cpp/virtual-methods.d.ts +3 -3
  536. package/dist/targets/cpp/virtual-methods.js +174 -17
  537. package/package.json +14 -13
  538. package/src/targets/cpp/runtime/gea_dynamic_proxy.h +155 -25
  539. package/src/targets/cpp/runtime/gea_eval.h +3 -0
  540. package/src/targets/cpp/runtime/gea_pcm.h +116 -0
  541. package/src/targets/cpp/runtime/gea_runtime.h +18159 -4887
  542. package/src/targets/cpp/runtime/gea_runtime_builtins.cpp +7 -45
  543. package/src/targets/cpp/runtime/gea_runtime_rtc.h +247 -0
@@ -1,19 +1,26 @@
1
1
  import { coercionText } from './emit-coercion.js';
2
- import { classRefTransportKind, constructorUpcastMember } from './class-ref-transport.js';
2
+ import { classRefTransportKind, constructorFamilyUpcastMembers, constructorUpcastMember, nativeRecordBaseTransportKind } from './class-ref-transport.js';
3
3
  import { chainFieldProtocolUnused, nativeSumNarrowingTransports } from './native-narrowing-transport.js';
4
4
  import { classRefDomainsOverlap, classifierDomainsOverlap } from '../../conversion/algebra.js';
5
5
  import { recordCastableToArray } from './emit-arrays.js';
6
6
  import { emptyConversionRegistry, narrowingReachesTarget, narrowsToDescendantClassUnion } from '../../conversion/build.js';
7
7
  import { defaultRecordLayoutPolicy } from '../../representation/policies.js';
8
- import { abiKey, arrayExtensionKey, representationKey, carriesUndefined } from '../../representation/model.js';
9
- import { isSpellable, callableObjectAbi, resultAdapterTransportOf, boxDiscriminantsOfArm, conversionRecipeOf, boxedAssertionText, dropsAllParametersIntoResultArm, dropsUnboundParameters, dynamicTagFor, promisePayloadConvertible, rebasesRestOverLeadingParameters, dictionaryCastableToDictionary, recordCastableToDictionary, recordRecastCrossesDynamic, recordsRecastable, sameArrayUpToExtension, sumIntoPayloadText, widensResultIntoArm } from './emit-narrowing.js';
8
+ import { abiKey, arrayExtensionKey, representationKey, carriesUndefined, containsUnresolved, isOpenDocument } from '../../representation/model.js';
9
+ import { isSpellable, callableObjectAbi, resultAdapterTransportOf, adaptsConstructorIntoDispatch, boxDiscriminantsOfArm, conversionRecipeOf, boxedAssertionText, classDocumentViewText, dropsAllParametersIntoResultArm, dropsUnboundParameters, dynamicTagFor, promisePayloadConvertible, rebasesRestOverLeadingParameters, dictionaryCastableToDictionary, CONSTRUCTOR_STATIC_VIEW, constructorStaticViewAdmitted, DYNAMIC_DICTIONARY_TO_NAMED_RECORD, dynamicDictionaryToNamedRecordAdmitted, indexedRecordCastableToDictionary, indexedRecordDictionaryArmOf, indexedRecordViewOf, INDEXED_RECORD_INTO_DICTIONARY_ARM, INDEXED_RECORD_TO_DICTIONARY, recordCastableToDictionary, recordRecastCrossesDynamic, recordsRecastable, sameArrayUpToExtension, sumIntoPayloadText, widensResultIntoArm, resultAdaptedCallableText, tryCandidateText, VIEW_ADAPTED_CALLABLE, CHECKED_ARM_NARROWING, checkedArmNarrowingText } from './emit-narrowing.js';
10
10
  import { cppTypeOf } from './types.js';
11
11
  import { nativeSumWidenable } from '../../conversion/native-sum.js';
12
12
  import { nativeSelectionRecipeOf, nativeTotalSelectionRecipeOf } from '../../conversion/native-selection.js';
13
13
  import { nativeClassReferenceIdentityOf } from '../../conversion/native-class-reference.js';
14
- import { isRecordViewTarget, ownedRecordMaterializationPlan, recordViewDispatchesArms, recordViewUsesOnlyDirectFields } from '../../conversion/record-view.js';
14
+ import { isRecordViewTarget, ownedRecordMaterializationPlan, recordViewDispatchesArms, recordViewIndirectReads, recordViewResidualReflection, recordViewUsesOnlyDirectFields } from '../../conversion/record-view.js';
15
15
  import { cppStringObjectNativeType } from './regexp-types.js';
16
- import { viewPlanFor } from './emit-record-view.js';
16
+ import { familyMemberViewPlanFor, viewPlanFor } from './emit-record-view.js';
17
+ import { FAMILY_MEMBER_VIEW_MATERIALIZER } from '../../conversion/nodes.js';
18
+ import { PROTOCOL_ITERATOR, protocolIteratorPlanFor } from './emit-protocol-iterator.js';
19
+ import { ITERABLE_OBJECT_VIEW, iterableObjectViewPlanFor } from './emit-iterable-object-view.js';
20
+ import { ITERATOR_OBJECT_VIEW, iteratorObjectViewPlanFor } from './emit-iterator-object-view.js';
21
+ import { CONSTRUCTOR_DISPATCH_FAMILY, CONSTRUCTOR_IDENTITY_FAMILY } from './emit-constructor-identity-family.js';
22
+ import { proxyArmWithoutHome } from '../../representation/proxy-carriers.js';
23
+ import { constructorDispatchFamilyPlan, constructorIdentityFamilyPlan } from '../../conversion/constructor-identity-family.js';
17
24
  /** Called only after the native converting-constructor predicate has selected this pair. */
18
25
  const nativeClassPresence = (value) => {
19
26
  if (value.kind === 'class-ref' || value.kind === 'null' || value.kind === 'undefined')
@@ -189,10 +196,13 @@ const upcastsToBase = (source, target) => classRefTransportKind(source, target)
189
196
  * layout selection must not discard a prototype object merely because it is
190
197
  * not an instance of its own constructor.
191
198
  */
192
- const downcastsToDerived = (source, target) => classRefTransportKind(source, target) === 'downcast';
199
+ const downcastsToDerived = (source, target) => classRefTransportKind(source, target) === 'downcast' || nativeRecordBaseTransportKind(source, target) === 'downcast';
193
200
  /** Exactly one class arm inside `target` accepts `source` by inheritance. */
194
201
  const hasSingleClassUpcastHome = (source, target) => {
195
- if (upcastsToBase(source, target))
202
+ // A class extending the intrinsic `Error` reaches an `Error` arm by the same
203
+ // pointer upcast a bare `Error` slot takes: mongodb hands every
204
+ // `MongoNetworkError` to an `(err?: Error | null)` callback.
205
+ if (upcastsToBase(source, target) || (target.kind !== source.kind && nativeRecordBaseTransportKind(source, target) === 'upcast'))
196
206
  return true;
197
207
  if (target.kind === 'optional')
198
208
  return hasSingleClassUpcastHome(source, target.payload);
@@ -324,6 +334,9 @@ const cppTaggedUnionArmClassifier = (arm) => {
324
334
  }
325
335
  if (discriminants === null || discriminants.length === 0)
326
336
  return null;
337
+ if (arm.runtimeDiscriminator.kind === 'record-literal') {
338
+ return { id: 'gea::detail::dynamicRecordDiscriminator', domain: `record-literal:${JSON.stringify(arm.runtimeDiscriminator)}` };
339
+ }
327
340
  if (arm.runtimeDiscriminator.kind === 'callable-tag') {
328
341
  return {
329
342
  id: 'gea::Value::tag',
@@ -407,10 +420,16 @@ const dynamicCarrierSupported = (representation, seen = new Set()) => {
407
420
  }
408
421
  case 'array-object':
409
422
  case 'class-ref':
410
- case 'record':
411
423
  case 'record-with-index':
412
424
  case 'native-record-ref':
425
+ // One `gea::Ref<gea::TypedArray<E>>`, authenticated off its allocation
426
+ // header like any other counted handle.
427
+ case 'typed-array':
413
428
  return representation.ownership === 'shared-refcount';
429
+ // An owned record crosses by value, checked by exact payload type
430
+ // (`DynamicCarrier<T>` for a `NativeFieldTable` struct).
431
+ case 'record':
432
+ return representation.ownership === 'shared-refcount' || representation.ownership === 'owned';
414
433
  case 'promise':
415
434
  return dynamicCarrierSupported(representation.value, nested);
416
435
  case 'function':
@@ -484,1594 +503,1897 @@ export const createCppConversionRegistry = (layouts = defaultRecordLayoutPolicy)
484
503
  const registry = cppConversionTables(layouts, (source, target) => nativeSumNarrowingTransports(registry, source, target) ? { nativeFieldProtocol: 'unused', nativePayloadTransport: 'preserved' } : {}, (source, payload) => (chainFieldProtocolUnused(registry, source, payload) ? { nativeFieldProtocol: 'unused' } : {}));
485
504
  return registry;
486
505
  };
487
- const cppConversionTables = (layouts, nativeNarrowing, nativeWrappedPayload) => ({
488
- ...emptyConversionRegistry,
489
- stringMaterializer: () => exactTagRead('String'),
490
- /**
491
- * `gea::Symbol` out of a box is the same exact-tag read as a string: the
492
- * printer's `unboxedLoadText` spells it `unboxValue<gea::Symbol>(v,
493
- * Tag::Symbol, ...)` off `dynamicTagFor`'s own `symbol -> 'Symbol'` row.
494
- * The registry left this `null` while the printer rendered it, so a
495
- * `typeof x === 'symbol'` narrowing certified nothing (no installed exact
496
- * symbol-tag materializer) on a program the printer had always emitted --
497
- * the census/printer disagreement Phase 2.3's emission gate exists to
498
- * surface, found on `symbol-description.runtime.js`.
499
- */
500
- symbolMaterializer: () => exactTagRead('Symbol'),
501
- scalarMaterializer: (domain) => domain === 'number'
502
- ? exactTagRead('Number')
503
- : domain === 'boolean'
504
- ? exactTagRead('Boolean')
505
- : domain === 'bigint'
506
- ? exactTagRead('BigInt')
507
- : null,
508
- /**
509
- * `undefined` out of a box: `exactTagRead` above cannot serve this either,
510
- * for the identical reason `gea::detail::unboxUndefinedValue`
511
- * (gea_runtime.h) exists instead of reusing `unboxValue<T>` -- there is no
512
- * payload, so no `T` to have recorded a `payloadTypeTagFor` for. The tag
513
- * alone is the whole check; a mismatch aborts by name, exactly the same
514
- * refusal discipline as every other exact-tag read in this registry.
515
- */
516
- undefinedMaterializer: () => ({
517
- classifier: { id: 'gea::Value::tag', domain: 'tag:Undefined' },
518
- materializer: { id: 'gea::detail::unboxUndefinedValue', domain: 'tag:Undefined', allocates: false }
519
- }),
520
- /**
521
- * A bare `Function` is intentionally dynamic: it promises `[[Call]]`, but
522
- * no static parameter or result types. The runtime's
523
- * `DynamicCarrier<CallableObject<R(A...)>>::in` is the checked bridge from
524
- * that boundary. It verifies `Tag::Function`, preserves an exact-ABI value
525
- * directly when possible, and otherwise returns a callable adapter that
526
- * boxes the target ABI's arguments, invokes the source box, and checks the
527
- * returned value as `R`.
528
- *
529
- * Install only the ABI presently proved end to end: a receiver-less,
530
- * fixed-arity numeric comparator whose arguments are themselves dynamic
531
- * values. This is Three's public `Function | null` sort hook. Broadening the
532
- * predicate requires matching `DynamicCarrier<T>::supported` for every new
533
- * parameter/result carrier; guessing there would move an honest preflight
534
- * refusal into a C++ template failure.
535
- */
536
- functionValueDispatchMaterializer: (abi) => {
537
- const target = { kind: 'function-value-dispatch', abi };
538
- return dynamicCallableAbiSupported(abi) ? dynamicCallablePair(target) : null;
539
- },
540
- functionMaterializer: (functionId, abi) => {
541
- if (!dynamicCallableAbiSupported(abi))
542
- return null;
543
- const domain = `dynamic-callable-identity:${functionId}:${representationKey({ kind: 'function', functionId, abi })}`;
544
- return {
545
- classifier: { id: 'gea::Value::callableDeclarationIdentity', domain },
546
- materializer: { id: 'gea::detail::DynamicCarrier::in', domain, allocates: true }
547
- };
548
- },
549
- /**
550
- * `null` out of a box: the exact sibling of `undefinedMaterializer` above,
551
- * and absent for as long as it was on a premise that was simply false.
552
- *
553
- * `conversion/derive.ts` asks this hook and, with nothing installed,
554
- * answers `never('the runtime does not distinguish null with an exact
555
- * tag')`. The runtime distinguishes it precisely: `Value::Tag::Null` is its
556
- * own enumerator, `dynamicTagFor` already WRITES it on the boxing side, and
557
- * `DynamicCarrier<std::nullptr_t>::accepts` already tests it. What was
558
- * missing was only the read.
559
- *
560
- * `null` has no PAYLOAD, which is not the same as having no VALUE -- its
561
- * carrier is `std::nullptr_t`, whose one inhabitant is `nullptr` -- so this
562
- * is the identical verify-then-produce `undefined` gets, never a payload
563
- * load. `gea::detail::unboxNullValue`.
564
- *
565
- * The cost of its absence was not one conversion: `deriveTaggedUnion`
566
- * derives one arm at a time and a single `never` arm makes the whole sum
567
- * `never`, so EVERY nullable tagged-union read out of a box was refused --
568
- * 15 of the three.js app's 74 unmet obligations, all on this one arm.
569
- */
570
- nullMaterializer: () => ({
571
- classifier: { id: 'gea::Value::tag', domain: 'tag:Null' },
572
- materializer: { id: 'gea::detail::unboxNullValue', domain: 'tag:Null', allocates: false }
573
- }),
574
- /**
575
- * `gea::Optional<T>` records only presence/absence, with no memory of which
576
- * JavaScript absent value a caller meant -- so the runtime TAG that marks a
577
- * dynamic value's own absence is the only place that fact still lives, and
578
- * this backend already writes `Tag::Null`/`Tag::Undefined` for exactly those
579
- * two on the boxing side (`dynamicTagFor`). Reading the two spellings apart
580
- * is just naming that same pair back for the unboxing side.
581
- */
582
- optionalAbsenceTag: (absence) => (absence === 'null' ? 'gea::Value::Tag::Null' : 'gea::Value::Tag::Undefined'),
583
- /**
584
- * Reading a class instance back out of a box, discriminated by the payload's
585
- * own recorded C++ type rather than by its tag.
586
- *
587
- * The tag cannot do this job, and the header above overstates the case by
588
- * concluding from that that the box cannot do it at all. Both the limit and
589
- * the overstatement are specific: `Tag::Object` is shared by a record, a
590
- * class instance, an array and a host handle (`dynamicTagFor`), so a
591
- * `tag:Object` domain would not be disjoint across those four and `as<T>()`
592
- * over it would be a `static_pointer_cast` to whichever type the reader
593
- * happened to name. What actually discriminates is `payloadType()`:
594
- * `Value::box` records `payloadTypeTagFor<std::decay_t<T>>()` for EVERY
595
- * payload it stores -- one program-wide address per C++ type, `typeid`
596
- * without RTTI -- and `gea::detail::unboxAs` compares the tag AND that
597
- * address, refusing by name when either disagrees. That is a real classifier
598
- * over a really-stored fact, which is why the domain below is keyed on the
599
- * class identity and not on the tag.
600
- *
601
- * Both halves of the round trip were already built and only this entry was
602
- * missing: `dynamicTagFor` boxes `class-ref`, and `unboxedLoadText` renders
603
- * `unboxValue<T>` for every tag except the three with no payload to read.
604
- * `dynamicTagFor`'s own comment writes this same argument out for
605
- * `typed-array`, which reached the identical conclusion by the identical
606
- * route.
607
- *
608
- * Only `shared-refcount` is installed. The other two are refused with a
609
- * reason rather than left for later, because for each of them the refusal is
610
- * the correct permanent answer as the runtime currently stands:
611
- *
612
- * - `borrowed` spells `Foo&` (`cppOwnershipWrap`), and `box` decays the
613
- * reference away before recording the type, so `payloadTypeTagFor<Foo&>`
614
- * cannot equal what any box holds. Installing it would emit a load that
615
- * aborts on every execution rather than one that sometimes works.
616
- * `narrowing` above refuses borrowed targets for a separate lifetime
617
- * reason, and both reasons apply here.
618
- * - `owned` spells a bare `Foo`, which `unboxValue` reaches by
619
- * copy-constructing from the `const Foo&` `unboxAs` hands back, while
620
- * boxing the same value needs only a MOVE (`makeRef<std::decay_t<T>>`
621
- * forwards). So the question is whether any emitted struct is
622
- * copy-constructible, and that is decidable rather than speculative:
623
- * `records.ts` writes no copy constructor and no assignment operator at
624
- * all, so copyability is never a property of the class this compiler
625
- * emits -- it is implicitly derived from the FIELD carriers. Surveying
626
- * every emitted struct across the corpus gives a closed carrier
627
- * vocabulary, and `is_copy_constructible_v` holds for all of the ones this
628
- * header owns (`double`, `bool`, `long long`, `std::string`,
629
- * `gea::Optional<T>`, `gea::TaggedUnion<...>`, `gea::Ref<T>`,
630
- * `gea::Value`) and for a struct built from them.
631
- *
632
- * What is still unproven is the HOST-owned carriers a struct can also hold
633
- * -- `gea::apple::UIKit::*`, `embedded::ui::Signal<T>`, `NodeHandle`,
634
- * `CanvasRenderingContext2D` -- which live in headers this survey did not
635
- * reach. One move-only type among them is all it takes, and it would fail
636
- * as a clang error inside a generated struct rather than at the entry that
637
- * licensed it. So this stays refused until that half is checked too: a
638
- * narrower reason than the one first written here, and the honest one.
639
- */
640
- classRefMaterializer: (declaration, ownership) => {
641
- if (ownership !== 'shared-refcount')
642
- return null;
643
- // A class projection is authenticated by the allocation's emitted class
644
- // family, not by the static `Ref<T>` spelling the writer happened to box:
645
- // a Ref<Base> may carry a Derived allocation. `unboxClassRef` checks the
646
- // same family table and retains the original allocation, so this domain is
647
- // intentionally nominal rather than a payload-type claim.
648
- const domain = `class-family:${declaration}:${ownership}`;
649
- return {
650
- classifier: { id: 'gea::Value::classIdentity', domain },
651
- materializer: { id: 'gea::detail::unboxClassRef', domain, allocates: false }
652
- };
653
- },
654
- // The compiler's own opaque host carrier is `NativeHandle<protocol>`: its
655
- // generated tag is an authenticated, copyable host identity, and an exact
656
- // payload read preserves that handle (and therefore host sidecars) without
657
- // reconstructing a native object. A plugin-provided C++ spelling may be a
658
- // value struct, an alias, or a handle; `nativeTypes` communicates only that
659
- // spelling, not that it is a dynamic identity carrier, so it stays refused
660
- // until the plugin publishes that stronger fact explicitly.
661
- nativeHandleMaterializer: (protocol, version, native) => {
662
- if (native !== null)
663
- return null;
664
- const domain = `opaque-native-handle:${protocol}@${version}`;
665
- return {
666
- classifier: { id: 'gea::Value::payloadType', domain },
667
- materializer: { id: 'gea::detail::unboxValue', domain, allocates: false }
668
- };
669
- },
670
- // Compiler-owned records have a closed field census, so a dynamic object can
671
- // materialize one only by checking object-ness, every required key, and every
672
- // declared field. `emit-narrowing.ts` renders that recipe. A boxed record of
673
- // the exact target type is merely its identity-preserving fast path; it does
674
- // not replace this product capability with an identity-only conversion.
675
- recordMaterializer: (shapeId, ownership) => {
676
- if (ownership === 'borrowed')
677
- return null;
678
- const domain = `record-product:${shapeId}:${ownership}`;
679
- return {
680
- id: 'gea::detail::unboxDynamicRecord',
681
- domain,
682
- allocates: ownership === 'shared-refcount'
683
- };
684
- },
685
- /**
686
- * Reading a record -- compiler-owned layout or host-stated native type
687
- * alike -- back out of a box BY IDENTITY, the exact mirror of
688
- * `classRefMaterializer` immediately above and installed on the identical
689
- * evidence.
690
- *
691
- * `Value::box` records `payloadTypeTagFor<std::decay_t<T>>()` for whatever
692
- * C++ type it stores, so a `gea::Ref<gea_record_type_N>` or a
693
- * `gea::Ref<gea::runtime::Date>` this program boxed records that exact
694
- * address, and `gea::detail::unboxValue<T>` -- the same primitive
695
- * `classRefMaterializer` uses, which `emit-narrowing.ts`'s `unboxedLoadText`
696
- * already renders through its generic `dynamicTagFor(target)` fallback --
697
- * checks both the tag and that address before handing the payload back. No
698
- * emitter change: both halves of the round trip were already built.
699
- *
700
- * Handing back the SAME object rather than a rebuild is the point. The
701
- * Compiler-owned records use `recordMaterializer`'s checked product path;
702
- * native records do not publish fields this compiler can walk, so this exact
703
- * identity recovery is their only admissible dynamic conversion.
704
- *
705
- * `shared-refcount` only, for the two reasons `classRefMaterializer`'s own
706
- * doc states in full: `borrowed` spells `Foo&`, which `box` decays away
707
- * before recording the type, so no box can ever match it; and `owned`
708
- * spells a bare `Foo`, whose copy-constructibility across every HOST carrier
709
- * a struct can hold is unchecked. Both stay refused rather than emitting a
710
- * load that aborts.
711
- */
712
- /**
713
- * A carrier read back out of the box BY IDENTITY -- the same round trip
714
- * `recordRefMaterializer` performs for a named record shape, for the
715
- * carriers that have no shape id to key on.
716
- *
717
- * Gated on `dynamicTagFor` answering, which is the one authority for which
718
- * carriers this backend boxes at all, so a value can never be admitted here
719
- * under a tag the boxing direction does not write. Gated on
720
- * `shared-refcount` for the reasons `classRefMaterializer` states in full:
721
- * `borrowed` spells `Foo&`, which `box` decays away before recording the
722
- * type, and `owned` spells a bare `Foo` whose copy-constructibility is
723
- * unchecked.
724
- *
725
- * `record`/`native-record-ref`/`class-ref`/`array-object` are deliberately
726
- * NOT routed here even though they would qualify -- each already has its own
727
- * entry with its own reasoning, and a second answer to the same question is
728
- * how two authorities drift apart.
729
- */
730
- boxedIdentityMaterializer: (target) => {
731
- const eligible = (target.kind === 'dictionary' || target.kind === 'record-with-index' || target.kind === 'typed-array') &&
732
- target.ownership === 'shared-refcount';
733
- if (!eligible && target.kind !== 'array-buffer' && target.kind !== 'shared-array-buffer')
734
- return null;
735
- if (dynamicTagFor(target) === null)
736
- return null;
737
- const domain = `boxed-identity:${representationKey(target)}`;
738
- return {
739
- classifier: { id: 'gea::Value::payloadType', domain },
740
- materializer: { id: 'gea::detail::unboxValue', domain, allocates: false }
741
- };
742
- },
743
- recordRefMaterializer: (shapeId, ownership) => {
744
- if (ownership !== 'shared-refcount')
745
- return null;
746
- const domain = `record-payload:${shapeId}:${ownership}`;
747
- return {
748
- classifier: { id: 'gea::Value::payloadType', domain },
749
- materializer: { id: 'gea::detail::unboxValue', domain, allocates: false }
750
- };
751
- },
752
- /**
753
- * Reading a materializable ordinary Array back out of a box -- the
754
- * MATERIALIZING direction (a genuinely dynamic value becoming a native
755
- * shape at a point the program requires one), never the boxing shortcut:
756
- * see `classRefMaterializer`'s own doc comment immediately above for the
757
- * exact discipline this mirrors.
758
- *
759
- * `Value::box`'s payload-type recording is generic over EVERY C++ type it
760
- * stores (`payloadTypeTagFor<std::decay_t<T>>()`, see `classRefMaterializer`'s
761
- * comment), so `gea::ArrayObject<Element>` is not a special case for it --
762
- * an array literal boxed into `dynamic` elsewhere in the SAME program (the
763
- * mirror widening this same registry's `widening` entry below already
764
- * installs for any `array-object` source, via `dynamicTagFor`'s existing
765
- * `'array-object' -> 'Object'` case) records that exact address, and
766
- * `gea::detail::unboxValue<T>` -- the SAME primitive `classRefMaterializer`
767
- * uses, and the one `emit-narrowing.ts`'s `unboxedLoadText` ALREADY renders
768
- * for every non-tagged-union target via its generic `dynamicTagFor(target)`
769
- * + `unboxValue<cppTypeOf(target)>` fallback -- checks both the tag and
770
- * that address before handing the payload back. So this entry needs no
771
- * emitter change at all: both halves of the round trip were already built,
772
- * the exact shape `classRefMaterializer`'s own doc names as the reason it
773
- * was missing for as long as it was.
774
- *
775
- * `unboxValue<Ref<ArrayObject<Element>>>` hands back a REFERENCE-COUNTED
776
- * pointer to the SAME underlying `ArrayObject` the box recorded -- not a
777
- * reconstruction -- so both properties `deriveArrayObject` requires hold
778
- * honestly: identity is the original object, not a copy, and every hole
779
- * `ArrayObject`'s own presence-bit storage tracked survives untouched,
780
- * because nothing about it was rebuilt.
781
- *
782
- * Restricted to `shared-refcount` for the identical reason
783
- * `classRefMaterializer` restricts to it: a `borrowed` target has no
784
- * lifetime a materialized value can honestly hold (`narrowing` above
785
- * refuses borrowed targets for the same reason), and `owned`'s
786
- * copy-constructibility across every carrier this backend can select as an
787
- * array element is unproven the same way it is for a class instance's own
788
- * fields -- narrower than a blanket refusal, and the honest boundary of
789
- * what has actually been checked.
790
- */
791
- arrayObjectDomain: (ownership) => {
792
- if (ownership !== 'shared-refcount')
793
- return null;
794
- return {
795
- classifier: { id: 'gea::Value::payloadType', domain: `array-payload:${ownership}` },
796
- excluded: [],
797
- preservesHoles: true,
798
- preservesIdentity: true
799
- };
800
- },
801
- // The sum classifier is the emitter's actual condition: one exact tag and
802
- // payload type, or an authenticated program-class family. A nested arm has
803
- // several possible conditions and this algebra has no disjunctive classifier
804
- // contract, so it remains explicitly refused rather than smuggling a
805
- // checker-only semantic type into a fake runtime domain.
806
- taggedUnionArmClassifier: cppTaggedUnionArmClassifier,
807
- narrowing: (source, target) => {
808
- // Presence loads and native class casts below inspect tags/allocation
809
- // identity, never a property's reflection protocol. State that on the
810
- // installed materializer, where the implementation is known; the IR
811
- // census must not reconstruct it from a helper name or a carrier kind.
812
- // General union selections remain unannotated because their renderer can
813
- // adapt a compatible arm through another conversion.
814
- // A target the backend cannot spell has no load: there is no C++ type for
815
- // it to produce. Asking the one authoritative type mapping keeps this from
816
- // becoming a second opinion about what is spellable.
817
- if (!isSpellable(target))
818
- return null;
819
- // A borrowed target is refused, and not for lack of syntax. `gea::Optional`
820
- // and `gea::TaggedUnion` both own their contents, so the reference a load
821
- // would hand back points into the cell -- which outlives nothing the caller
822
- // can see, and whose lifetime the program never stated.
823
- if ('ownership' in target && target.ownership === 'borrowed')
824
- return null;
825
- if (classArmWithoutHome(layouts, source, target))
826
- return null;
827
- const setPair = genericFunctionSetPair(source, target);
828
- if (setPair)
829
- return setPair;
830
- // The payload read as the array-extending interface it also is
831
- // (`sameArrayUpToExtension`): the presence proof is the same and the load
832
- // is the same, since both carriers are one C++ type.
833
- if (source.kind === 'optional' &&
834
- (representationKey(source.payload) === representationKey(target) || sameArrayUpToExtension(source.payload, target))) {
835
- return {
836
- classifier: { id: 'gea::Optional::has_value', domain: 'present-optional' },
837
- materializer: {
838
- id: 'gea::Optional::operator*',
839
- domain: 'present-optional',
840
- allocates: false,
841
- nativeFieldProtocol: 'unused',
842
- nativePayloadTransport: 'preserved',
843
- ...nativeClassReferenceIdentityOf(source, target)
844
- }
845
- };
846
- }
847
- // The mirror of the presence narrowing directly above: the guard proved the
848
- // cell ABSENT, and the read carries the absent value's own carrier. There is
849
- // nothing in the cell to load -- `null`'s carrier is `std::nullptr_t` and
850
- // `undefined`'s is `gea::Undefined`, and each has exactly one inhabitant --
851
- // so the materializer produces that constant. Gated on the two absences
852
- // AGREEING: an `optional(T,undefined)` narrowed by `x === null` is not this
853
- // pair, and the checker would not have produced it.
854
- if (source.kind === 'optional' && target.kind === source.absence) {
855
- return {
856
- classifier: { id: 'gea::Optional::has_value', domain: `absent-optional:${source.absence}` },
857
- materializer: {
858
- id: 'gea::constant',
859
- domain: `absent-optional:${source.absence}`,
860
- allocates: false,
861
- nativeFieldProtocol: 'unused',
862
- ...nativeClassReferenceIdentityOf(source, target)
863
- }
864
- };
865
- }
866
- // A structural value read as an instance of a class nothing can
867
- // instantiate. No such instance exists, so a guard that narrowed to it --
868
- // `incoming instanceof Http2ServerRequest` -- never passes, and the
869
- // instance-test census renders that guard only when it proved the view
870
- // cannot hold one (`projection/instance-test.ts`). The load is the branch's
871
- // own unreachability, never a value.
872
- if (target.kind === 'class-ref' &&
873
- layouts.classUninstantiable?.(target.declaration) === true &&
874
- (source.kind === 'record' ||
875
- source.kind === 'record-with-index' ||
876
- source.kind === 'dictionary' ||
877
- (source.kind === 'native-record-ref' && source.native === null))) {
878
- const domain = `uninstantiable-class:${representationKey(target)}`;
879
- return {
880
- classifier: { id: 'gea::host::neverInstance', domain },
881
- materializer: { id: 'gea::host::unreachableValue', domain, allocates: false, nativeFieldProtocol: 'unused' }
882
- };
883
- }
884
- // A shared structural view read as a class, under the `instanceof` that
885
- // proved it was built from one: the view remembers its origin
886
- // (`gea::record::viewOrigin`) and the origin is narrowed like any boxed
887
- // class instance, checked. An optional view is the same read of its
888
- // payload, which the test proved present.
889
- const sharedView = (value) => (value.kind === 'record' || value.kind === 'record-with-index' || (value.kind === 'native-record-ref' && value.native === null)) &&
890
- value.ownership === 'shared-refcount';
891
- if (target.kind === 'class-ref' &&
892
- target.ownership === 'shared-refcount' &&
893
- (sharedView(source) || (source.kind === 'optional' && sharedView(source.payload)))) {
894
- const domain = `view-origin:${representationKey(target)}`;
506
+ /**
507
+ * The registry's per-pair claim, as `recordViewUsesOnlyDirectFields` asks it
508
+ * of a held field converted into the view's carrier. A recursive record
509
+ * (`Filter<T>` holds `Filter<T>[]`) revisits its own pair; the claim is
510
+ * coinductive, so a pair already being asked answers `true` and every other
511
+ * obligation on the cycle is still asked in its own frame.
512
+ */
513
+ const heldPairsInProgress = new Set();
514
+ const heldPairUnusedOf = (wrapped) => (from, to) => {
515
+ const pair = `${representationKey(from)}->${representationKey(to)}`;
516
+ if (heldPairsInProgress.has(pair))
517
+ return true;
518
+ heldPairsInProgress.add(pair);
519
+ try {
520
+ return wrapped(from, to).nativeFieldProtocol === 'unused';
521
+ }
522
+ finally {
523
+ heldPairsInProgress.delete(pair);
524
+ }
525
+ };
526
+ const cppConversionTables = (layouts, nativeNarrowing, nativeWrappedPayload) => {
527
+ // A rebuilt view's claim: native when every read is direct, otherwise the
528
+ // per-field conversions it still performs (`recordViewResidualReflection`).
529
+ const viewProtocolOf = (plan) => {
530
+ const heldUnused = heldPairUnusedOf(nativeWrappedPayload);
531
+ if (recordViewUsesOnlyDirectFields(plan, heldUnused))
532
+ return { nativeFieldProtocol: 'unused' };
533
+ const residual = recordViewResidualReflection(plan, heldUnused);
534
+ return residual === null ? {} : { residualReflection: residual };
535
+ };
536
+ return {
537
+ ...emptyConversionRegistry,
538
+ stringMaterializer: () => exactTagRead('String'),
539
+ /**
540
+ * `gea::Symbol` out of a box is the same exact-tag read as a string: the
541
+ * printer's `unboxedLoadText` spells it `unboxValue<gea::Symbol>(v,
542
+ * Tag::Symbol, ...)` off `dynamicTagFor`'s own `symbol -> 'Symbol'` row.
543
+ * The registry left this `null` while the printer rendered it, so a
544
+ * `typeof x === 'symbol'` narrowing certified nothing (no installed exact
545
+ * symbol-tag materializer) on a program the printer had always emitted --
546
+ * the census/printer disagreement Phase 2.3's emission gate exists to
547
+ * surface, found on `symbol-description.runtime.js`.
548
+ */
549
+ symbolMaterializer: () => exactTagRead('Symbol'),
550
+ scalarMaterializer: (domain) => domain === 'number'
551
+ ? exactTagRead('Number')
552
+ : domain === 'boolean'
553
+ ? exactTagRead('Boolean')
554
+ : domain === 'bigint'
555
+ ? exactTagRead('BigInt')
556
+ : null,
557
+ /**
558
+ * `undefined` out of a box: `exactTagRead` above cannot serve this either,
559
+ * for the identical reason `gea::detail::unboxUndefinedValue`
560
+ * (gea_runtime.h) exists instead of reusing `unboxValue<T>` -- there is no
561
+ * payload, so no `T` to have recorded a `payloadTypeTagFor` for. The tag
562
+ * alone is the whole check; a mismatch aborts by name, exactly the same
563
+ * refusal discipline as every other exact-tag read in this registry.
564
+ */
565
+ undefinedMaterializer: () => ({
566
+ classifier: { id: 'gea::Value::tag', domain: 'tag:Undefined' },
567
+ materializer: { id: 'gea::detail::unboxUndefinedValue', domain: 'tag:Undefined', allocates: false }
568
+ }),
569
+ /**
570
+ * A bare `Function` is intentionally dynamic: it promises `[[Call]]`, but
571
+ * no static parameter or result types. The runtime's
572
+ * `DynamicCarrier<CallableObject<R(A...)>>::in` is the checked bridge from
573
+ * that boundary. It verifies `Tag::Function`, preserves an exact-ABI value
574
+ * directly when possible, and otherwise returns a callable adapter that
575
+ * boxes the target ABI's arguments, invokes the source box, and checks the
576
+ * returned value as `R`.
577
+ *
578
+ * Install only the ABI presently proved end to end: a receiver-less,
579
+ * fixed-arity numeric comparator whose arguments are themselves dynamic
580
+ * values. This is Three's public `Function | null` sort hook. Broadening the
581
+ * predicate requires matching `DynamicCarrier<T>::supported` for every new
582
+ * parameter/result carrier; guessing there would move an honest preflight
583
+ * refusal into a C++ template failure.
584
+ */
585
+ functionValueDispatchMaterializer: (abi) => {
586
+ const target = { kind: 'function-value-dispatch', abi };
587
+ return dynamicCallableAbiSupported(abi) ? dynamicCallablePair(target) : null;
588
+ },
589
+ functionMaterializer: (functionId, abi) => {
590
+ if (!dynamicCallableAbiSupported(abi))
591
+ return null;
592
+ const domain = `dynamic-callable-identity:${functionId}:${representationKey({ kind: 'function', functionId, abi })}`;
895
593
  return {
896
- classifier: { id: 'gea::record::viewOriginIs', domain },
897
- materializer: { id: 'gea::record::viewOrigin', domain, allocates: false, nativeFieldProtocol: 'unused' }
594
+ classifier: { id: 'gea::Value::callableDeclarationIdentity', domain },
595
+ materializer: { id: 'gea::detail::DynamicCarrier::in', domain, allocates: true }
898
596
  };
899
- }
900
- // A base class-ref read at a descendant -- see `downcastsToDerived` above.
901
- // `downcastClassRef` (gea_runtime.h) is `Ref::staticCast`, which adopts
902
- // `static_cast<Derived*>` of the SAME pointee: the payload travels as the
903
- // object it already was, so payload transport is preserved as well.
904
- if (downcastsToDerived(source, target)) {
597
+ },
598
+ /**
599
+ * `null` out of a box: the exact sibling of `undefinedMaterializer` above,
600
+ * and absent for as long as it was on a premise that was simply false.
601
+ *
602
+ * `conversion/derive.ts` asks this hook and, with nothing installed,
603
+ * answers `never('the runtime does not distinguish null with an exact
604
+ * tag')`. The runtime distinguishes it precisely: `Value::Tag::Null` is its
605
+ * own enumerator, `dynamicTagFor` already WRITES it on the boxing side, and
606
+ * `DynamicCarrier<std::nullptr_t>::accepts` already tests it. What was
607
+ * missing was only the read.
608
+ *
609
+ * `null` has no PAYLOAD, which is not the same as having no VALUE -- its
610
+ * carrier is `std::nullptr_t`, whose one inhabitant is `nullptr` -- so this
611
+ * is the identical verify-then-produce `undefined` gets, never a payload
612
+ * load. `gea::detail::unboxNullValue`.
613
+ *
614
+ * The cost of its absence was not one conversion: `deriveTaggedUnion`
615
+ * derives one arm at a time and a single `never` arm makes the whole sum
616
+ * `never`, so EVERY nullable tagged-union read out of a box was refused --
617
+ * 15 of the three.js app's 74 unmet obligations, all on this one arm.
618
+ */
619
+ nullMaterializer: () => ({
620
+ classifier: { id: 'gea::Value::tag', domain: 'tag:Null' },
621
+ materializer: { id: 'gea::detail::unboxNullValue', domain: 'tag:Null', allocates: false }
622
+ }),
623
+ /**
624
+ * `gea::Optional<T>` records only presence/absence, with no memory of which
625
+ * JavaScript absent value a caller meant -- so the runtime TAG that marks a
626
+ * dynamic value's own absence is the only place that fact still lives, and
627
+ * this backend already writes `Tag::Null`/`Tag::Undefined` for exactly those
628
+ * two on the boxing side (`dynamicTagFor`). Reading the two spellings apart
629
+ * is just naming that same pair back for the unboxing side.
630
+ */
631
+ optionalAbsenceTag: (absence) => (absence === 'null' ? 'gea::Value::Tag::Null' : 'gea::Value::Tag::Undefined'),
632
+ /**
633
+ * Reading a class instance back out of a box, discriminated by the payload's
634
+ * own recorded C++ type rather than by its tag.
635
+ *
636
+ * The tag cannot do this job, and the header above overstates the case by
637
+ * concluding from that that the box cannot do it at all. Both the limit and
638
+ * the overstatement are specific: `Tag::Object` is shared by a record, a
639
+ * class instance, an array and a host handle (`dynamicTagFor`), so a
640
+ * `tag:Object` domain would not be disjoint across those four and `as<T>()`
641
+ * over it would be a `static_pointer_cast` to whichever type the reader
642
+ * happened to name. What actually discriminates is `payloadType()`:
643
+ * `Value::box` records `payloadTypeTagFor<std::decay_t<T>>()` for EVERY
644
+ * payload it stores -- one program-wide address per C++ type, `typeid`
645
+ * without RTTI -- and `gea::detail::unboxAs` compares the tag AND that
646
+ * address, refusing by name when either disagrees. That is a real classifier
647
+ * over a really-stored fact, which is why the domain below is keyed on the
648
+ * class identity and not on the tag.
649
+ *
650
+ * Both halves of the round trip were already built and only this entry was
651
+ * missing: `dynamicTagFor` boxes `class-ref`, and `unboxedLoadText` renders
652
+ * `unboxValue<T>` for every tag except the three with no payload to read.
653
+ * `dynamicTagFor`'s own comment writes this same argument out for
654
+ * `typed-array`, which reached the identical conclusion by the identical
655
+ * route.
656
+ *
657
+ * Only `shared-refcount` is installed. The other two are refused with a
658
+ * reason rather than left for later, because for each of them the refusal is
659
+ * the correct permanent answer as the runtime currently stands:
660
+ *
661
+ * - `borrowed` spells `Foo&` (`cppOwnershipWrap`), and `box` decays the
662
+ * reference away before recording the type, so `payloadTypeTagFor<Foo&>`
663
+ * cannot equal what any box holds. Installing it would emit a load that
664
+ * aborts on every execution rather than one that sometimes works.
665
+ * `narrowing` above refuses borrowed targets for a separate lifetime
666
+ * reason, and both reasons apply here.
667
+ * - `owned` spells a bare `Foo`, which `unboxValue` reaches by
668
+ * copy-constructing from the `const Foo&` `unboxAs` hands back, while
669
+ * boxing the same value needs only a MOVE (`makeRef<std::decay_t<T>>`
670
+ * forwards). So the question is whether any emitted struct is
671
+ * copy-constructible, and that is decidable rather than speculative:
672
+ * `records.ts` writes no copy constructor and no assignment operator at
673
+ * all, so copyability is never a property of the class this compiler
674
+ * emits -- it is implicitly derived from the FIELD carriers. Surveying
675
+ * every emitted struct across the corpus gives a closed carrier
676
+ * vocabulary, and `is_copy_constructible_v` holds for all of the ones this
677
+ * header owns (`double`, `bool`, `long long`, `std::string`,
678
+ * `gea::Optional<T>`, `gea::TaggedUnion<...>`, `gea::Ref<T>`,
679
+ * `gea::Value`) and for a struct built from them.
680
+ *
681
+ * What is still unproven is the HOST-owned carriers a struct can also hold
682
+ * -- `gea::apple::UIKit::*`, `embedded::ui::Signal<T>`, `NodeHandle`,
683
+ * `CanvasRenderingContext2D` -- which live in headers this survey did not
684
+ * reach. One move-only type among them is all it takes, and it would fail
685
+ * as a clang error inside a generated struct rather than at the entry that
686
+ * licensed it. So this stays refused until that half is checked too: a
687
+ * narrower reason than the one first written here, and the honest one.
688
+ */
689
+ classRefMaterializer: (declaration, ownership) => {
690
+ if (ownership !== 'shared-refcount')
691
+ return null;
692
+ // A class projection is authenticated by the allocation's emitted class
693
+ // family, not by the static `Ref<T>` spelling the writer happened to box:
694
+ // a Ref<Base> may carry a Derived allocation. `unboxClassRef` checks the
695
+ // same family table and retains the original allocation, so this domain is
696
+ // intentionally nominal rather than a payload-type claim.
697
+ const domain = `class-family:${declaration}:${ownership}`;
905
698
  return {
906
- classifier: { id: 'gea::host::hasNativeClassLayoutRef', domain: `class-descendant:${representationKey(target)}` },
907
- materializer: {
908
- id: 'gea::host::downcastClassRef',
909
- domain: `class-descendant:${representationKey(target)}`,
910
- allocates: false,
911
- nativeFieldProtocol: 'unused',
912
- nativePayloadTransport: 'preserved',
913
- ...nativeClassReferenceIdentityOf(source, target)
914
- }
699
+ classifier: { id: 'gea::Value::classIdentity', domain },
700
+ materializer: { id: 'gea::detail::unboxClassRef', domain, allocates: false }
915
701
  };
916
- }
917
- // The same handle read at a UNION of descendants -- `object instanceof Mesh
918
- // || object instanceof Line || object instanceof Points`. The physical
919
- // carrier stays one `Ref<Base>`; allocation identity is the discriminant,
920
- // so the classifier is the same family test and the materializer the same
921
- // checked downcast, applied per arm by `emit-narrowing.ts`'s
922
- // `classFamilyLoadText`. `conversion/build.ts` owns the predicate and this
923
- // imports it, so the pair this admits is exactly the pair that proposed it.
924
- if (narrowsToDescendantClassUnion(source, target)) {
702
+ },
703
+ // The compiler's own opaque host carrier is `NativeHandle<protocol>`: its
704
+ // generated tag is an authenticated, copyable host identity, and an exact
705
+ // payload read preserves that handle (and therefore host sidecars) without
706
+ // reconstructing a native object. A plugin-provided C++ spelling may be a
707
+ // value struct, an alias, or a handle; `nativeTypes` communicates only that
708
+ // spelling, not that it is a dynamic identity carrier, so it stays refused
709
+ // until the plugin publishes that stronger fact explicitly.
710
+ nativeHandleMaterializer: (protocol, version, native) => {
711
+ if (native !== null)
712
+ return null;
713
+ const domain = `opaque-native-handle:${protocol}@${version}`;
925
714
  return {
926
- classifier: { id: 'gea::host::hasNativeClassLayoutRef', domain: `class-descendant-union:${representationKey(target)}` },
927
- materializer: {
928
- id: 'gea::host::downcastClassRef',
929
- domain: `class-descendant-union:${representationKey(target)}`,
930
- allocates: false,
931
- nativeFieldProtocol: 'unused',
932
- // Each arm is `ofArm<I>(downcastClassRef<D>(held))`: one pointee,
933
- // injected into the target union (and its optional, if any).
934
- nativePayloadTransport: 'preserved',
935
- ...nativeClassReferenceIdentityOf(source, target)
936
- }
715
+ classifier: { id: 'gea::Value::payloadType', domain },
716
+ materializer: { id: 'gea::detail::unboxValue', domain, allocates: false }
937
717
  };
938
- }
939
- // The census asks this table before widening. A total native transfer
940
- // must therefore win here too; otherwise the broad subset fallback below
941
- // can shadow its selected recipe and lose its payload identity contract.
942
- const nativeSelection = nativeTotalSelectionRecipeOf(source, target) ??
943
- ((source.kind === 'optional' || source.kind === 'tagged-union') && narrowingReachesTarget(source, target)
944
- ? nativeSelectionRecipeOf(source, target)
945
- : null);
946
- if (nativeSelection)
947
- return nativeSelectionConversion(source, target, nativeSelection);
948
- if ((source.kind === 'optional' || source.kind === 'tagged-union') &&
949
- target.kind === 'class-ref' &&
950
- narrowingReachesTarget(source, target)) {
718
+ },
719
+ // Compiler-owned records have a closed field census, so a dynamic object can
720
+ // materialize one only by checking object-ness, every required key, and every
721
+ // declared field. `emit-narrowing.ts` renders that recipe. A boxed record of
722
+ // the exact target type is merely its identity-preserving fast path; it does
723
+ // not replace this product capability with an identity-only conversion.
724
+ recordMaterializer: (shapeId, ownership) => {
725
+ if (ownership === 'borrowed')
726
+ return null;
727
+ const domain = `record-product:${shapeId}:${ownership}`;
951
728
  return {
952
- classifier: { id: 'gea::host::hasNativeClassLayoutRef', domain: `class-descendant-sum:${representationKey(target)}` },
953
- materializer: {
954
- id: 'gea::host::downcastClassRef',
955
- domain: `class-descendant-sum:${representationKey(target)}`,
956
- allocates: false,
957
- // Presence and sum selection over native class handles never reads
958
- // field values. Mixed sums retain their general converting protocol.
959
- ...(nativeClassPresence(source)
960
- ? { nativeFieldProtocol: 'unused', ...nativeClassReferenceIdentityOf(source, target) }
961
- : {})
962
- }
729
+ id: 'gea::detail::unboxDynamicRecord',
730
+ domain,
731
+ allocates: ownership === 'shared-refcount'
963
732
  };
964
- }
965
- // Selecting one arm of a union, either directly or through an optional the
966
- // same narrowing also proved present. `gea::TaggedUnion::is<Index>` is the
967
- // discriminant test and `get<Index>` is the load, and both are indexed by
968
- // the arm's position in `representation.arms` -- the checker's own order,
969
- // which is what the emitter already uses to build one.
970
- //
971
- // More than one arm may carry the target's C++ type: `A | B | C` where all
972
- // three lower to `std::string` is one narrowing target with three possible
973
- // live arms. That is a fact about the load -- it dispatches on which arm is
974
- // live -- not about whether the capability exists, so it does not change
975
- // the answer here.
976
- //
977
- // The target may itself still be an optional: narrowing `A | B | undefined`
978
- // to `A | undefined` rules out an arm and proves nothing about presence, so
979
- // both sides unwrap before the arms are compared and the load rebuilds the
980
- // optional around whichever arm it read.
981
- const union = source.kind === 'optional' ? source.payload : source;
982
- const selected = source.kind === 'optional' && target.kind === 'optional' ? target.payload : target;
983
- if (union.kind !== 'tagged-union')
984
- return null;
985
- // A record-shaped target some OTHER arm reaches only through the
986
- // structural view is not a selection: that arm is live at a store, and a
987
- // selection would read it as the exact arm. The view's `dispatch` plan
988
- // (`conversion/record-view.ts`) is the conversion, installed by
989
- // `staticRecipe` below once this table declines -- the same plan
990
- // `emit-narrowing.ts`'s `narrowedLoadText` defers to, asked here so the
991
- // admission and the render agree.
992
- if (isRecordViewTarget(selected)) {
993
- const view = viewPlanFor(layouts, source, target);
994
- if (view !== null && recordViewDispatchesArms(view))
733
+ },
734
+ /**
735
+ * Reading a record -- compiler-owned layout or host-stated native type
736
+ * alike -- back out of a box BY IDENTITY, the exact mirror of
737
+ * `classRefMaterializer` immediately above and installed on the identical
738
+ * evidence.
739
+ *
740
+ * `Value::box` records `payloadTypeTagFor<std::decay_t<T>>()` for whatever
741
+ * C++ type it stores, so a `gea::Ref<gea_record_type_N>` or a
742
+ * `gea::Ref<gea::runtime::Date>` this program boxed records that exact
743
+ * address, and `gea::detail::unboxValue<T>` -- the same primitive
744
+ * `classRefMaterializer` uses, which `emit-narrowing.ts`'s `unboxedLoadText`
745
+ * already renders through its generic `dynamicTagFor(target)` fallback --
746
+ * checks both the tag and that address before handing the payload back. No
747
+ * emitter change: both halves of the round trip were already built.
748
+ *
749
+ * Handing back the SAME object rather than a rebuild is the point. The
750
+ * Compiler-owned records use `recordMaterializer`'s checked product path;
751
+ * native records do not publish fields this compiler can walk, so this exact
752
+ * identity recovery is their only admissible dynamic conversion.
753
+ *
754
+ * `shared-refcount` only, for the two reasons `classRefMaterializer`'s own
755
+ * doc states in full: `borrowed` spells `Foo&`, which `box` decays away
756
+ * before recording the type, so no box can ever match it; and `owned`
757
+ * spells a bare `Foo`, whose copy-constructibility across every HOST carrier
758
+ * a struct can hold is unchecked. Both stay refused rather than emitting a
759
+ * load that aborts.
760
+ */
761
+ /**
762
+ * A carrier read back out of the box BY IDENTITY -- the same round trip
763
+ * `recordRefMaterializer` performs for a named record shape, for the
764
+ * carriers that have no shape id to key on.
765
+ *
766
+ * Gated on `dynamicTagFor` answering, which is the one authority for which
767
+ * carriers this backend boxes at all, so a value can never be admitted here
768
+ * under a tag the boxing direction does not write. Gated on
769
+ * `shared-refcount` for the reasons `classRefMaterializer` states in full:
770
+ * `borrowed` spells `Foo&`, which `box` decays away before recording the
771
+ * type, and `owned` spells a bare `Foo` whose copy-constructibility is
772
+ * unchecked.
773
+ *
774
+ * `record`/`native-record-ref`/`class-ref`/`array-object` are deliberately
775
+ * NOT routed here even though they would qualify -- each already has its own
776
+ * entry with its own reasoning, and a second answer to the same question is
777
+ * how two authorities drift apart.
778
+ */
779
+ boxedIdentityMaterializer: (target) => {
780
+ const eligible = (target.kind === 'dictionary' || target.kind === 'record-with-index' || target.kind === 'typed-array') &&
781
+ target.ownership === 'shared-refcount';
782
+ if (!eligible && target.kind !== 'array-buffer' && target.kind !== 'shared-array-buffer' && target.kind !== 'data-view')
995
783
  return null;
996
- }
997
- const targetKey = representationKey(selected);
998
- // A SUB-union target: `selected` is still a tagged union, just missing one
999
- // or more of `union`'s arms -- `h instanceof Headers`'s `else` branch
1000
- // leaving a `Headers | Record<string,string> | [string,string][]` cell
1001
- // narrowed to the latter two. Installed exactly when every one of
1002
- // `selected`'s own arms has a same-shaped home among `union`'s -- the
1003
- // identical admission `emit-narrowing.ts`'s `narrowedUnionSubsetText`
1004
- // checks before it renders the `ofArm<Index>` rebuild, asked here rather
1005
- // than restated so the two cannot disagree about which pairs install.
1006
- if (selected.kind === 'tagged-union') {
1007
- const installed = selected.arms.every((arm) => union.arms.some((candidate) => representationKey(candidate.value) === representationKey(arm.value) ||
1008
- narrowingReachesTarget(candidate.value, arm.value) ||
1009
- downcastsToDerived(candidate.value, arm.value)));
1010
- if (!installed)
784
+ if (dynamicTagFor(target) === null)
1011
785
  return null;
786
+ const domain = `boxed-identity:${representationKey(target)}`;
1012
787
  return {
1013
- classifier: { id: 'gea::TaggedUnion::is', domain: `live-arm-subset:${targetKey}` },
1014
- materializer: {
1015
- id: 'gea::TaggedUnion::ofArm',
1016
- domain: `live-arm-subset:${targetKey}`,
1017
- allocates: false,
1018
- // The discriminant selects; each candidate leaf's own contract says
1019
- // whether the selected payload travels natively.
1020
- ...nativeNarrowing(source, target)
1021
- }
1022
- };
1023
- }
1024
- // A target OPTIONAL whose payload is one of the union's arms, where the
1025
- // union carries no bare absent arm at all -- absence living inside another
1026
- // arm's own optional. `emit-narrowing.ts`'s `narrowedLoadText` renders the
1027
- // arm test as the presence test; this installs the capability it needs.
1028
- if (target.kind === 'optional' && union.arms.some((arm) => representationKey(arm.value) === representationKey(target.payload))) {
1029
- return {
1030
- classifier: { id: 'gea::TaggedUnion::is', domain: `live-arm-optional:${targetKey}` },
1031
- materializer: {
1032
- id: 'gea::TaggedUnion::get',
1033
- domain: `live-arm-optional:${targetKey}`,
1034
- allocates: false,
1035
- ...nativeNarrowing(source, target)
1036
- }
788
+ classifier: { id: 'gea::Value::payloadType', domain },
789
+ materializer: { id: 'gea::detail::unboxValue', domain, allocates: false }
1037
790
  };
1038
- }
1039
- if (!union.arms.some((arm) => representationKey(arm.value) === targetKey)) {
1040
- // An arm the target lives INSIDE, not one that equals it. A narrowing
1041
- // does not stop at the top level: three's `?(string|number|boolean)`
1042
- // field is `undefined | null | (string|number|boolean)`, and a guard past
1043
- // the two absences lands on one of the inner arms -- two steps, and this
1044
- // test saw only one. `narrowingReachesTarget` (`conversion/build.ts`) is
1045
- // the same enumeration that PROPOSED this pair, asked here rather than
1046
- // restated so the admission cannot admit fewer levels than the graph
1047
- // offers, and `emit-narrowing.ts`'s `taggedUnionArmText` recurses through
1048
- // `narrowedLoadText` to render exactly the step this admits.
1049
- if (!narrowingReachesTarget(source, target))
791
+ },
792
+ dynamicPromiseAdoptionMaterializer: (target) => {
793
+ if (target.kind !== 'promise' || !isSpellable(target))
1050
794
  return null;
795
+ const domain = `dynamic-promise-adoption:${representationKey(target)}`;
1051
796
  return {
1052
- classifier: { id: 'gea::TaggedUnion::is', domain: `live-arm-nested:${targetKey}` },
1053
- materializer: {
1054
- id: 'gea::TaggedUnion::get',
1055
- domain: `live-arm-nested:${targetKey}`,
1056
- allocates: false,
1057
- ...nativeNarrowing(source, target)
1058
- }
1059
- };
1060
- }
1061
- return {
1062
- classifier: { id: 'gea::TaggedUnion::is', domain: `live-arm:${targetKey}` },
1063
- materializer: { id: 'gea::TaggedUnion::get', domain: `live-arm:${targetKey}`, allocates: false, ...nativeNarrowing(source, target) }
1064
- };
1065
- },
1066
- // The mirror of `narrowing`: a plain value taking the place of the tagged
1067
- // union (or the union payload of an optional) that declares it as one arm --
1068
- // or, when the target is an optional and the source is exactly its bare
1069
- // payload, no union at all, because `gea::Optional<T>` declares its own
1070
- // converting constructor from `T`. `gea::TaggedUnion::ofArm<Index>` is a
1071
- // real constructor -- built, not assumed -- so the union case is installed
1072
- // exactly when the source's carrier is one of the target union's arms,
1073
- // indexed the same way the emitter already reads one back
1074
- // (`representation.arms`'s own order).
1075
- widening: (source, target) => {
1076
- if (!isSpellable(target))
1077
- return null;
1078
- const nativeSum = nativeSumConversion(source, target);
1079
- if (nativeSum)
1080
- return nativeSum;
1081
- const totalSelection = nativeTotalSelectionRecipeOf(source, target);
1082
- if (totalSelection)
1083
- return nativeSelectionConversion(source, target, totalSelection);
1084
- const setPair = genericFunctionSetPair(source, target);
1085
- if (setPair)
1086
- return setPair;
1087
- const exactDispatch = exactFunctionDispatchPair(source, target);
1088
- if (exactDispatch)
1089
- return exactDispatch;
1090
- const identity = callableIdentityPair(source, target);
1091
- if (identity)
1092
- return identity;
1093
- const constructEntry = callableConstructEntryPair(source, target);
1094
- if (constructEntry)
1095
- return constructEntry;
1096
- // `Function` promises only callability, so crossing into an evaluated
1097
- // callable slot needs the same checked ABI adapter as the generic dynamic
1098
- // materializer above. This pair is proposed explicitly by
1099
- // `wideningSourcesOf`: dynamic provenance is part of a representation's
1100
- // key, and the generic node is intentionally keyed to declared `any`.
1101
- if (source.kind === 'dynamic' &&
1102
- source.reason === 'untyped-callable' &&
1103
- target.kind === 'function-value-dispatch' &&
1104
- dynamicCallableAbiSupported(target.abi)) {
1105
- return dynamicCallablePair(target);
1106
- }
1107
- // A callable declaring a type-matching PREFIX of the target's own
1108
- // parameters widening into it -- `gea::CallableObject`'s own converting
1109
- // constructor (`gea_runtime.h`) performs this, so the pairing this
1110
- // capability approves is exactly the one `dropsUnboundParameters` (the
1111
- // same authority `emit-narrowing.ts`'s renderer asks) proves sound. Asked
1112
- // before the `dynamic`/absence/optional cases below because a callable
1113
- // pair can never satisfy any of those (`callableObjectAbi` inside
1114
- // `dropsUnboundParameters` answers `null` for anything that is not a
1115
- // `function`/`function-family`/`function-value-family`/
1116
- // `function-value-dispatch`), so ordering only ever skips work, never
1117
- // changes an answer.
1118
- if (constructorUpcastMember(source, target) !== null) {
1119
- const domain = `constructor-upcast:${representationKey(source)}->${representationKey(target)}`;
1120
- return {
1121
- classifier: { id: 'gea::upcastConstructor', domain },
1122
- materializer: { id: 'gea::upcastConstructor', domain, allocates: false }
1123
- };
1124
- }
1125
- if (upcastsToBase(source, target)) {
1126
- const sourceKey = representationKey(source);
1127
- const targetKey = representationKey(target);
1128
- return {
1129
- classifier: { id: 'gea::Ref::converting-ctor', domain: `class-upcast:${sourceKey}->${targetKey}` },
1130
- materializer: {
1131
- id: 'gea::Ref::converting-ctor',
1132
- domain: `class-upcast:${sourceKey}->${targetKey}`,
1133
- allocates: false,
1134
- nativeFieldProtocol: 'unused',
1135
- // `Ref<Base>(derived)` retains the same pointee.
1136
- nativePayloadTransport: 'preserved',
1137
- ...nativeClassReferenceIdentityOf(source, target)
1138
- }
1139
- };
1140
- }
1141
- if (dropsUnboundParameters(source, target)) {
1142
- const sourceKey = representationKey(source);
1143
- const targetKey = representationKey(target);
1144
- return {
1145
- classifier: { id: 'gea::CallableObject::converting-ctor', domain: `callable-prefix:${sourceKey}->${targetKey}` },
1146
- materializer: {
1147
- id: 'gea::CallableObject::converting-ctor',
1148
- domain: `callable-prefix:${sourceKey}->${targetKey}`,
1149
- allocates: true,
1150
- ...nativeCallableTransport(source, target)
1151
- }
1152
- };
1153
- }
1154
- // The composed sibling of the pairing just above: a zero-parameter
1155
- // callable widening into a slot that ALSO widens its result into one arm
1156
- // of a tagged union -- `gea_runtime.h`'s `ResultWidensIntoArm` performs
1157
- // both steps as one converting constructor, asked here through
1158
- // `dropsAllParametersIntoResultArm` for the identical reason
1159
- // `dropsUnboundParameters` is asked above it, so the two authorities
1160
- // cannot disagree about which pairs the runtime actually accepts.
1161
- if (dropsAllParametersIntoResultArm(source, target)) {
1162
- const sourceKey = representationKey(source);
1163
- const targetKey = representationKey(target);
1164
- return {
1165
- classifier: { id: 'gea::CallableObject::result-arm-ctor', domain: `callable-result-arm:${sourceKey}->${targetKey}` },
1166
- materializer: {
1167
- id: 'gea::CallableObject::result-arm-ctor',
1168
- domain: `callable-result-arm:${sourceKey}->${targetKey}`,
1169
- allocates: true,
1170
- ...nativeCallableTransport(source, target)
1171
- }
797
+ classifier: { id: 'gea::detail::adoptBoxedPromise', domain },
798
+ materializer: { id: 'gea::detail::promiseFromDynamic', domain, allocates: true }
1172
799
  };
1173
- }
1174
- // The same widening at a nonzero arity the source already declares in
1175
- // full -- `gea_runtime.h`'s `widenResultIntoArm` constructor, gated by the
1176
- // very same `ResultWidensIntoArm` trait as the composed case above.
1177
- // Installed here for the identical reason its two siblings are: the
1178
- // conversion graph decides admissibility, and a pairing the emitter
1179
- // renders but the graph never heard of is refused at certification for a
1180
- // conversion this backend can already perform.
1181
- if (widensResultIntoArm(source, target)) {
1182
- const sourceKey = representationKey(source);
1183
- const targetKey = representationKey(target);
800
+ },
801
+ dynamicMapViewMaterializer: (target) => {
802
+ if (target.kind !== 'keyed-collection' || target.family !== 'map' || target.ownership !== 'shared-refcount')
803
+ return null;
804
+ if (target.recursive !== undefined || target.readOnlyView === true)
805
+ return null;
806
+ if (target.key.kind !== 'dynamic' || target.value?.kind !== 'dynamic')
807
+ return null;
808
+ const domain = `dynamic-map-view:${representationKey(target)}`;
1184
809
  return {
1185
- classifier: {
1186
- id: 'gea::CallableObject::same-arity-result-arm-ctor',
1187
- domain: `callable-result-arm-fixed:${sourceKey}->${targetKey}`
1188
- },
1189
- materializer: {
1190
- id: 'gea::CallableObject::same-arity-result-arm-ctor',
1191
- domain: `callable-result-arm-fixed:${sourceKey}->${targetKey}`,
1192
- allocates: true,
1193
- ...nativeCallableTransport(source, target)
1194
- }
810
+ classifier: { id: 'gea::Value::isMapPayload', domain },
811
+ materializer: { id: 'gea::detail::unboxDynamicMap', domain, allocates: true }
1195
812
  };
1196
- }
1197
- // The rest slot rebased to position 0 -- `gea_runtime.h`'s
1198
- // `spreadRestOverLeading` constructor, gated by the very same
1199
- // `RestRebaseAdmits` trait. Installed here for the identical reason its
1200
- // siblings are: a pairing the emitter renders but the graph never heard
1201
- // of is refused at certification for a conversion this backend performs.
1202
- if (rebasesRestOverLeadingParameters(source, target)) {
1203
- const sourceKey = representationKey(source);
1204
- const targetKey = representationKey(target);
813
+ },
814
+ recordRefMaterializer: (shapeId, ownership) => {
815
+ if (ownership !== 'shared-refcount')
816
+ return null;
817
+ const domain = `record-payload:${shapeId}:${ownership}`;
1205
818
  return {
1206
- classifier: { id: 'gea::CallableObject::rest-rebase-ctor', domain: `callable-rest-rebase:${sourceKey}->${targetKey}` },
1207
- materializer: {
1208
- id: 'gea::CallableObject::rest-rebase-ctor',
1209
- domain: `callable-rest-rebase:${sourceKey}->${targetKey}`,
1210
- allocates: true
1211
- }
819
+ classifier: { id: 'gea::Value::payloadType', domain },
820
+ materializer: { id: 'gea::detail::unboxValue', domain, allocates: false }
1212
821
  };
1213
- }
1214
- // A fifth pair, and the one that is not a constructor at all: same frame,
1215
- // a result no `CallableObject` constructor can convert because converting
1216
- // it means BOXING, and the tag table lives in the emitter. Rendered as a
1217
- // captureless-lambda adapter at the conversion site
1218
- // (`emit-narrowing.ts`'s `resultAdapterOf`); named here so the graph
1219
- // states the capability rather than leaving the pair to be licensed by
1220
- // accident and refused at emission -- which is exactly what happened
1221
- // before this entry existed, the inverse of the usual gap.
1222
- //
1223
- // Asked AFTER the four above and never before: every pair one of them
1224
- // accepts is an implicit conversion with no allocation of its own, and
1225
- // an adapter for such a pair would make an identity store allocate.
1226
- const resultAdapter = resultAdapterTransportOf(source, target);
1227
- if (resultAdapter !== null) {
1228
- const sourceKey = representationKey(source);
1229
- const targetKey = representationKey(target);
1230
- const domain = `callable-result-adapter:${sourceKey}->${targetKey}`;
1231
- const callableAdapter = resultAdapter.nativeConventions;
822
+ },
823
+ /**
824
+ * Reading a materializable ordinary Array back out of a box -- the
825
+ * MATERIALIZING direction (a genuinely dynamic value becoming a native
826
+ * shape at a point the program requires one), never the boxing shortcut:
827
+ * see `classRefMaterializer`'s own doc comment immediately above for the
828
+ * exact discipline this mirrors.
829
+ *
830
+ * `Value::box`'s payload-type recording is generic over EVERY C++ type it
831
+ * stores (`payloadTypeTagFor<std::decay_t<T>>()`, see `classRefMaterializer`'s
832
+ * comment), so `gea::ArrayObject<Element>` is not a special case for it --
833
+ * an array literal boxed into `dynamic` elsewhere in the SAME program (the
834
+ * mirror widening this same registry's `widening` entry below already
835
+ * installs for any `array-object` source, via `dynamicTagFor`'s existing
836
+ * `'array-object' -> 'Object'` case) records that exact address, and
837
+ * `gea::detail::unboxValue<T>` -- the SAME primitive `classRefMaterializer`
838
+ * uses, and the one `emit-narrowing.ts`'s `unboxedLoadText` ALREADY renders
839
+ * for every non-tagged-union target via its generic `dynamicTagFor(target)`
840
+ * + `unboxValue<cppTypeOf(target)>` fallback -- checks both the tag and
841
+ * that address before handing the payload back. So this entry needs no
842
+ * emitter change at all: both halves of the round trip were already built,
843
+ * the exact shape `classRefMaterializer`'s own doc names as the reason it
844
+ * was missing for as long as it was.
845
+ *
846
+ * `unboxValue<Ref<ArrayObject<Element>>>` hands back a REFERENCE-COUNTED
847
+ * pointer to the SAME underlying `ArrayObject` the box recorded -- not a
848
+ * reconstruction -- so both properties `deriveArrayObject` requires hold
849
+ * honestly: identity is the original object, not a copy, and every hole
850
+ * `ArrayObject`'s own presence-bit storage tracked survives untouched,
851
+ * because nothing about it was rebuilt.
852
+ *
853
+ * Restricted to `shared-refcount` for the identical reason
854
+ * `classRefMaterializer` restricts to it: a `borrowed` target has no
855
+ * lifetime a materialized value can honestly hold (`narrowing` above
856
+ * refuses borrowed targets for the same reason), and `owned`'s
857
+ * copy-constructibility across every carrier this backend can select as an
858
+ * array element is unproven the same way it is for a class instance's own
859
+ * fields -- narrower than a blanket refusal, and the honest boundary of
860
+ * what has actually been checked.
861
+ */
862
+ arrayObjectDomain: (ownership) => {
863
+ if (ownership !== 'shared-refcount')
864
+ return null;
1232
865
  return {
1233
- classifier: { id: 'gea::CallableObject::result-adapter', domain },
1234
- materializer: {
1235
- id: 'gea::CallableObject::result-adapter',
1236
- domain,
1237
- allocates: true,
1238
- ...(callableAdapter === null
1239
- ? {}
1240
- : { nativeFieldProtocol: 'unused', callableAdapter, callableIdentityTransport: 'preserved' })
1241
- }
866
+ classifier: { id: 'gea::Value::payloadType', domain: `array-payload:${ownership}` },
867
+ excluded: [],
868
+ preservesHoles: true,
869
+ preservesIdentity: true
1242
870
  };
1243
- }
1244
- // Boxing into `dynamic`: the one widening direction whose *target*
1245
- // carries no structural information about which sources are valid at
1246
- // all (a tagged union's arms are a fixed list; `gea::Value` accepts
1247
- // anything `dynamicTagFor` recognizes). `emit-narrowing.ts`'s
1248
- // `widenedStoreText` already renders exactly this store; asking the
1249
- // identical function here is what lets the conversion graph -- built
1250
- // structurally from `target`'s own shape everywhere else -- offer this
1251
- // one capability too, rather than leaving every merge whose carrier is
1252
- // `dynamic` refused for a conversion emission can already perform.
1253
- if (target.kind === 'dynamic') {
1254
- // An optional value has no single tag of its own -- see this
1255
- // function's sibling render, `emit-narrowing.ts`'s `widenedStoreText`,
1256
- // whose `held.kind === 'dynamic'` branch already renders exactly this
1257
- // recursively: absence boxes to `Null`/`Undefined`, presence boxes
1258
- // whatever the payload itself boxes as (which may in turn be a tagged
1259
- // union, the case just below). This installs the capability that
1260
- // render already implements; without it, every optional value merging
1261
- // or returning into a declared-`any`/`unknown` carrier refused for a
1262
- // conversion `emitConvert` could already perform.
1263
- if (source.kind === 'optional') {
1264
- const payload = source.payload;
1265
- if (!boxable(payload))
871
+ },
872
+ // The sum classifier is the emitter's actual condition: one exact tag and
873
+ // payload type, or an authenticated program-class family. A nested arm has
874
+ // several possible conditions and this algebra has no disjunctive classifier
875
+ // contract, so it remains explicitly refused rather than smuggling a
876
+ // checker-only semantic type into a fake runtime domain.
877
+ taggedUnionArmClassifier: cppTaggedUnionArmClassifier,
878
+ narrowing: (source, target) => {
879
+ // Presence loads and native class casts below inspect tags/allocation
880
+ // identity, never a property's reflection protocol. State that on the
881
+ // installed materializer, where the implementation is known; the IR
882
+ // census must not reconstruct it from a helper name or a carrier kind.
883
+ // General union selections remain unannotated because their renderer can
884
+ // adapt a compatible arm through another conversion.
885
+ // A target the backend cannot spell has no load: there is no C++ type for
886
+ // it to produce. Asking the one authoritative type mapping keeps this from
887
+ // becoming a second opinion about what is spellable.
888
+ if (!isSpellable(target))
889
+ return null;
890
+ // A borrowed target is refused, and not for lack of syntax. `gea::Optional`
891
+ // and `gea::TaggedUnion` both own their contents, so the reference a load
892
+ // would hand back points into the cell -- which outlives nothing the caller
893
+ // can see, and whose lifetime the program never stated.
894
+ if ('ownership' in target && target.ownership === 'borrowed')
895
+ return null;
896
+ if (classArmWithoutHome(layouts, source, target))
897
+ return null;
898
+ if (proxyArmWithoutHome(source, target))
899
+ return null;
900
+ const setPair = genericFunctionSetPair(source, target);
901
+ if (setPair)
902
+ return setPair;
903
+ // The payload read as the array-extending interface it also is
904
+ // (`sameArrayUpToExtension`): the presence proof is the same and the load
905
+ // is the same, since both carriers are one C++ type.
906
+ if (source.kind === 'optional' &&
907
+ (representationKey(source.payload) === representationKey(target) || sameArrayUpToExtension(source.payload, target))) {
908
+ return {
909
+ classifier: { id: 'gea::Optional::has_value', domain: 'present-optional' },
910
+ materializer: {
911
+ id: 'gea::Optional::operator*',
912
+ domain: 'present-optional',
913
+ allocates: false,
914
+ nativeFieldProtocol: 'unused',
915
+ nativePayloadTransport: 'preserved',
916
+ ...nativeClassReferenceIdentityOf(source, target)
917
+ }
918
+ };
919
+ }
920
+ // The mirror of the presence narrowing directly above: the guard proved the
921
+ // cell ABSENT, and the read carries the absent value's own carrier. There is
922
+ // nothing in the cell to load -- `null`'s carrier is `std::nullptr_t` and
923
+ // `undefined`'s is `gea::Undefined`, and each has exactly one inhabitant --
924
+ // so the materializer produces that constant. Gated on the two absences
925
+ // AGREEING: an `optional(T,undefined)` narrowed by `x === null` is not this
926
+ // pair, and the checker would not have produced it.
927
+ if (source.kind === 'optional' && target.kind === source.absence) {
928
+ return {
929
+ classifier: { id: 'gea::Optional::has_value', domain: `absent-optional:${source.absence}` },
930
+ materializer: {
931
+ id: 'gea::constant',
932
+ domain: `absent-optional:${source.absence}`,
933
+ allocates: false,
934
+ nativeFieldProtocol: 'unused',
935
+ ...nativeClassReferenceIdentityOf(source, target)
936
+ }
937
+ };
938
+ }
939
+ // A structural value read as an instance of a class nothing can
940
+ // instantiate. No such instance exists, so a guard that narrowed to it --
941
+ // `incoming instanceof Http2ServerRequest` -- never passes, and the
942
+ // instance-test census renders that guard only when it proved the view
943
+ // cannot hold one (`projection/instance-test.ts`). The load is the branch's
944
+ // own unreachability, never a value.
945
+ if (target.kind === 'class-ref' &&
946
+ layouts.classUninstantiable?.(target.declaration) === true &&
947
+ (source.kind === 'record' ||
948
+ source.kind === 'record-with-index' ||
949
+ source.kind === 'dictionary' ||
950
+ (source.kind === 'native-record-ref' && source.native === null))) {
951
+ const domain = `uninstantiable-class:${representationKey(target)}`;
952
+ return {
953
+ classifier: { id: 'gea::host::neverInstance', domain },
954
+ materializer: { id: 'gea::host::unreachableValue', domain, allocates: false, nativeFieldProtocol: 'unused' }
955
+ };
956
+ }
957
+ // A shared structural view read as a class, under the `instanceof` that
958
+ // proved it was built from one: the view remembers its origin
959
+ // (`gea::record::viewOrigin`) and the origin is narrowed like any boxed
960
+ // class instance, checked. An optional view is the same read of its
961
+ // payload, which the test proved present.
962
+ // An open `any` document may view an instance too (`classDocumentViewText`).
963
+ const sharedView = (value) => ((value.kind === 'record' || value.kind === 'record-with-index' || (value.kind === 'native-record-ref' && value.native === null)) &&
964
+ value.ownership === 'shared-refcount') ||
965
+ isOpenDocument(value);
966
+ if (target.kind === 'class-ref' &&
967
+ target.ownership === 'shared-refcount' &&
968
+ (sharedView(source) || (source.kind === 'optional' && sharedView(source.payload)))) {
969
+ const domain = `view-origin:${representationKey(target)}`;
970
+ return {
971
+ classifier: { id: 'gea::record::viewOriginIs', domain },
972
+ materializer: { id: 'gea::record::viewOrigin', domain, allocates: false, nativeFieldProtocol: 'unused' }
973
+ };
974
+ }
975
+ // A base class-ref read at a descendant -- see `downcastsToDerived` above.
976
+ // `downcastClassRef` (gea_runtime.h) is `Ref::staticCast`, which adopts
977
+ // `static_cast<Derived*>` of the SAME pointee: the payload travels as the
978
+ // object it already was, so payload transport is preserved as well.
979
+ if (downcastsToDerived(source, target)) {
980
+ return {
981
+ classifier: { id: 'gea::host::hasNativeClassLayoutRef', domain: `class-descendant:${representationKey(target)}` },
982
+ materializer: {
983
+ id: 'gea::host::downcastClassRef',
984
+ domain: `class-descendant:${representationKey(target)}`,
985
+ allocates: false,
986
+ nativeFieldProtocol: 'unused',
987
+ nativePayloadTransport: 'preserved',
988
+ ...nativeClassReferenceIdentityOf(source, target)
989
+ }
990
+ };
991
+ }
992
+ // The same handle read at a UNION of descendants -- `object instanceof Mesh
993
+ // || object instanceof Line || object instanceof Points`. The physical
994
+ // carrier stays one `Ref<Base>`; allocation identity is the discriminant,
995
+ // so the classifier is the same family test and the materializer the same
996
+ // checked downcast, applied per arm by `emit-narrowing.ts`'s
997
+ // `classFamilyLoadText`. `conversion/build.ts` owns the predicate and this
998
+ // imports it, so the pair this admits is exactly the pair that proposed it.
999
+ if (narrowsToDescendantClassUnion(source, target)) {
1000
+ return {
1001
+ classifier: { id: 'gea::host::hasNativeClassLayoutRef', domain: `class-descendant-union:${representationKey(target)}` },
1002
+ materializer: {
1003
+ id: 'gea::host::downcastClassRef',
1004
+ domain: `class-descendant-union:${representationKey(target)}`,
1005
+ allocates: false,
1006
+ nativeFieldProtocol: 'unused',
1007
+ // Each arm is `ofArm<I>(downcastClassRef<D>(held))`: one pointee,
1008
+ // injected into the target union (and its optional, if any).
1009
+ nativePayloadTransport: 'preserved',
1010
+ ...nativeClassReferenceIdentityOf(source, target)
1011
+ }
1012
+ };
1013
+ }
1014
+ // The census asks this table before widening. A total native transfer
1015
+ // must therefore win here too; otherwise the broad subset fallback below
1016
+ // can shadow its selected recipe and lose its payload identity contract.
1017
+ const nativeSelection = nativeTotalSelectionRecipeOf(source, target) ??
1018
+ ((source.kind === 'optional' || source.kind === 'tagged-union') && narrowingReachesTarget(source, target)
1019
+ ? nativeSelectionRecipeOf(source, target)
1020
+ : null);
1021
+ if (nativeSelection)
1022
+ return nativeSelectionConversion(source, target, nativeSelection);
1023
+ if ((source.kind === 'optional' || source.kind === 'tagged-union') &&
1024
+ target.kind === 'class-ref' &&
1025
+ narrowingReachesTarget(source, target)) {
1026
+ return {
1027
+ classifier: { id: 'gea::host::hasNativeClassLayoutRef', domain: `class-descendant-sum:${representationKey(target)}` },
1028
+ materializer: {
1029
+ id: 'gea::host::downcastClassRef',
1030
+ domain: `class-descendant-sum:${representationKey(target)}`,
1031
+ allocates: false,
1032
+ // Presence and sum selection over native class handles never reads
1033
+ // field values. Mixed sums retain their general converting protocol.
1034
+ // A mixed sum (`Error | MongoError` narrowed by `instanceof`) composes
1035
+ // its leaves' contracts, as the exact-arm narrowing below does.
1036
+ ...(nativeClassPresence(source)
1037
+ ? { nativeFieldProtocol: 'unused', ...nativeClassReferenceIdentityOf(source, target) }
1038
+ : nativeNarrowing(source, target))
1039
+ }
1040
+ };
1041
+ }
1042
+ // Selecting one arm of a union, either directly or through an optional the
1043
+ // same narrowing also proved present. `gea::TaggedUnion::is<Index>` is the
1044
+ // discriminant test and `get<Index>` is the load, and both are indexed by
1045
+ // the arm's position in `representation.arms` -- the checker's own order,
1046
+ // which is what the emitter already uses to build one.
1047
+ //
1048
+ // More than one arm may carry the target's C++ type: `A | B | C` where all
1049
+ // three lower to `std::string` is one narrowing target with three possible
1050
+ // live arms. That is a fact about the load -- it dispatches on which arm is
1051
+ // live -- not about whether the capability exists, so it does not change
1052
+ // the answer here.
1053
+ //
1054
+ // The target may itself still be an optional: narrowing `A | B | undefined`
1055
+ // to `A | undefined` rules out an arm and proves nothing about presence, so
1056
+ // both sides unwrap before the arms are compared and the load rebuilds the
1057
+ // optional around whichever arm it read.
1058
+ const union = source.kind === 'optional' ? source.payload : source;
1059
+ const selected = source.kind === 'optional' && target.kind === 'optional' ? target.payload : target;
1060
+ if (union.kind !== 'tagged-union')
1061
+ return null;
1062
+ // A record-shaped target some OTHER arm reaches only through the
1063
+ // structural view is not a selection: that arm is live at a store, and a
1064
+ // selection would read it as the exact arm. The view's `dispatch` plan
1065
+ // (`conversion/record-view.ts`) is the conversion, installed by
1066
+ // `staticRecipe` below once this table declines -- the same plan
1067
+ // `emit-narrowing.ts`'s `narrowedLoadText` defers to, asked here so the
1068
+ // admission and the render agree.
1069
+ if (isRecordViewTarget(selected)) {
1070
+ const view = viewPlanFor(layouts, source, target);
1071
+ if (view !== null && recordViewDispatchesArms(view))
1072
+ return null;
1073
+ }
1074
+ const targetKey = representationKey(selected);
1075
+ // A SUB-union target: `selected` is still a tagged union, just missing one
1076
+ // or more of `union`'s arms -- `h instanceof Headers`'s `else` branch
1077
+ // leaving a `Headers | Record<string,string> | [string,string][]` cell
1078
+ // narrowed to the latter two. Installed exactly when every one of
1079
+ // `selected`'s own arms has a same-shaped home among `union`'s -- the
1080
+ // identical admission `emit-narrowing.ts`'s `narrowedUnionSubsetText`
1081
+ // checks before it renders the `ofArm<Index>` rebuild, asked here rather
1082
+ // than restated so the two cannot disagree about which pairs install.
1083
+ if (selected.kind === 'tagged-union') {
1084
+ const installed = selected.arms.every((arm) => union.arms.some((candidate) => representationKey(candidate.value) === representationKey(arm.value) ||
1085
+ narrowingReachesTarget(candidate.value, arm.value) ||
1086
+ downcastsToDerived(candidate.value, arm.value)));
1087
+ if (!installed)
1266
1088
  return null;
1267
1089
  return {
1268
- classifier: { id: 'gea::Value::box', domain: `box:optional:${representationKey(payload)}` },
1269
- materializer: { id: 'gea::Value::box', domain: `box:optional:${representationKey(payload)}`, allocates: true }
1090
+ classifier: { id: 'gea::TaggedUnion::is', domain: `live-arm-subset:${targetKey}` },
1091
+ materializer: {
1092
+ id: 'gea::TaggedUnion::ofArm',
1093
+ domain: `live-arm-subset:${targetKey}`,
1094
+ allocates: false,
1095
+ // The discriminant selects; each candidate leaf's own contract says
1096
+ // whether the selected payload travels natively.
1097
+ ...nativeNarrowing(source, target)
1098
+ }
1099
+ };
1100
+ }
1101
+ // A target OPTIONAL whose payload is one of the union's arms, where the
1102
+ // union carries no bare absent arm at all -- absence living inside another
1103
+ // arm's own optional. `emit-narrowing.ts`'s `narrowedLoadText` renders the
1104
+ // arm test as the presence test; this installs the capability it needs.
1105
+ if (target.kind === 'optional' && union.arms.some((arm) => representationKey(arm.value) === representationKey(target.payload))) {
1106
+ return {
1107
+ classifier: { id: 'gea::TaggedUnion::is', domain: `live-arm-optional:${targetKey}` },
1108
+ materializer: {
1109
+ id: 'gea::TaggedUnion::get',
1110
+ domain: `live-arm-optional:${targetKey}`,
1111
+ allocates: false,
1112
+ ...nativeNarrowing(source, target)
1113
+ }
1270
1114
  };
1271
1115
  }
1272
- // A tagged union is the other sum carrier, and it boxes on exactly the
1273
- // condition the optional case above already states for its payload:
1274
- // every arm boxes. `dynamicTagFor` cannot answer for the union itself --
1275
- // a sum has no single tag, which is the whole point of it -- but each
1276
- // arm has one, and `widenedStoreText` already renders the per-arm store
1277
- // recursively. Without this the identical value refused one level out
1278
- // from where it was admitted: `optional(tagged-union(A|B))` boxed and a
1279
- // bare `tagged-union(A|B)` did not.
1280
- if (source.kind === 'tagged-union') {
1281
- if (!boxable(source))
1116
+ if (!union.arms.some((arm) => representationKey(arm.value) === targetKey)) {
1117
+ // An arm the target lives INSIDE, not one that equals it. A narrowing
1118
+ // does not stop at the top level: three's `?(string|number|boolean)`
1119
+ // field is `undefined | null | (string|number|boolean)`, and a guard past
1120
+ // the two absences lands on one of the inner arms -- two steps, and this
1121
+ // test saw only one. `narrowingReachesTarget` (`conversion/build.ts`) is
1122
+ // the same enumeration that PROPOSED this pair, asked here rather than
1123
+ // restated so the admission cannot admit fewer levels than the graph
1124
+ // offers, and `emit-narrowing.ts`'s `taggedUnionArmText` recurses through
1125
+ // `narrowedLoadText` to render exactly the step this admits.
1126
+ if (!narrowingReachesTarget(source, target))
1282
1127
  return null;
1283
1128
  return {
1284
- classifier: { id: 'gea::Value::box', domain: `box:sum:${representationKey(source)}` },
1285
- materializer: { id: 'gea::Value::box', domain: `box:sum:${representationKey(source)}`, allocates: true }
1129
+ classifier: { id: 'gea::TaggedUnion::is', domain: `live-arm-nested:${targetKey}` },
1130
+ materializer: {
1131
+ id: 'gea::TaggedUnion::get',
1132
+ domain: `live-arm-nested:${targetKey}`,
1133
+ allocates: false,
1134
+ ...nativeNarrowing(source, target)
1135
+ }
1286
1136
  };
1287
1137
  }
1288
- const tag = dynamicTagFor(source);
1289
- if (tag === null)
1290
- return null;
1291
- // Absence constructs only the dynamic tag; there is no native payload
1292
- // to allocate, inspect or publish. In particular, an omitted any formal
1293
- // must not turn an otherwise known constructor into an external entry.
1294
- const absent = source.kind === 'undefined' || source.kind === 'null';
1295
1138
  return {
1296
- classifier: { id: 'gea::Value::box', domain: `box:${tag}` },
1297
- materializer: {
1298
- id: 'gea::Value::box',
1299
- domain: `box:${tag}`,
1300
- allocates: !absent,
1301
- ...(absent ? { nativeFieldProtocol: 'unused' } : {})
1302
- }
1303
- };
1304
- }
1305
- // The bare absence marker -- `null`/`undefined` as its OWN static type,
1306
- // not a literal appearing where a wider carrier is held -- widening into
1307
- // an optional whose absence tag it matches: no payload conversion at
1308
- // all, just the optional's own empty state. `emit-narrowing.ts`'s
1309
- // `emptyOptionalText` already renders exactly this (`written.kind ===
1310
- // held.absence` -> default-construct); this installs the capability
1311
- // that render already implements. Gated to a matching tag on purpose --
1312
- // `null` reaching an `undefined`-absent optional is a real semantic
1313
- // mismatch `emptyOptionalText` itself refuses, not a spelling gap.
1314
- if ((source.kind === 'null' || source.kind === 'undefined') && target.kind === 'optional' && source.kind === target.absence) {
1315
- return {
1316
- classifier: { id: 'gea::Optional::empty', domain: `absence:${target.absence}` },
1317
- materializer: {
1318
- id: 'gea::Optional::empty',
1319
- domain: `absence:${target.absence}`,
1320
- allocates: false,
1321
- nativeFieldProtocol: 'unused',
1322
- ...nativeClassReferenceIdentityOf(source, target)
1323
- }
1324
- };
1325
- }
1326
- // widenedStoreText already renders null as the empty state of a native
1327
- // handle or refcounted class. Neither admits undefined without a flag.
1328
- // The render is the default-constructed handle (`Ref<T>()`): no payload is
1329
- // read or built, which is the payload-transport statement below.
1330
- if (source.kind === 'null' &&
1331
- (target.kind === 'native-handle' || (target.kind === 'class-ref' && target.ownership === 'shared-refcount'))) {
1332
- return {
1333
- classifier: { id: 'empty-reference', domain: 'absence:null' },
1334
- materializer: {
1335
- id: 'empty-reference',
1336
- domain: 'absence:null',
1337
- allocates: false,
1338
- nativeFieldProtocol: 'unused',
1339
- nativePayloadTransport: 'preserved',
1340
- ...nativeClassReferenceIdentityOf(source, target)
1341
- }
1139
+ classifier: { id: 'gea::TaggedUnion::is', domain: `live-arm:${targetKey}` },
1140
+ materializer: { id: 'gea::TaggedUnion::get', domain: `live-arm:${targetKey}`, allocates: false, ...nativeNarrowing(source, target) }
1342
1141
  };
1343
- }
1344
- // A source still wearing its own optional widens by reading its own
1345
- // presence flag rather than assuming one -- `emit-narrowing.ts`'s
1346
- // `widenedStoreText` is what actually renders that read, guarded by a
1347
- // `has_value()` check when the target keeps an absence of its own and
1348
- // unconditional (the checker having already proven presence) when it does
1349
- // not. This only states the pairing is real: the payload widens exactly
1350
- // as a bare source would, one optional layer down, so the domain is named
1351
- // separately from the bare-payload case below to keep the two capability
1352
- // pairs from being mistaken for one another.
1353
- if (source.kind === 'optional') {
1354
- const payloadKey = representationKey(source.payload);
1355
- if (target.kind === 'optional' && representationKey(target.payload) === payloadKey) {
1142
+ },
1143
+ // The mirror of `narrowing`: a plain value taking the place of the tagged
1144
+ // union (or the union payload of an optional) that declares it as one arm --
1145
+ // or, when the target is an optional and the source is exactly its bare
1146
+ // payload, no union at all, because `gea::Optional<T>` declares its own
1147
+ // converting constructor from `T`. `gea::TaggedUnion::ofArm<Index>` is a
1148
+ // real constructor -- built, not assumed -- so the union case is installed
1149
+ // exactly when the source's carrier is one of the target union's arms,
1150
+ // indexed the same way the emitter already reads one back
1151
+ // (`representation.arms`'s own order).
1152
+ widening: (source, target) => {
1153
+ if (!isSpellable(target))
1154
+ return null;
1155
+ const nativeSum = nativeSumConversion(source, target);
1156
+ if (nativeSum)
1157
+ return nativeSum;
1158
+ const totalSelection = nativeTotalSelectionRecipeOf(source, target);
1159
+ if (totalSelection)
1160
+ return nativeSelectionConversion(source, target, totalSelection);
1161
+ const setPair = genericFunctionSetPair(source, target);
1162
+ if (setPair)
1163
+ return setPair;
1164
+ const exactDispatch = exactFunctionDispatchPair(source, target);
1165
+ if (exactDispatch)
1166
+ return exactDispatch;
1167
+ const identity = callableIdentityPair(source, target);
1168
+ if (identity)
1169
+ return identity;
1170
+ const constructEntry = callableConstructEntryPair(source, target);
1171
+ if (constructEntry)
1172
+ return constructEntry;
1173
+ // `Function` promises only callability, so crossing into an evaluated
1174
+ // callable slot needs the same checked ABI adapter as the generic dynamic
1175
+ // materializer above. This pair is proposed explicitly by
1176
+ // `wideningSourcesOf`: dynamic provenance is part of a representation's
1177
+ // key, and the generic node is intentionally keyed to declared `any`.
1178
+ if (source.kind === 'dynamic' &&
1179
+ source.reason === 'untyped-callable' &&
1180
+ target.kind === 'function-value-dispatch' &&
1181
+ dynamicCallableAbiSupported(target.abi)) {
1182
+ return dynamicCallablePair(target);
1183
+ }
1184
+ // A callable declaring a type-matching PREFIX of the target's own
1185
+ // parameters widening into it -- `gea::CallableObject`'s own converting
1186
+ // constructor (`gea_runtime.h`) performs this, so the pairing this
1187
+ // capability approves is exactly the one `dropsUnboundParameters` (the
1188
+ // same authority `emit-narrowing.ts`'s renderer asks) proves sound. Asked
1189
+ // before the `dynamic`/absence/optional cases below because a callable
1190
+ // pair can never satisfy any of those (`callableObjectAbi` inside
1191
+ // `dropsUnboundParameters` answers `null` for anything that is not a
1192
+ // `function`/`function-family`/`function-value-family`/
1193
+ // `function-value-dispatch`), so ordering only ever skips work, never
1194
+ // changes an answer.
1195
+ if (constructorUpcastMember(source, target) !== null || constructorFamilyUpcastMembers(source, target) !== null) {
1196
+ const domain = `constructor-upcast:${representationKey(source)}->${representationKey(target)}`;
1197
+ return {
1198
+ classifier: { id: 'gea::upcastConstructor', domain },
1199
+ materializer: { id: 'gea::upcastConstructor', domain, allocates: false }
1200
+ };
1201
+ }
1202
+ // A class stored into a construct-signature slot with its own convention:
1203
+ // the environment (and so the constructor's identity) is kept and only the
1204
+ // construct entry is adapted -- see `emit-narrowing.ts`'s
1205
+ // `constructorDispatchAdapterText`, asked here so the two cannot disagree.
1206
+ if (adaptsConstructorIntoDispatch(source, target)) {
1207
+ const domain = `constructor-dispatch-adapter:${representationKey(source)}->${representationKey(target)}`;
1208
+ return {
1209
+ classifier: { id: 'gea::ConstructorObject::adapter', domain },
1210
+ materializer: { id: 'gea::ConstructorObject::adapter', domain, allocates: false }
1211
+ };
1212
+ }
1213
+ if (upcastsToBase(source, target)) {
1214
+ const sourceKey = representationKey(source);
1215
+ const targetKey = representationKey(target);
1356
1216
  return {
1357
- classifier: { id: 'gea::Optional::converting-ctor', domain: `optional-payload:${payloadKey}` },
1217
+ classifier: { id: 'gea::Ref::converting-ctor', domain: `class-upcast:${sourceKey}->${targetKey}` },
1358
1218
  materializer: {
1359
- id: 'gea::Optional::converting-ctor',
1360
- domain: `optional-payload:${payloadKey}`,
1219
+ id: 'gea::Ref::converting-ctor',
1220
+ domain: `class-upcast:${sourceKey}->${targetKey}`,
1361
1221
  allocates: false,
1362
1222
  nativeFieldProtocol: 'unused',
1223
+ // `Ref<Base>(derived)` retains the same pointee.
1224
+ nativePayloadTransport: 'preserved',
1363
1225
  ...nativeClassReferenceIdentityOf(source, target)
1364
1226
  }
1365
1227
  };
1366
1228
  }
1367
- const wrappedUnion = target.kind === 'optional' ? target.payload : target;
1368
- if (wrappedUnion.kind !== 'tagged-union')
1369
- return null;
1370
- if (!wrappedUnion.arms.some((arm) => representationKey(arm.value) === payloadKey))
1371
- return null;
1372
- return {
1373
- classifier: { id: 'gea::TaggedUnion::ofArm', domain: `optional-arm:${payloadKey}` },
1374
- materializer: {
1375
- id: 'gea::TaggedUnion::ofArm',
1376
- domain: `optional-arm:${payloadKey}`,
1377
- allocates: false,
1378
- nativeFieldProtocol: 'unused',
1379
- ...nativeClassReferenceIdentityOf(source, target)
1380
- }
1381
- };
1382
- }
1383
- const sourceKey = representationKey(source);
1384
- // The bare payload widening straight into its own optional --
1385
- // `gea::Optional<T>` declares a converting constructor from `T`, so this
1386
- // needs no tagged union and no arm index at all.
1387
- if (target.kind === 'optional' && representationKey(target.payload) === sourceKey) {
1388
- return {
1389
- classifier: { id: 'gea::Optional::converting-ctor', domain: `payload:${sourceKey}` },
1390
- materializer: {
1391
- id: 'gea::Optional::converting-ctor',
1392
- domain: `payload:${sourceKey}`,
1393
- allocates: false,
1394
- nativeFieldProtocol: 'unused',
1395
- ...nativeClassReferenceIdentityOf(source, target)
1396
- }
1397
- };
1398
- }
1399
- // A source that is not the payload but reaches it by one of the four
1400
- // `gea::CallableObject` converting constructors above. Every one of those
1401
- // was installed only for a BARE callable target, so
1402
- // `((gl, v) => void)` returned where `((gl, v, textures) => void) |
1403
- // undefined` is expected -- three's `getSingularSetter`, 30 returns of
1404
- // exactly that shape -- refused for a pair whose two halves this backend
1405
- // performs individually. The same four authorities are asked here, one
1406
- // optional layer down, so the graph and the emitter cannot disagree about
1407
- // which pairs the runtime accepts.
1408
- //
1409
- // `allocates` is true, unlike the bare-payload case: the emitter names
1410
- // the payload type EXPLICITLY (`convertedValueText`'s optional branch)
1411
- // because C++ allows one user-defined conversion per implicit sequence
1412
- // and this pair needs two, so a `CallableObject` really is constructed
1413
- // here rather than merely wrapped.
1414
- if (target.kind === 'optional') {
1415
- const payload = target.payload;
1416
- const nativeConstructor = dropsUnboundParameters(source, payload) || dropsAllParametersIntoResultArm(source, payload) || widensResultIntoArm(source, payload);
1417
- const restRebase = !nativeConstructor && rebasesRestOverLeadingParameters(source, payload);
1418
- const adapter = nativeConstructor || restRebase ? null : resultAdapterTransportOf(source, payload);
1419
- if (nativeConstructor || restRebase || adapter !== null) {
1420
- const domain = `payload-callable:${sourceKey}->${representationKey(payload)}`;
1421
- const native = nativeConstructor
1422
- ? nativeCallableTransport(source, payload)
1423
- : adapter?.nativeConventions
1424
- ? {
1425
- nativeFieldProtocol: 'unused',
1426
- callableAdapter: adapter.nativeConventions,
1427
- callableIdentityTransport: 'preserved'
1428
- }
1429
- : {};
1229
+ if (dropsUnboundParameters(source, target)) {
1230
+ const sourceKey = representationKey(source);
1231
+ const targetKey = representationKey(target);
1430
1232
  return {
1431
- classifier: { id: 'gea::Optional::converting-ctor', domain },
1432
- materializer: { id: 'gea::Optional::converting-ctor', domain, allocates: true, ...native }
1233
+ classifier: { id: 'gea::CallableObject::converting-ctor', domain: `callable-prefix:${sourceKey}->${targetKey}` },
1234
+ materializer: {
1235
+ id: 'gea::CallableObject::converting-ctor',
1236
+ domain: `callable-prefix:${sourceKey}->${targetKey}`,
1237
+ allocates: true,
1238
+ ...nativeCallableTransport(source, target)
1239
+ }
1433
1240
  };
1434
1241
  }
1435
- }
1436
- if ((target.kind === 'optional' || target.kind === 'tagged-union') && hasSingleClassUpcastHome(source, target)) {
1437
- const domain = `class-upcast-arm:${sourceKey}->${representationKey(target)}`;
1438
- return {
1439
- classifier: { id: 'gea::TaggedUnion::ofArm', domain },
1440
- materializer: {
1441
- id: 'gea::TaggedUnion::ofArm',
1442
- domain,
1443
- allocates: false,
1444
- nativeFieldProtocol: 'unused',
1445
- ...nativeClassReferenceIdentityOf(source, target)
1242
+ // The composed sibling of the pairing just above: a zero-parameter
1243
+ // callable widening into a slot that ALSO widens its result into one arm
1244
+ // of a tagged union -- `gea_runtime.h`'s `ResultWidensIntoArm` performs
1245
+ // both steps as one converting constructor, asked here through
1246
+ // `dropsAllParametersIntoResultArm` for the identical reason
1247
+ // `dropsUnboundParameters` is asked above it, so the two authorities
1248
+ // cannot disagree about which pairs the runtime actually accepts.
1249
+ if (dropsAllParametersIntoResultArm(source, target)) {
1250
+ const sourceKey = representationKey(source);
1251
+ const targetKey = representationKey(target);
1252
+ return {
1253
+ classifier: { id: 'gea::CallableObject::result-arm-ctor', domain: `callable-result-arm:${sourceKey}->${targetKey}` },
1254
+ materializer: {
1255
+ id: 'gea::CallableObject::result-arm-ctor',
1256
+ domain: `callable-result-arm:${sourceKey}->${targetKey}`,
1257
+ allocates: true,
1258
+ ...nativeCallableTransport(source, target)
1259
+ }
1260
+ };
1261
+ }
1262
+ // The same widening at a nonzero arity the source already declares in
1263
+ // full -- `gea_runtime.h`'s `widenResultIntoArm` constructor, gated by the
1264
+ // very same `ResultWidensIntoArm` trait as the composed case above.
1265
+ // Installed here for the identical reason its two siblings are: the
1266
+ // conversion graph decides admissibility, and a pairing the emitter
1267
+ // renders but the graph never heard of is refused at certification for a
1268
+ // conversion this backend can already perform.
1269
+ if (widensResultIntoArm(source, target)) {
1270
+ const sourceKey = representationKey(source);
1271
+ const targetKey = representationKey(target);
1272
+ return {
1273
+ classifier: {
1274
+ id: 'gea::CallableObject::same-arity-result-arm-ctor',
1275
+ domain: `callable-result-arm-fixed:${sourceKey}->${targetKey}`
1276
+ },
1277
+ materializer: {
1278
+ id: 'gea::CallableObject::same-arity-result-arm-ctor',
1279
+ domain: `callable-result-arm-fixed:${sourceKey}->${targetKey}`,
1280
+ allocates: true,
1281
+ ...nativeCallableTransport(source, target)
1282
+ }
1283
+ };
1284
+ }
1285
+ // The rest slot rebased to position 0 -- `gea_runtime.h`'s
1286
+ // `spreadRestOverLeading` constructor, gated by the very same
1287
+ // `RestRebaseAdmits` trait. Installed here for the identical reason its
1288
+ // siblings are: a pairing the emitter renders but the graph never heard
1289
+ // of is refused at certification for a conversion this backend performs.
1290
+ if (rebasesRestOverLeadingParameters(source, target)) {
1291
+ const sourceKey = representationKey(source);
1292
+ const targetKey = representationKey(target);
1293
+ return {
1294
+ classifier: { id: 'gea::CallableObject::rest-rebase-ctor', domain: `callable-rest-rebase:${sourceKey}->${targetKey}` },
1295
+ materializer: {
1296
+ id: 'gea::CallableObject::rest-rebase-ctor',
1297
+ domain: `callable-rest-rebase:${sourceKey}->${targetKey}`,
1298
+ allocates: true
1299
+ }
1300
+ };
1301
+ }
1302
+ // A fifth pair, and the one that is not a constructor at all: same frame,
1303
+ // a result no `CallableObject` constructor can convert because converting
1304
+ // it means BOXING, and the tag table lives in the emitter. Rendered as a
1305
+ // captureless-lambda adapter at the conversion site
1306
+ // (`emit-narrowing.ts`'s `resultAdapterOf`); named here so the graph
1307
+ // states the capability rather than leaving the pair to be licensed by
1308
+ // accident and refused at emission -- which is exactly what happened
1309
+ // before this entry existed, the inverse of the usual gap.
1310
+ //
1311
+ // Asked AFTER the four above and never before: every pair one of them
1312
+ // accepts is an implicit conversion with no allocation of its own, and
1313
+ // an adapter for such a pair would make an identity store allocate.
1314
+ const resultAdapter = resultAdapterTransportOf(source, target);
1315
+ if (resultAdapter !== null) {
1316
+ const sourceKey = representationKey(source);
1317
+ const targetKey = representationKey(target);
1318
+ const domain = `callable-result-adapter:${sourceKey}->${targetKey}`;
1319
+ const callableAdapter = resultAdapter.nativeConventions;
1320
+ return {
1321
+ classifier: { id: 'gea::CallableObject::result-adapter', domain },
1322
+ materializer: {
1323
+ id: 'gea::CallableObject::result-adapter',
1324
+ domain,
1325
+ allocates: true,
1326
+ // `resultAdaptedCallableText` renders every such adapter through
1327
+ // `CallableObject::adaptSource`, which shares the source's Function
1328
+ // identity whether or not the entry boxes: identity is a fact of
1329
+ // the renderer, not of the native field protocol.
1330
+ ...(callableAdapter === null
1331
+ ? { callableIdentityTransport: 'preserved' }
1332
+ : { nativeFieldProtocol: 'unused', callableAdapter, callableIdentityTransport: 'preserved' })
1333
+ }
1334
+ };
1335
+ }
1336
+ // Boxing into `dynamic`: the one widening direction whose *target*
1337
+ // carries no structural information about which sources are valid at
1338
+ // all (a tagged union's arms are a fixed list; `gea::Value` accepts
1339
+ // anything `dynamicTagFor` recognizes). `emit-narrowing.ts`'s
1340
+ // `widenedStoreText` already renders exactly this store; asking the
1341
+ // identical function here is what lets the conversion graph -- built
1342
+ // structurally from `target`'s own shape everywhere else -- offer this
1343
+ // one capability too, rather than leaving every merge whose carrier is
1344
+ // `dynamic` refused for a conversion emission can already perform.
1345
+ if (target.kind === 'dynamic') {
1346
+ // An optional value has no single tag of its own -- see this
1347
+ // function's sibling render, `emit-narrowing.ts`'s `widenedStoreText`,
1348
+ // whose `held.kind === 'dynamic'` branch already renders exactly this
1349
+ // recursively: absence boxes to `Null`/`Undefined`, presence boxes
1350
+ // whatever the payload itself boxes as (which may in turn be a tagged
1351
+ // union, the case just below). This installs the capability that
1352
+ // render already implements; without it, every optional value merging
1353
+ // or returning into a declared-`any`/`unknown` carrier refused for a
1354
+ // conversion `emitConvert` could already perform.
1355
+ if (source.kind === 'optional') {
1356
+ const payload = source.payload;
1357
+ if (!boxable(payload))
1358
+ return null;
1359
+ return {
1360
+ classifier: { id: 'gea::Value::box', domain: `box:optional:${representationKey(payload)}` },
1361
+ materializer: { id: 'gea::Value::box', domain: `box:optional:${representationKey(payload)}`, allocates: true }
1362
+ };
1446
1363
  }
1447
- };
1448
- }
1449
- const union = target.kind === 'optional' ? target.payload : target;
1450
- if (union.kind !== 'tagged-union')
1451
- return null;
1452
- if (union.arms.some((arm) => representationKey(arm.value) === sourceKey)) {
1453
- return {
1454
- classifier: { id: 'gea::TaggedUnion::ofArm', domain: `arm:${sourceKey}` },
1455
- materializer: {
1456
- id: 'gea::TaggedUnion::ofArm',
1457
- domain: `arm:${sourceKey}`,
1458
- allocates: false,
1459
- nativeFieldProtocol: 'unused',
1460
- ...nativeClassReferenceIdentityOf(source, target)
1364
+ // A tagged union is the other sum carrier, and it boxes on exactly the
1365
+ // condition the optional case above already states for its payload:
1366
+ // every arm boxes. `dynamicTagFor` cannot answer for the union itself --
1367
+ // a sum has no single tag, which is the whole point of it -- but each
1368
+ // arm has one, and `widenedStoreText` already renders the per-arm store
1369
+ // recursively. Without this the identical value refused one level out
1370
+ // from where it was admitted: `optional(tagged-union(A|B))` boxed and a
1371
+ // bare `tagged-union(A|B)` did not.
1372
+ if (source.kind === 'tagged-union') {
1373
+ if (!boxable(source))
1374
+ return null;
1375
+ return {
1376
+ classifier: { id: 'gea::Value::box', domain: `box:sum:${representationKey(source)}` },
1377
+ materializer: { id: 'gea::Value::box', domain: `box:sum:${representationKey(source)}`, allocates: true }
1378
+ };
1461
1379
  }
1462
- };
1463
- }
1464
- return null;
1465
- },
1466
- // Two tagged unions built from the same member set at different tag orders
1467
- // -- one declared `boolean | number`, the other `number | boolean` -- need a
1468
- // recast: every value the source can hold must have a same-typed home among
1469
- // the target's arms, so the live one can always be rebuilt at the target's
1470
- // own tag. A source arm with no match in the target is a real hole, not a
1471
- // missing recipe, and is refused rather than dropped.
1472
- recasting: (source, target) => {
1473
- if (!isSpellable(target))
1474
- return null;
1475
- const setPair = genericFunctionSetPair(source, target);
1476
- if (setPair)
1477
- return setPair;
1478
- if (source.kind === 'native-record-ref' && source.native === cppStringObjectNativeType && target.kind === 'string') {
1479
- const domain = `string-object-value:${representationKey(source)}`;
1480
- return {
1481
- classifier: { id: 'gea::runtime::StringObject::value', domain },
1482
- materializer: { id: 'gea::runtime::StringObject::value', domain, allocates: false }
1483
- };
1484
- }
1485
- // The two void-payload guards that used to sit here now live inside
1486
- // `promisePayloadConvertible`, which is the printer's own authority: a
1487
- // `Promise<never>` source is admissible and a `Promise<void>` one is not,
1488
- // and stating that twice is how the census and the printer drift apart.
1489
- if (source.kind === 'promise' && target.kind === 'promise' && promisePayloadConvertible(source.value, target.value)) {
1490
- const domain = `promise-state-adoption:${representationKey(source)}->${representationKey(target)}`;
1491
- return {
1492
- classifier: { id: 'gea::Promise::state', domain },
1493
- materializer: { id: 'gea::Promise::adopt-converted', domain, allocates: true }
1494
- };
1495
- }
1496
- if (source.kind === 'record' && target.kind === 'tagged-union' && ownedRecordMaterializationPlan(source, target, layouts) !== null) {
1497
- const domain = `owned-record-arm:${representationKey(source)}->${representationKey(target)}`;
1498
- return {
1499
- classifier: { id: 'gea::record::ownedArm', domain },
1500
- materializer: { id: 'gea::record::ownedArm', domain, allocates: true }
1501
- };
1502
- }
1503
- // Built on demand, never up front: this function is asked about EVERY
1504
- // ordered pair of recastable carriers (`conversion/build.ts`), hundreds
1505
- // of millions on TypeScript's own compiler, and almost every pair leaves
1506
- // through an early `null` without ever needing its key. Concatenating
1507
- // it first was one string allocation per pair and a collector busy
1508
- // reclaiming them -- the same cost `build.ts`'s own loop already paid once.
1509
- let pairKeyMemo = null;
1510
- const pairKey = () => {
1511
- pairKeyMemo ??= `${representationKey(source)}->${representationKey(target)}`;
1512
- return pairKeyMemo;
1513
- };
1514
- if (source.kind === 'native-record-ref' &&
1515
- target.kind === 'native-record-ref' &&
1516
- source.native !== null &&
1517
- source.native === target.native &&
1518
- source.ownership === target.ownership &&
1519
- cppTypeOf(source) === cppTypeOf(target)) {
1520
- return {
1521
- classifier: { id: 'gea::native-record::identity', domain: `native-identity:${source.native}:${source.ownership}` },
1522
- materializer: {
1523
- id: 'gea::native-record::identity',
1524
- domain: `native-identity:${source.native}:${source.ownership}`,
1525
- allocates: false
1380
+ const tag = dynamicTagFor(source);
1381
+ if (tag === null)
1382
+ return null;
1383
+ // Absence constructs only the dynamic tag; there is no native payload
1384
+ // to allocate, inspect or publish. In particular, an omitted any formal
1385
+ // must not turn an otherwise known constructor into an external entry.
1386
+ const absent = source.kind === 'undefined' || source.kind === 'null';
1387
+ return {
1388
+ classifier: { id: 'gea::Value::box', domain: `box:${tag}` },
1389
+ materializer: {
1390
+ id: 'gea::Value::box',
1391
+ domain: `box:${tag}`,
1392
+ allocates: !absent,
1393
+ ...(absent ? { nativeFieldProtocol: 'unused' } : {})
1394
+ }
1395
+ };
1396
+ }
1397
+ // The bare absence marker -- `null`/`undefined` as its OWN static type,
1398
+ // not a literal appearing where a wider carrier is held -- widening into
1399
+ // an optional whose absence tag it matches: no payload conversion at
1400
+ // all, just the optional's own empty state. `emit-narrowing.ts`'s
1401
+ // `emptyOptionalText` already renders exactly this (`written.kind ===
1402
+ // held.absence` -> default-construct); this installs the capability
1403
+ // that render already implements. Gated to a matching tag on purpose --
1404
+ // `null` reaching an `undefined`-absent optional is a real semantic
1405
+ // mismatch `emptyOptionalText` itself refuses, not a spelling gap.
1406
+ if ((source.kind === 'null' || source.kind === 'undefined') && target.kind === 'optional' && source.kind === target.absence) {
1407
+ return {
1408
+ classifier: { id: 'gea::Optional::empty', domain: `absence:${target.absence}` },
1409
+ materializer: {
1410
+ id: 'gea::Optional::empty',
1411
+ domain: `absence:${target.absence}`,
1412
+ allocates: false,
1413
+ nativeFieldProtocol: 'unused',
1414
+ ...nativeClassReferenceIdentityOf(source, target)
1415
+ }
1416
+ };
1417
+ }
1418
+ // widenedStoreText already renders null as the empty state of a native
1419
+ // handle or refcounted class. Neither admits undefined without a flag.
1420
+ // The render is the default-constructed handle (`Ref<T>()`): no payload is
1421
+ // read or built, which is the payload-transport statement below.
1422
+ if (source.kind === 'null' &&
1423
+ (target.kind === 'native-handle' || (target.kind === 'class-ref' && target.ownership === 'shared-refcount'))) {
1424
+ return {
1425
+ classifier: { id: 'empty-reference', domain: 'absence:null' },
1426
+ materializer: {
1427
+ id: 'empty-reference',
1428
+ domain: 'absence:null',
1429
+ allocates: false,
1430
+ nativeFieldProtocol: 'unused',
1431
+ nativePayloadTransport: 'preserved',
1432
+ ...nativeClassReferenceIdentityOf(source, target)
1433
+ }
1434
+ };
1435
+ }
1436
+ // A source still wearing its own optional widens by reading its own
1437
+ // presence flag rather than assuming one -- `emit-narrowing.ts`'s
1438
+ // `widenedStoreText` is what actually renders that read, guarded by a
1439
+ // `has_value()` check when the target keeps an absence of its own and
1440
+ // unconditional (the checker having already proven presence) when it does
1441
+ // not. This only states the pairing is real: the payload widens exactly
1442
+ // as a bare source would, one optional layer down, so the domain is named
1443
+ // separately from the bare-payload case below to keep the two capability
1444
+ // pairs from being mistaken for one another.
1445
+ if (source.kind === 'optional') {
1446
+ const payloadKey = representationKey(source.payload);
1447
+ if (target.kind === 'optional' && representationKey(target.payload) === payloadKey) {
1448
+ return {
1449
+ classifier: { id: 'gea::Optional::converting-ctor', domain: `optional-payload:${payloadKey}` },
1450
+ materializer: {
1451
+ id: 'gea::Optional::converting-ctor',
1452
+ domain: `optional-payload:${payloadKey}`,
1453
+ allocates: false,
1454
+ nativeFieldProtocol: 'unused',
1455
+ ...nativeClassReferenceIdentityOf(source, target)
1456
+ }
1457
+ };
1526
1458
  }
1459
+ const wrappedUnion = target.kind === 'optional' ? target.payload : target;
1460
+ if (wrappedUnion.kind !== 'tagged-union')
1461
+ return null;
1462
+ if (!wrappedUnion.arms.some((arm) => representationKey(arm.value) === payloadKey))
1463
+ return null;
1464
+ return {
1465
+ classifier: { id: 'gea::TaggedUnion::ofArm', domain: `optional-arm:${payloadKey}` },
1466
+ materializer: {
1467
+ id: 'gea::TaggedUnion::ofArm',
1468
+ domain: `optional-arm:${payloadKey}`,
1469
+ allocates: false,
1470
+ nativeFieldProtocol: 'unused',
1471
+ ...nativeClassReferenceIdentityOf(source, target)
1472
+ }
1473
+ };
1474
+ }
1475
+ const sourceKey = representationKey(source);
1476
+ // The bare payload widening straight into its own optional --
1477
+ // `gea::Optional<T>` declares a converting constructor from `T`, so this
1478
+ // needs no tagged union and no arm index at all.
1479
+ if (target.kind === 'optional' && representationKey(target.payload) === sourceKey) {
1480
+ return {
1481
+ classifier: { id: 'gea::Optional::converting-ctor', domain: `payload:${sourceKey}` },
1482
+ materializer: {
1483
+ id: 'gea::Optional::converting-ctor',
1484
+ domain: `payload:${sourceKey}`,
1485
+ allocates: false,
1486
+ nativeFieldProtocol: 'unused',
1487
+ ...nativeClassReferenceIdentityOf(source, target)
1488
+ }
1489
+ };
1490
+ }
1491
+ // A source that is not the payload but reaches it by one of the four
1492
+ // `gea::CallableObject` converting constructors above. Every one of those
1493
+ // was installed only for a BARE callable target, so
1494
+ // `((gl, v) => void)` returned where `((gl, v, textures) => void) |
1495
+ // undefined` is expected -- three's `getSingularSetter`, 30 returns of
1496
+ // exactly that shape -- refused for a pair whose two halves this backend
1497
+ // performs individually. The same four authorities are asked here, one
1498
+ // optional layer down, so the graph and the emitter cannot disagree about
1499
+ // which pairs the runtime accepts.
1500
+ //
1501
+ // `allocates` is true, unlike the bare-payload case: the emitter names
1502
+ // the payload type EXPLICITLY (`convertedValueText`'s optional branch)
1503
+ // because C++ allows one user-defined conversion per implicit sequence
1504
+ // and this pair needs two, so a `CallableObject` really is constructed
1505
+ // here rather than merely wrapped.
1506
+ if (target.kind === 'optional') {
1507
+ const payload = target.payload;
1508
+ const nativeConstructor = dropsUnboundParameters(source, payload) ||
1509
+ dropsAllParametersIntoResultArm(source, payload) ||
1510
+ widensResultIntoArm(source, payload);
1511
+ const restRebase = !nativeConstructor && rebasesRestOverLeadingParameters(source, payload);
1512
+ const adapter = nativeConstructor || restRebase ? null : resultAdapterTransportOf(source, payload);
1513
+ if (nativeConstructor || restRebase || adapter !== null) {
1514
+ const domain = `payload-callable:${sourceKey}->${representationKey(payload)}`;
1515
+ const native = nativeConstructor
1516
+ ? nativeCallableTransport(source, payload)
1517
+ : adapter?.nativeConventions
1518
+ ? {
1519
+ nativeFieldProtocol: 'unused',
1520
+ callableAdapter: adapter.nativeConventions,
1521
+ callableIdentityTransport: 'preserved'
1522
+ }
1523
+ : {};
1524
+ return {
1525
+ classifier: { id: 'gea::Optional::converting-ctor', domain },
1526
+ materializer: { id: 'gea::Optional::converting-ctor', domain, allocates: true, ...native }
1527
+ };
1528
+ }
1529
+ }
1530
+ if ((target.kind === 'optional' || target.kind === 'tagged-union') && hasSingleClassUpcastHome(source, target)) {
1531
+ const domain = `class-upcast-arm:${sourceKey}->${representationKey(target)}`;
1532
+ return {
1533
+ classifier: { id: 'gea::TaggedUnion::ofArm', domain },
1534
+ materializer: {
1535
+ id: 'gea::TaggedUnion::ofArm',
1536
+ domain,
1537
+ allocates: false,
1538
+ nativeFieldProtocol: 'unused',
1539
+ ...nativeClassReferenceIdentityOf(source, target)
1540
+ }
1541
+ };
1542
+ }
1543
+ const union = target.kind === 'optional' ? target.payload : target;
1544
+ if (union.kind !== 'tagged-union')
1545
+ return null;
1546
+ if (union.arms.some((arm) => representationKey(arm.value) === sourceKey)) {
1547
+ return {
1548
+ classifier: { id: 'gea::TaggedUnion::ofArm', domain: `arm:${sourceKey}` },
1549
+ materializer: {
1550
+ id: 'gea::TaggedUnion::ofArm',
1551
+ domain: `arm:${sourceKey}`,
1552
+ allocates: false,
1553
+ nativeFieldProtocol: 'unused',
1554
+ ...nativeClassReferenceIdentityOf(source, target)
1555
+ }
1556
+ };
1557
+ }
1558
+ return null;
1559
+ },
1560
+ // Two tagged unions built from the same member set at different tag orders
1561
+ // -- one declared `boolean | number`, the other `number | boolean` -- need a
1562
+ // recast: every value the source can hold must have a same-typed home among
1563
+ // the target's arms, so the live one can always be rebuilt at the target's
1564
+ // own tag. A source arm with no match in the target is a real hole, not a
1565
+ // missing recipe, and is refused rather than dropped.
1566
+ recasting: (source, target) => {
1567
+ if (!isSpellable(target))
1568
+ return null;
1569
+ const setPair = genericFunctionSetPair(source, target);
1570
+ if (setPair)
1571
+ return setPair;
1572
+ if (source.kind === 'native-record-ref' && source.native === cppStringObjectNativeType && target.kind === 'string') {
1573
+ const domain = `string-object-value:${representationKey(source)}`;
1574
+ return {
1575
+ classifier: { id: 'gea::runtime::StringObject::value', domain },
1576
+ materializer: { id: 'gea::runtime::StringObject::value', domain, allocates: false }
1577
+ };
1578
+ }
1579
+ // The two void-payload guards that used to sit here now live inside
1580
+ // `promisePayloadConvertible`, which is the printer's own authority: a
1581
+ // `Promise<never>` source is admissible and a `Promise<void>` one is not,
1582
+ // and stating that twice is how the census and the printer drift apart.
1583
+ // A payload that only a structural record view carries adopts the same
1584
+ // way: `Promise.resolve({ value, done: false })` returned where
1585
+ // `Promise<IteratorResult<T>>` is declared reaches the yield arm's named
1586
+ // interface by the view, never by the ctx-free chain. `recipeText`
1587
+ // renders the pair from the identical plan.
1588
+ if (source.kind === 'promise' &&
1589
+ target.kind === 'promise' &&
1590
+ (promisePayloadConvertible(source.value, target.value) || viewPlanFor(layouts, source.value, target.value) !== null)) {
1591
+ const domain = `promise-state-adoption:${representationKey(source)}->${representationKey(target)}`;
1592
+ return {
1593
+ classifier: { id: 'gea::Promise::state', domain },
1594
+ materializer: { id: 'gea::Promise::adopt-converted', domain, allocates: true }
1595
+ };
1596
+ }
1597
+ // A hand-written iterator object read as the cursor its declared type
1598
+ // names -- mongodb's `onData` literal, `return this` out of its own
1599
+ // `[Symbol.asyncIterator]()` (`conversion/protocol-iterator.ts`).
1600
+ // `Connection.dataEvents` holds it as `AsyncGenerator<Buffer> | null`.
1601
+ const cursor = target.kind === 'optional' ? target.payload : target;
1602
+ if ((cursor.kind === 'iterator' || cursor.kind === 'async-generator') && protocolIteratorPlanFor(layouts, source, cursor) !== null) {
1603
+ const domain = `protocol-iterator:${representationKey(source)}->${representationKey(target)}`;
1604
+ return {
1605
+ classifier: { id: PROTOCOL_ITERATOR, domain },
1606
+ materializer: { id: PROTOCOL_ITERATOR, domain, allocates: true }
1607
+ };
1608
+ }
1609
+ // The reverse: a native cursor read as the iterator OBJECT an interface
1610
+ // declares -- `mongodb-connection-string-url`'s `keys():
1611
+ // IterableIterator<K> { return super.keys() as IterableIterator<K> }`
1612
+ // over a generator-backed `URLSearchParams.keys()`
1613
+ // (`conversion/iterator-object-view.ts`).
1614
+ // `x.constructor` stored where a constructor family is declared
1615
+ // (`conversion/constructor-identity-family.ts`).
1616
+ if (constructorIdentityFamilyPlan(layouts, source, target) !== null) {
1617
+ const domain = `constructor-identity-family:${representationKey(source)}->${representationKey(target)}`;
1618
+ return {
1619
+ classifier: { id: CONSTRUCTOR_IDENTITY_FAMILY, domain },
1620
+ materializer: { id: CONSTRUCTOR_IDENTITY_FAMILY, domain, allocates: false }
1621
+ };
1622
+ }
1623
+ // A constructor carried by its convention alone read as a class family --
1624
+ // a checked projection by the class evaluation's own declaration token.
1625
+ if (constructorDispatchFamilyPlan(layouts, source, target) !== null) {
1626
+ const domain = `constructor-dispatch-family:${representationKey(source)}->${representationKey(target)}`;
1627
+ return {
1628
+ classifier: { id: CONSTRUCTOR_DISPATCH_FAMILY, domain },
1629
+ materializer: { id: CONSTRUCTOR_DISPATCH_FAMILY, domain, allocates: false }
1630
+ };
1631
+ }
1632
+ const object = target.kind === 'optional' ? target.payload : target;
1633
+ if ((source.kind === 'iterator' || source.kind === 'async-generator') &&
1634
+ iteratorObjectViewPlanFor(layouts, source, object) !== null) {
1635
+ const domain = `iterator-object-view:${representationKey(source)}->${representationKey(target)}`;
1636
+ return {
1637
+ classifier: { id: ITERATOR_OBJECT_VIEW, domain },
1638
+ materializer: { id: ITERATOR_OBJECT_VIEW, domain, allocates: true }
1639
+ };
1640
+ }
1641
+ // An Array or Set read as the iterable object an interface declares --
1642
+ // `Readable.from(['a', 'b'])` into `Iterable<unknown>`
1643
+ // (`conversion/iterable-object-view.ts`).
1644
+ if ((source.kind === 'array-object' || source.kind === 'keyed-collection') &&
1645
+ iterableObjectViewPlanFor(layouts, source, object) !== null) {
1646
+ const domain = `iterable-object-view:${representationKey(source)}->${representationKey(target)}`;
1647
+ return {
1648
+ classifier: { id: ITERABLE_OBJECT_VIEW, domain },
1649
+ materializer: { id: ITERABLE_OBJECT_VIEW, domain, allocates: true }
1650
+ };
1651
+ }
1652
+ if (source.kind === 'record' && target.kind === 'tagged-union' && ownedRecordMaterializationPlan(source, target, layouts) !== null) {
1653
+ const domain = `owned-record-arm:${representationKey(source)}->${representationKey(target)}`;
1654
+ return {
1655
+ classifier: { id: 'gea::record::ownedArm', domain },
1656
+ materializer: { id: 'gea::record::ownedArm', domain, allocates: true }
1657
+ };
1658
+ }
1659
+ // Built on demand, never up front: this function is asked about EVERY
1660
+ // ordered pair of recastable carriers (`conversion/build.ts`), hundreds
1661
+ // of millions on TypeScript's own compiler, and almost every pair leaves
1662
+ // through an early `null` without ever needing its key. Concatenating
1663
+ // it first was one string allocation per pair and a collector busy
1664
+ // reclaiming them -- the same cost `build.ts`'s own loop already paid once.
1665
+ let pairKeyMemo = null;
1666
+ const pairKey = () => {
1667
+ pairKeyMemo ??= `${representationKey(source)}->${representationKey(target)}`;
1668
+ return pairKeyMemo;
1527
1669
  };
1528
- }
1529
- const sum = nativeSumConversion(source, target);
1530
- if (sum)
1531
- return sum;
1532
- // Two boxes are one box. `dynamic`'s `reason` records WHY a value is
1533
- // carried dynamically -- it is diagnostic provenance, not a physical
1534
- // difference -- and `cppTypeOf` spells every one of them `gea::Value`. So
1535
- // a store from one to another is the identity, and refusing it would
1536
- // refuse an assignment C++ performs with no conversion at all.
1537
- //
1538
- // The pair became reachable when `untyped-callable` joined the reason list
1539
- // (`representation/model.ts`): a `Function`-typed value flowing into a
1540
- // cell that holds a declared `any` is two reasons over one carrier, and
1541
- // before this the conversion graph had no node for it even though there
1542
- // was nothing to convert.
1543
- if (source.kind === 'dynamic' && target.kind === 'dynamic') {
1544
- return {
1545
- classifier: { id: 'gea::Value::identity', domain: `dynamic-reason:${pairKey()}` },
1546
- materializer: { id: 'gea::Value::identity', domain: `dynamic-reason:${pairKey()}`, allocates: false }
1547
- };
1548
- }
1549
- // The plain array and the array an interface extended with typed fields
1550
- // (`NodeArray<T> extends ReadonlyArray<T>`, `array-object.extension`) are
1551
- // ONE `gea::ArrayObject<E>`: the fields live in the object's own
1552
- // extension sidecar, so `elements.slice() as MutableNodeArray<T>` is the
1553
- // same object gaining fields on their first write, and a `NodeArray<T>`
1554
- // handed to a `readonly T[]` parameter is that object read as the array
1555
- // it is. Same element, same ownership, and only the extension differs;
1556
- // the identity spelling `convertedValueText` already renders for two
1557
- // carriers with one C++ type is what performs it.
1558
- if (source.kind === 'array-object' &&
1559
- target.kind === 'array-object' &&
1560
- source.ownership === target.ownership &&
1561
- representationKey(source.element) === representationKey(target.element) &&
1562
- arrayExtensionKey(source.extension) !== arrayExtensionKey(target.extension)) {
1563
- return {
1564
- classifier: { id: 'gea::ArrayObject::identity', domain: `array-extension:${pairKey()}` },
1565
- materializer: { id: 'gea::ArrayObject::identity', domain: `array-extension:${pairKey()}`, allocates: false }
1566
- };
1567
- }
1568
- // `never[]` into `E[]`: THE empty array of `E`, by identity. tsc's
1569
- // `emptyArray: never[]` is a sentinel the program compares by identity
1570
- // (`type.resolvedBaseTypes = emptyArray` marks a circular resolution in
1571
- // progress; `=== emptyArray` detects it), so a fresh `[]` is a silently
1572
- // wrong answer and a boxed one a refusal; `gea::emptyArraySentinel<E>()`
1573
- // is one object per element type, so every `never[]` that reaches an
1574
- // `E[]` slot is the same one and compares equal to itself. The carrier
1575
- // cannot tell `never[]` from `undefined[]` (an element with no storage is
1576
- // stored as the absence), so the recipe admits only the pairs TypeScript
1577
- // admits for `never[]` alone: an element that does not carry `undefined`
1578
- // (a genuine `undefined[]` is not assignable to it) and, for `any[]`, a
1579
- // runtime test -- empty is the sentinel, anything else is boxed element
1580
- // by element, which is what a real `undefined[]` into `any[]` means.
1581
- if (source.kind === 'array-object' &&
1582
- target.kind === 'array-object' &&
1583
- source.element.kind === 'undefined' &&
1584
- source.ownership === 'shared-refcount' &&
1585
- target.ownership === 'shared-refcount' &&
1586
- (target.element.kind === 'dynamic' || !carriesUndefined(target.element))) {
1587
- return {
1588
- classifier: { id: 'gea::emptyArraySentinel', domain: `empty-array:${pairKey()}` },
1589
- materializer: { id: 'gea::emptyArraySentinel', domain: `empty-array:${pairKey()}`, allocates: false }
1670
+ if (source.kind === 'native-record-ref' &&
1671
+ target.kind === 'native-record-ref' &&
1672
+ source.native !== null &&
1673
+ source.native === target.native &&
1674
+ source.ownership === target.ownership &&
1675
+ cppTypeOf(source) === cppTypeOf(target)) {
1676
+ return {
1677
+ classifier: { id: 'gea::native-record::identity', domain: `native-identity:${source.native}:${source.ownership}` },
1678
+ materializer: {
1679
+ id: 'gea::native-record::identity',
1680
+ domain: `native-identity:${source.native}:${source.ownership}`,
1681
+ allocates: false
1682
+ }
1683
+ };
1684
+ }
1685
+ const sum = nativeSumConversion(source, target);
1686
+ if (sum)
1687
+ return sum;
1688
+ // Two boxes are one box. `dynamic`'s `reason` records WHY a value is
1689
+ // carried dynamically -- it is diagnostic provenance, not a physical
1690
+ // difference -- and `cppTypeOf` spells every one of them `gea::Value`. So
1691
+ // a store from one to another is the identity, and refusing it would
1692
+ // refuse an assignment C++ performs with no conversion at all.
1693
+ //
1694
+ // The pair became reachable when `untyped-callable` joined the reason list
1695
+ // (`representation/model.ts`): a `Function`-typed value flowing into a
1696
+ // cell that holds a declared `any` is two reasons over one carrier, and
1697
+ // before this the conversion graph had no node for it even though there
1698
+ // was nothing to convert.
1699
+ if (source.kind === 'dynamic' && target.kind === 'dynamic') {
1700
+ return {
1701
+ classifier: { id: 'gea::Value::identity', domain: `dynamic-reason:${pairKey()}` },
1702
+ materializer: { id: 'gea::Value::identity', domain: `dynamic-reason:${pairKey()}`, allocates: false }
1703
+ };
1704
+ }
1705
+ // The plain array and the array an interface extended with typed fields
1706
+ // (`NodeArray<T> extends ReadonlyArray<T>`, `array-object.extension`) are
1707
+ // ONE `gea::ArrayObject<E>`: the fields live in the object's own
1708
+ // extension sidecar, so `elements.slice() as MutableNodeArray<T>` is the
1709
+ // same object gaining fields on their first write, and a `NodeArray<T>`
1710
+ // handed to a `readonly T[]` parameter is that object read as the array
1711
+ // it is. Same element, same ownership, and only the extension differs;
1712
+ // the identity spelling `convertedValueText` already renders for two
1713
+ // carriers with one C++ type is what performs it.
1714
+ if (source.kind === 'array-object' &&
1715
+ target.kind === 'array-object' &&
1716
+ source.ownership === target.ownership &&
1717
+ representationKey(source.element) === representationKey(target.element) &&
1718
+ arrayExtensionKey(source.extension) !== arrayExtensionKey(target.extension)) {
1719
+ return {
1720
+ classifier: { id: 'gea::ArrayObject::identity', domain: `array-extension:${pairKey()}` },
1721
+ materializer: { id: 'gea::ArrayObject::identity', domain: `array-extension:${pairKey()}`, allocates: false }
1722
+ };
1723
+ }
1724
+ // `never[]` into `E[]`: THE empty array of `E`, by identity. tsc's
1725
+ // `emptyArray: never[]` is a sentinel the program compares by identity
1726
+ // (`type.resolvedBaseTypes = emptyArray` marks a circular resolution in
1727
+ // progress; `=== emptyArray` detects it), so a fresh `[]` is a silently
1728
+ // wrong answer and a boxed one a refusal; `gea::emptyArraySentinel<E>()`
1729
+ // is one object per element type, so every `never[]` that reaches an
1730
+ // `E[]` slot is the same one and compares equal to itself. The carrier
1731
+ // cannot tell `never[]` from `undefined[]` (an element with no storage is
1732
+ // stored as the absence), so the recipe admits only the pairs TypeScript
1733
+ // admits for `never[]` alone: an element that does not carry `undefined`
1734
+ // (a genuine `undefined[]` is not assignable to it) and, for `any[]`, a
1735
+ // runtime test -- empty is the sentinel, anything else is boxed element
1736
+ // by element, which is what a real `undefined[]` into `any[]` means.
1737
+ if (source.kind === 'array-object' &&
1738
+ target.kind === 'array-object' &&
1739
+ source.element.kind === 'undefined' &&
1740
+ source.ownership === 'shared-refcount' &&
1741
+ target.ownership === 'shared-refcount' &&
1742
+ (target.element.kind === 'dynamic' || !carriesUndefined(target.element))) {
1743
+ return {
1744
+ classifier: { id: 'gea::emptyArraySentinel', domain: `empty-array:${pairKey()}` },
1745
+ materializer: { id: 'gea::emptyArraySentinel', domain: `empty-array:${pairKey()}`, allocates: false }
1746
+ };
1747
+ }
1748
+ // ⛔ NO CONVERSION IS INSTALLED between two `array-object` carriers whose
1749
+ // ELEMENTS disagree, and none may be. Such a conversion can only ALLOCATE
1750
+ // -- every element needs its own unbox -- and an `ArrayObject` a program
1751
+ // can still reach is a mutable reference, so a fresh array silently drops
1752
+ // every later write through the other name and loses identity outright.
1753
+ // `gea::ArrayObject::recastElements` did exactly that at a call argument
1754
+ // in three's `getProgramCacheKey`: the two helpers pushed ~60 values into
1755
+ // the COPY, so every material's cache key came out identical, one shader
1756
+ // program served the whole scene, and every HUD glyph rendered as a solid
1757
+ // rectangle. A compile refusal is the correct outcome here, and the fix
1758
+ // for a disagreement is to make the two authorities agree -- which is
1759
+ // where `structural-array-element.ts`'s `unstatedNeverArray` parameter
1760
+ // form and `structural.ts`'s `refusedArrayParameterTypeAt` now put it.
1761
+ // See `test/runtime/array-object-call-argument-aliasing.ts`.
1762
+ // Two records declaring the SAME fields under two shape ids -- one written
1763
+ // as `Named & { age: number }`, the other as the literal that satisfies it
1764
+ // -- are one shape this backend spells as two structs, so a value of one is
1765
+ // rebuilt member-wise as the other. `emit-narrowing.ts`'s
1766
+ // `recastedRecordText` is what performs it; asking it here rather than
1767
+ // restating the admission rule keeps the census and the renderer from
1768
+ // disagreeing about which pairs are installed.
1769
+ // A `native-record-ref` target is the SAME question asked of a layout the
1770
+ // carrier only names: it holds a shape id, never a field list, so the pair
1771
+ // was never even proposed (`conversion/build.ts`'s `recastable` filter had
1772
+ // no reason to include a carrier nothing could compare). Resolving the
1773
+ // layout through the one policy and asking `recordsRecastable` the
1774
+ // identical question keeps this admission and the record-to-record one from
1775
+ // ever disagreeing. `emit-callable.ts`'s `structuralRecordViewText` is what
1776
+ // performs it -- the one place in the emitter both layouts are in hand --
1777
+ // reached from an argument slot and, since this pair became admissible,
1778
+ // from a return as well.
1779
+ const asRecord = (candidate) => {
1780
+ if (candidate.kind !== 'native-record-ref' || candidate.native !== null)
1781
+ return candidate;
1782
+ const fields = layouts.forShape(candidate.shapeId);
1783
+ if (fields === null)
1784
+ return candidate;
1785
+ return { kind: 'record', shapeId: candidate.shapeId, ownership: candidate.ownership, fields, accessors: [] };
1590
1786
  };
1591
- }
1592
- // ⛔ NO CONVERSION IS INSTALLED between two `array-object` carriers whose
1593
- // ELEMENTS disagree, and none may be. Such a conversion can only ALLOCATE
1594
- // -- every element needs its own unbox -- and an `ArrayObject` a program
1595
- // can still reach is a mutable reference, so a fresh array silently drops
1596
- // every later write through the other name and loses identity outright.
1597
- // `gea::ArrayObject::recastElements` did exactly that at a call argument
1598
- // in three's `getProgramCacheKey`: the two helpers pushed ~60 values into
1599
- // the COPY, so every material's cache key came out identical, one shader
1600
- // program served the whole scene, and every HUD glyph rendered as a solid
1601
- // rectangle. A compile refusal is the correct outcome here, and the fix
1602
- // for a disagreement is to make the two authorities agree -- which is
1603
- // where `structural-array-element.ts`'s `unstatedNeverArray` parameter
1604
- // form and `structural.ts`'s `refusedArrayParameterTypeAt` now put it.
1605
- // See `test/runtime/array-object-call-argument-aliasing.ts`.
1606
- // Two records declaring the SAME fields under two shape ids -- one written
1607
- // as `Named & { age: number }`, the other as the literal that satisfies it
1608
- // -- are one shape this backend spells as two structs, so a value of one is
1609
- // rebuilt member-wise as the other. `emit-narrowing.ts`'s
1610
- // `recastedRecordText` is what performs it; asking it here rather than
1611
- // restating the admission rule keeps the census and the renderer from
1612
- // disagreeing about which pairs are installed.
1613
- // A `native-record-ref` target is the SAME question asked of a layout the
1614
- // carrier only names: it holds a shape id, never a field list, so the pair
1615
- // was never even proposed (`conversion/build.ts`'s `recastable` filter had
1616
- // no reason to include a carrier nothing could compare). Resolving the
1617
- // layout through the one policy and asking `recordsRecastable` the
1618
- // identical question keeps this admission and the record-to-record one from
1619
- // ever disagreeing. `emit-callable.ts`'s `structuralRecordViewText` is what
1620
- // performs it -- the one place in the emitter both layouts are in hand --
1621
- // reached from an argument slot and, since this pair became admissible,
1622
- // from a return as well.
1623
- const asRecord = (candidate) => {
1624
- if (candidate.kind !== 'native-record-ref' || candidate.native !== null)
1625
- return candidate;
1626
- const fields = layouts.forShape(candidate.shapeId);
1627
- if (fields === null)
1628
- return candidate;
1629
- return { kind: 'record', shapeId: candidate.shapeId, ownership: candidate.ownership, fields, accessors: [] };
1630
- };
1631
- // A generated class written to a structural interface is materialized as
1632
- // the native record view `emit-callable.ts` renders. Data fields are read
1633
- // from the instance and methods become receiver-bound callable members.
1634
- // Build the same effective source shape here so certification asks the
1635
- // existing recursive record predicate about every field carrier before
1636
- // the renderer sees the pair. The concrete source class supplies its own
1637
- // method set, so interfaces with several implementors need no nominal or
1638
- // sole-implementor shortcut.
1639
- if (source.kind === 'class-ref' &&
1640
- source.ownership === 'shared-refcount' &&
1641
- (target.kind === 'native-record-ref' || target.kind === 'record') &&
1642
- !(target.kind === 'native-record-ref' && target.native !== null)) {
1643
- const sourceFields = layouts.forShape(source.shapeId);
1644
- const targetFields = target.kind === 'record'
1645
- ? target.accessors.length === 0
1646
- ? target.fields
1647
- : null
1648
- : (layouts.plainFieldsForShape?.(target.shapeId) ?? null);
1649
- if (sourceFields !== null && targetFields !== null) {
1650
- const projected = [...sourceFields];
1651
- for (const field of targetFields) {
1652
- if (!layouts.classMethodFor?.(source.declaration, field.key))
1653
- continue;
1654
- const abi = 'abi' in field.value ? field.value.abi : null;
1655
- if (abi === null || abi.receiver !== null || abi.restFrom !== null)
1656
- continue;
1657
- const structuralIndex = projected.findIndex((candidate) => candidate.key === field.key);
1658
- if (structuralIndex >= 0)
1659
- projected.splice(structuralIndex, 1);
1660
- projected.push({ key: field.key, value: field.value, required: true });
1787
+ // A generated class written to a structural interface is materialized as
1788
+ // the native record view `emit-callable.ts` renders. Data fields are read
1789
+ // from the instance and methods become receiver-bound callable members.
1790
+ // Build the same effective source shape here so certification asks the
1791
+ // existing recursive record predicate about every field carrier before
1792
+ // the renderer sees the pair. The concrete source class supplies its own
1793
+ // method set, so interfaces with several implementors need no nominal or
1794
+ // sole-implementor shortcut.
1795
+ if (source.kind === 'class-ref' &&
1796
+ source.ownership === 'shared-refcount' &&
1797
+ (target.kind === 'native-record-ref' || target.kind === 'record') &&
1798
+ !(target.kind === 'native-record-ref' && target.native !== null)) {
1799
+ const sourceFields = layouts.forShape(source.shapeId);
1800
+ const targetFields = target.kind === 'record'
1801
+ ? target.accessors.length === 0
1802
+ ? target.fields
1803
+ : null
1804
+ : (layouts.plainFieldsForShape?.(target.shapeId) ?? null);
1805
+ if (sourceFields !== null && targetFields !== null) {
1806
+ const projected = [...sourceFields];
1807
+ for (const field of targetFields) {
1808
+ if (!layouts.classMethodFor?.(source.declaration, field.key))
1809
+ continue;
1810
+ const abi = 'abi' in field.value ? field.value.abi : null;
1811
+ if (abi === null || abi.receiver !== null || abi.restFrom !== null)
1812
+ continue;
1813
+ const structuralIndex = projected.findIndex((candidate) => candidate.key === field.key);
1814
+ if (structuralIndex >= 0)
1815
+ projected.splice(structuralIndex, 1);
1816
+ projected.push({ key: field.key, value: field.value, required: true });
1817
+ }
1818
+ const sourceView = {
1819
+ kind: 'record',
1820
+ shapeId: source.shapeId,
1821
+ ownership: source.ownership,
1822
+ fields: projected,
1823
+ accessors: []
1824
+ };
1825
+ const targetView = {
1826
+ kind: 'record',
1827
+ shapeId: target.shapeId,
1828
+ ownership: target.ownership,
1829
+ fields: targetFields,
1830
+ accessors: []
1831
+ };
1832
+ if (recordsRecastable(sourceView, targetView)) {
1833
+ // The printer renders this atom as the chain's text when the chain
1834
+ // has one and otherwise as the structural view's plan
1835
+ // (`emit-narrowing.ts`'s `recipeText`). Where the plan is what
1836
+ // renders and it only copies held carriers or leaves members
1837
+ // absent, the view reads the instance's own native storage and
1838
+ // publishes nothing through its field protocol -- the same proof
1839
+ // `staticRecipe` states for `view:structural-record`. The origin
1840
+ // the view remembers boxed is read back only by `instanceof` and
1841
+ // by the `gea::record::viewOrigin` narrowing to the class, never by
1842
+ // program code that could write through it. Without it
1843
+ // the reflection census read node-compat's `emitter as unknown as
1844
+ // PausableEmitterMethods` as an unknown boundary, promoted every
1845
+ // emitter subclass and everything their fields reach to full
1846
+ // reflection, and refused each `this.method.bind(this)` in mongodb
1847
+ // as `call-abi:bind-shadowable`.
1848
+ const plan = conversionRecipeOf(source, target)?.renders === true ? null : viewPlanFor(layouts, source, target);
1849
+ return {
1850
+ classifier: { id: 'gea::record::classStructuralView', domain: `class-view:${pairKey()}` },
1851
+ materializer: {
1852
+ id: 'gea::record::classStructuralView',
1853
+ domain: `class-view:${pairKey()}`,
1854
+ allocates: target.ownership === 'shared-refcount',
1855
+ ...(plan !== null ? viewProtocolOf(plan) : {})
1856
+ }
1857
+ };
1858
+ }
1661
1859
  }
1662
- const sourceView = {
1860
+ }
1861
+ // An EMPTY record -- what `[]` with no contextual array type derives, via
1862
+ // the empty tuple -- into a native array-like. Nothing is carried across
1863
+ // and nothing is lost: the source declares no field at all, and the target
1864
+ // is minted value-initialized, which is an array-like holding nothing.
1865
+ // `emit-narrowing.ts`'s `convertedValueText` renders it; installed here so
1866
+ // the merge that needs it is certified rather than emitted uncertified.
1867
+ // The same for an open record whose every declared field is optional:
1868
+ // mongodb's `deleteOne(filter: Filter<TSchema> = {})` defaults a query
1869
+ // document to the empty literal, and the value-initialized struct IS that
1870
+ // object -- every presence bit off, an empty index sidecar.
1871
+ if (source.kind === 'record' &&
1872
+ source.fields.length === 0 &&
1873
+ source.accessors.length === 0 &&
1874
+ (target.kind === 'native-record-ref' || (target.kind === 'record-with-index' && target.fields.every((field) => !field.required)))) {
1875
+ return {
1876
+ classifier: { id: 'gea::record::emptyNative', domain: `empty:${pairKey()}` },
1877
+ materializer: { id: 'gea::record::emptyNative', domain: `empty:${pairKey()}`, allocates: target.ownership === 'shared-refcount' }
1878
+ };
1879
+ }
1880
+ if (source.kind === 'record-with-index' && target.kind === 'native-record-ref' && target.native === null) {
1881
+ const targetFields = layouts.forShape(target.shapeId);
1882
+ const targetIndexes = layouts.indexesForShape?.(target.shapeId) ?? [];
1883
+ const sourceFields = {
1663
1884
  kind: 'record',
1664
1885
  shapeId: source.shapeId,
1665
1886
  ownership: source.ownership,
1666
- fields: projected,
1887
+ fields: source.fields,
1667
1888
  accessors: []
1668
1889
  };
1669
- const targetView = {
1670
- kind: 'record',
1671
- shapeId: target.shapeId,
1672
- ownership: target.ownership,
1673
- fields: targetFields,
1674
- accessors: []
1675
- };
1676
- if (recordsRecastable(sourceView, targetView)) {
1890
+ const targetFieldsView = targetFields === null
1891
+ ? null
1892
+ : { kind: 'record', shapeId: target.shapeId, ownership: target.ownership, fields: targetFields, accessors: [] };
1893
+ if (targetFieldsView !== null &&
1894
+ targetIndexes.length === source.indexes.length &&
1895
+ targetIndexes.every((targetIndex, index) => {
1896
+ const sourceIndex = source.indexes[index];
1897
+ return (sourceIndex !== undefined &&
1898
+ targetIndex.key === sourceIndex.key &&
1899
+ representationKey(targetIndex.value) === representationKey(sourceIndex.value));
1900
+ }) &&
1901
+ recordsRecastable(sourceFields, targetFieldsView)) {
1677
1902
  return {
1678
- classifier: { id: 'gea::record::classStructuralView', domain: `class-view:${pairKey()}` },
1903
+ classifier: { id: 'gea::record::recastWithIndex', domain: `recast-index:${pairKey()}` },
1679
1904
  materializer: {
1680
- id: 'gea::record::classStructuralView',
1681
- domain: `class-view:${pairKey()}`,
1905
+ id: 'gea::record::recastWithIndex',
1906
+ domain: `recast-index:${pairKey()}`,
1682
1907
  allocates: target.ownership === 'shared-refcount'
1683
1908
  }
1684
1909
  };
1685
1910
  }
1911
+ // A closed named interface may receive an open record at runtime even
1912
+ // though the interface itself declares no index signature. TypeScript's
1913
+ // structural assignment permits that value, and JavaScript keeps the
1914
+ // extra own properties: BSON's `Object.assign(o, this.fields)` returns a
1915
+ // `DBRefLike` whose user fields must still enumerate and serialize.
1916
+ //
1917
+ // The target does not need an inline index member. Every shared native
1918
+ // record already has the identity-keyed expando table implemented by
1919
+ // `nativeDynamicGet`/`Set` in the runtime. Admit only the sidecar carrier
1920
+ // that table stores exactly -- string keys and `gea::Value` payloads --
1921
+ // and only a data-only target layout. `emit-callable.ts` copies the
1922
+ // source sidecar into that expando table after rebuilding the named
1923
+ // fields, so no property is dropped and the typed target stays native.
1924
+ const plainTargetFields = layouts.plainFieldsForShape?.(target.shapeId) ?? null;
1925
+ const plainTargetView = plainTargetFields === null
1926
+ ? null
1927
+ : { kind: 'record', shapeId: target.shapeId, ownership: target.ownership, fields: plainTargetFields, accessors: [] };
1928
+ if (targetIndexes.length === 0 &&
1929
+ target.ownership === 'shared-refcount' &&
1930
+ source.indexes.length === 1 &&
1931
+ source.indexes[0]?.key === 'string' &&
1932
+ source.indexes[0]?.value.kind === 'dynamic' &&
1933
+ plainTargetView !== null &&
1934
+ recordsRecastable(sourceFields, plainTargetView)) {
1935
+ return {
1936
+ classifier: { id: 'gea::record::recastWithExpando', domain: `recast-expando:${pairKey()}` },
1937
+ materializer: { id: 'gea::record::recastWithExpando', domain: `recast-expando:${pairKey()}`, allocates: true }
1938
+ };
1939
+ }
1686
1940
  }
1687
- }
1688
- // An EMPTY record -- what `[]` with no contextual array type derives, via
1689
- // the empty tuple -- into a native array-like. Nothing is carried across
1690
- // and nothing is lost: the source declares no field at all, and the target
1691
- // is minted value-initialized, which is an array-like holding nothing.
1692
- // `emit-narrowing.ts`'s `convertedValueText` renders it; installed here so
1693
- // the merge that needs it is certified rather than emitted uncertified.
1694
- if (source.kind === 'record' && source.fields.length === 0 && source.accessors.length === 0 && target.kind === 'native-record-ref') {
1695
- return {
1696
- classifier: { id: 'gea::record::emptyNative', domain: `empty:${pairKey()}` },
1697
- materializer: { id: 'gea::record::emptyNative', domain: `empty:${pairKey()}`, allocates: target.ownership === 'shared-refcount' }
1698
- };
1699
- }
1700
- if (source.kind === 'record-with-index' && target.kind === 'native-record-ref' && target.native === null) {
1701
- const targetFields = layouts.forShape(target.shapeId);
1702
- const targetIndexes = layouts.indexesForShape?.(target.shapeId) ?? [];
1703
- const sourceFields = {
1704
- kind: 'record',
1705
- shapeId: source.shapeId,
1706
- ownership: source.ownership,
1707
- fields: source.fields,
1708
- accessors: []
1709
- };
1710
- const targetFieldsView = targetFields === null
1711
- ? null
1712
- : { kind: 'record', shapeId: target.shapeId, ownership: target.ownership, fields: targetFields, accessors: [] };
1713
- if (targetFieldsView !== null &&
1714
- targetIndexes.length === source.indexes.length &&
1715
- targetIndexes.every((targetIndex, index) => {
1716
- const sourceIndex = source.indexes[index];
1717
- return (sourceIndex !== undefined &&
1718
- targetIndex.key === sourceIndex.key &&
1719
- representationKey(targetIndex.value) === representationKey(sourceIndex.value));
1720
- }) &&
1721
- recordsRecastable(sourceFields, targetFieldsView)) {
1941
+ // A class viewed as a record of its own properties: mongodb's
1942
+ // `defineAspects(AggregateOperation, ...)` takes the class as
1943
+ // `{ aspects?: Set<symbol> }`, and `hasAspect` reads
1944
+ // `(this.constructor as { aspects?: Set<symbol> }).aspects`. The view is
1945
+ // the class evaluation's own record for the shape, so a write through one
1946
+ // view is every later view's read (`gea::constructorStaticView`).
1947
+ if (constructorStaticViewAdmitted(source, target, target.kind === 'native-record-ref' ? layouts.forShape(target.shapeId) : null)) {
1722
1948
  return {
1723
- classifier: { id: 'gea::record::recastWithIndex', domain: `recast-index:${pairKey()}` },
1949
+ classifier: { id: CONSTRUCTOR_STATIC_VIEW, domain: `constructor-view:${pairKey()}` },
1950
+ materializer: { id: CONSTRUCTOR_STATIC_VIEW, domain: `constructor-view:${pairKey()}`, allocates: true }
1951
+ };
1952
+ }
1953
+ // An open `any` document read as a named interface: mongodb's
1954
+ // `new MongoServerError(document)` hands a `Document` to a parameter typed
1955
+ // `ErrorDescription`. The same checked rebuild `dictionary-to-record`
1956
+ // performs for an anonymous record, over the layout the name resolves to;
1957
+ // a string index sidecar of `any` keeps every key the fields do not name.
1958
+ // `emit-narrowing.ts`'s `documentAdoptionText` renders it, and the
1959
+ // Document then views the record rather than leaving a copy beside it.
1960
+ // `DbOptions` in mongodb's `new Db(client, name, options?)` is the
1961
+ // optional case: `filterOptions` returns a Document.
1962
+ const named = target.kind === 'optional' ? target.payload : target;
1963
+ // Lifted through an optional of the same absence: mongodb's
1964
+ // `this.statements.find((o: Document) => o.hint)` answers
1965
+ // `Document | undefined` where `DeleteStatement | undefined` is carried.
1966
+ const document = source.kind === 'optional' && target.kind === 'optional' && source.absence === target.absence ? source.payload : source;
1967
+ if (document.kind === 'dictionary' &&
1968
+ named.kind === 'native-record-ref' &&
1969
+ dynamicDictionaryToNamedRecordAdmitted(document, named, layouts.forShape(named.shapeId), layouts.indexesForShape?.(named.shapeId) ?? [])) {
1970
+ return {
1971
+ classifier: { id: DYNAMIC_DICTIONARY_TO_NAMED_RECORD, domain: `dictionary-record:${pairKey()}` },
1972
+ materializer: { id: DYNAMIC_DICTIONARY_TO_NAMED_RECORD, domain: `dictionary-record:${pairKey()}`, allocates: true }
1973
+ };
1974
+ }
1975
+ if ((source.kind === 'record' || source.kind === 'native-record-ref') && target.kind === 'native-record-ref') {
1976
+ const viewed = asRecord(source);
1977
+ const viewedTarget = asRecord(target);
1978
+ if (viewedTarget.kind !== 'record' || viewed.kind !== 'record')
1979
+ return null;
1980
+ if (!recordsRecastable(viewed, viewedTarget))
1981
+ return null;
1982
+ return {
1983
+ classifier: { id: 'gea::record::recast', domain: `recast:${pairKey()}` },
1724
1984
  materializer: {
1725
- id: 'gea::record::recastWithIndex',
1726
- domain: `recast-index:${pairKey()}`,
1727
- allocates: target.ownership === 'shared-refcount'
1985
+ id: 'gea::record::recast',
1986
+ domain: `recast:${pairKey()}`,
1987
+ allocates: target.ownership === 'shared-refcount',
1988
+ // Unused only while no field crosses the dynamic boundary; a boxed
1989
+ // field is read through the payload's protocol later
1990
+ // (`recordRecastCrossesDynamic`).
1991
+ ...(recordRecastCrossesDynamic(viewed, viewedTarget) ? {} : { nativeFieldProtocol: 'unused' })
1728
1992
  }
1729
1993
  };
1730
1994
  }
1731
- // A closed named interface may receive an open record at runtime even
1732
- // though the interface itself declares no index signature. TypeScript's
1733
- // structural assignment permits that value, and JavaScript keeps the
1734
- // extra own properties: BSON's `Object.assign(o, this.fields)` returns a
1735
- // `DBRefLike` whose user fields must still enumerate and serialize.
1736
- //
1737
- // The target does not need an inline index member. Every shared native
1738
- // record already has the identity-keyed expando table implemented by
1739
- // `nativeDynamicGet`/`Set` in the runtime. Admit only the sidecar carrier
1740
- // that table stores exactly -- string keys and `gea::Value` payloads --
1741
- // and only a data-only target layout. `emit-callable.ts` copies the
1742
- // source sidecar into that expando table after rebuilding the named
1743
- // fields, so no property is dropped and the typed target stays native.
1744
- const plainTargetFields = layouts.plainFieldsForShape?.(target.shapeId) ?? null;
1745
- const plainTargetView = plainTargetFields === null
1746
- ? null
1747
- : { kind: 'record', shapeId: target.shapeId, ownership: target.ownership, fields: plainTargetFields, accessors: [] };
1748
- if (targetIndexes.length === 0 &&
1749
- target.ownership === 'shared-refcount' &&
1750
- source.indexes.length === 1 &&
1751
- source.indexes[0]?.key === 'string' &&
1752
- source.indexes[0]?.value.kind === 'dynamic' &&
1753
- plainTargetView !== null &&
1754
- recordsRecastable(sourceFields, plainTargetView)) {
1995
+ // The arm the value belongs in, written as a DIFFERENT shape id than the
1996
+ // arm declares. A tuple literal returned into a union of tuple types is
1997
+ // the case -- hono's `PatternRouter.match` writes `[handlers]` against
1998
+ // `Result<T> = [[T, Params][]] | [[T, ParamIndexMap][], ParamStash]` --
1999
+ // and an exact-key search cannot see it, because the literal's own shape
2000
+ // id is minted at the literal and the arm's at the declaration. It is
2001
+ // still the same shape: `recordsRecastable` is the one authority on that,
2002
+ // asked here so this admission and `armInjectedText`'s render, which asks
2003
+ // it through `recastedRecordText`, can never disagree. When several arms
2004
+ // accept the value it carries no field that tells them apart (every
2005
+ // distinguishing field is optional and absent), so each is a correct
2006
+ // home; the first is the one `armInjectedText` renders into.
2007
+ if (source.kind === 'record' && target.kind === 'tagged-union') {
2008
+ const recastable = target.arms.map((arm) => arm.value).filter((arm) => arm.kind === 'record' && recordsRecastable(source, arm));
2009
+ const sole = recastable[0];
2010
+ if (!sole || sole.kind !== 'record')
2011
+ return null;
1755
2012
  return {
1756
- classifier: { id: 'gea::record::recastWithExpando', domain: `recast-expando:${pairKey()}` },
1757
- materializer: { id: 'gea::record::recastWithExpando', domain: `recast-expando:${pairKey()}`, allocates: true }
2013
+ classifier: { id: 'gea::TaggedUnion::ofArm', domain: `arm-recast:${pairKey()}` },
2014
+ materializer: {
2015
+ id: 'gea::TaggedUnion::ofArm',
2016
+ domain: `arm-recast:${pairKey()}`,
2017
+ allocates: sole.ownership === 'shared-refcount',
2018
+ nativeFieldProtocol: 'unused'
2019
+ }
1758
2020
  };
1759
2021
  }
1760
- }
1761
- if ((source.kind === 'record' || source.kind === 'native-record-ref') && target.kind === 'native-record-ref') {
1762
- const viewed = asRecord(source);
1763
- const viewedTarget = asRecord(target);
1764
- if (viewedTarget.kind !== 'record' || viewed.kind !== 'record')
1765
- return null;
1766
- if (!recordsRecastable(viewed, viewedTarget))
1767
- return null;
1768
- return {
1769
- classifier: { id: 'gea::record::recast', domain: `recast:${pairKey()}` },
1770
- materializer: {
1771
- id: 'gea::record::recast',
1772
- domain: `recast:${pairKey()}`,
1773
- allocates: target.ownership === 'shared-refcount',
1774
- // Unused only while no field crosses the dynamic boundary; a boxed
1775
- // field is read through the payload's protocol later
1776
- // (`recordRecastCrossesDynamic`).
1777
- ...(recordRecastCrossesDynamic(viewed, viewedTarget) ? {} : { nativeFieldProtocol: 'unused' })
1778
- }
1779
- };
1780
- }
1781
- // The arm the value belongs in, written as a DIFFERENT shape id than the
1782
- // arm declares. A tuple literal returned into a union of tuple types is
1783
- // the case -- hono's `PatternRouter.match` writes `[handlers]` against
1784
- // `Result<T> = [[T, Params][]] | [[T, ParamIndexMap][], ParamStash]` --
1785
- // and an exact-key search cannot see it, because the literal's own shape
1786
- // id is minted at the literal and the arm's at the declaration. It is
1787
- // still the same shape: `recordsRecastable` is the one authority on that,
1788
- // asked here so this admission and `armInjectedText`'s render, which asks
1789
- // it through `recastedRecordText`, can never disagree. When several arms
1790
- // accept the value it carries no field that tells them apart (every
1791
- // distinguishing field is optional and absent), so each is a correct
1792
- // home; the first is the one `armInjectedText` renders into.
1793
- if (source.kind === 'record' && target.kind === 'tagged-union') {
1794
- const recastable = target.arms.map((arm) => arm.value).filter((arm) => arm.kind === 'record' && recordsRecastable(source, arm));
1795
- const sole = recastable[0];
1796
- if (!sole || sole.kind !== 'record')
1797
- return null;
1798
- return {
1799
- classifier: { id: 'gea::TaggedUnion::ofArm', domain: `arm-recast:${pairKey()}` },
1800
- materializer: {
1801
- id: 'gea::TaggedUnion::ofArm',
1802
- domain: `arm-recast:${pairKey()}`,
1803
- allocates: sole.ownership === 'shared-refcount',
1804
- nativeFieldProtocol: 'unused'
1805
- }
1806
- };
1807
- }
1808
- // The same admission for a dictionary whose values widen into ONE
1809
- // dictionary arm of the union -- the string dictionary `@hono/node-server`
1810
- // merges into `[string, string][] | OutgoingHttpHeaders`. Only a SOLE
1811
- // castable arm, for the same reason as the record rule: two would make
1812
- // the choice of arm a guess. `emit-narrowing.ts`'s `widenedStoreText`
1813
- // renders it through `recastedDictionaryText` at the arm it finds first,
1814
- // which under this admission is the only one.
1815
- if (source.kind === 'dictionary' && target.kind === 'tagged-union') {
1816
- const recastable = target.arms
1817
- .map((arm) => arm.value)
1818
- .filter((arm) => arm.kind === 'dictionary' && dictionaryCastableToDictionary(source, arm));
1819
- if (recastable.length !== 1)
1820
- return null;
1821
- return {
1822
- classifier: { id: 'gea::TaggedUnion::ofArm', domain: `arm-recast:${pairKey()}` },
1823
- materializer: { id: 'gea::TaggedUnion::ofArm', domain: `arm-recast:${pairKey()}`, allocates: true, nativeFieldProtocol: 'unused' }
1824
- };
1825
- }
1826
- if (source.kind === 'record' && target.kind === 'record') {
1827
- if (!recordsRecastable(source, target))
1828
- return null;
1829
- return {
1830
- classifier: { id: 'gea::record::recast', domain: `recast:${pairKey()}` },
1831
- materializer: {
1832
- id: 'gea::record::recast',
1833
- domain: `recast:${pairKey()}`,
1834
- allocates: target.ownership === 'shared-refcount',
1835
- // This renderer only copies fields, injects native alternatives and
1836
- // recursively rebuilds records. It never asks a dynamic field table
1837
- // -- unless a field it copies is boxed into (or unboxed out of) a
1838
- // `dynamic` destination: that payload is read through its own field
1839
- // protocol by every later dynamic read, so the claim is withheld
1840
- // (`recordRecastCrossesDynamic`) and the payload keeps its protocol.
1841
- ...(recordRecastCrossesDynamic(source, target) ? {} : { nativeFieldProtocol: 'unused' })
1842
- }
1843
- };
1844
- }
1845
- // A closed record's fields poured into an open dictionary -- one level out
1846
- // from the record-to-record recast just above, and sound for the same
1847
- // reason: the dictionary can hold every field the record has, so nothing
1848
- // is lost going from the closed shape to the open one. `derive.ts`'s
1849
- // `dictionary` case is the mirror refusal (recovering a closed field list
1850
- // from an open one is not derivable); this direction has no such gap.
1851
- // `emit-narrowing.ts`'s `recordCastableToDictionary` is the one authority
1852
- // for which pairs actually rebuild, asked here rather than restated.
1853
- if (source.kind === 'record' && target.kind === 'dictionary') {
1854
- if (!recordCastableToDictionary(source, target))
1855
- return null;
1856
- return {
1857
- classifier: { id: 'gea::record::recastToDictionary', domain: `recast:${pairKey()}` },
1858
- materializer: { id: 'gea::record::recastToDictionary', domain: `recast:${pairKey()}`, allocates: true }
1859
- };
1860
- }
1861
- // One shape wider: an open dictionary's values widened into another open
1862
- // dictionary's -- `Record<string, string>` reaching `OutgoingHttpHeaders`.
1863
- // `emit-narrowing.ts`'s `dictionaryCastableToDictionary` is the one
1864
- // authority for which pairs rebuild, asked here rather than restated.
1865
- if (source.kind === 'dictionary' && target.kind === 'dictionary') {
1866
- if (!dictionaryCastableToDictionary(source, target))
1867
- return null;
1868
- return {
1869
- classifier: { id: 'gea::dictionary::recastValues', domain: `recast:${pairKey()}` },
1870
- materializer: { id: 'gea::dictionary::recastValues', domain: `recast:${pairKey()}`, allocates: true }
1871
- };
1872
- }
1873
- // A third recast at the same distance: a closed, contiguous-numeric-keyed
1874
- // record -- an unannotated rest parameter's open-arity tuple view, from
1875
- // `semantics/normalize/structural.ts`'s `restParameterArrayElementAt` --
1876
- // poured into the array it physically is. `emit-narrowing.ts`'s
1877
- // `recordCastableToArray` is the one authority for which pairs rebuild.
1878
- if (source.kind === 'record' && target.kind === 'array-object') {
1879
- if (!recordCastableToArray(source, target))
1880
- return null;
1881
- return {
1882
- classifier: { id: 'gea::record::recastToArray', domain: `recast:${pairKey()}` },
1883
- materializer: { id: 'gea::record::recastToArray', domain: `recast:${pairKey()}`, allocates: true }
1884
- };
1885
- }
1886
- // Two optionals over the IDENTICAL payload that disagree only on which
1887
- // falsy JS value spends the absence -- `string | null` widened into a
1888
- // `string | undefined` slot (`request.ts`'s `this.raw.headers.get(name) ??
1889
- // undefined`, where DOM `Headers.get` returns `string | null`). `gea::
1890
- // Optional<T>` has no field for which value caused the empty state --
1891
- // `cppTypeOf` never reads `.absence` -- so the two carriers are one C++
1892
- // type under two identities, and `emit-narrowing.ts`'s `convertedValueText`
1893
- // already renders this as the value unchanged (its `cppTypeOf(source) ===
1894
- // cppTypeOf(target)` shortcut). This only asks whether the CAPABILITY
1895
- // exists; a payload that itself still needs converting is refused here and
1896
- // left to the ordinary narrowing/widening obligations to require.
1897
- if (source.kind === 'optional' && target.kind === 'optional') {
1898
- if (representationKey(source.payload) === representationKey(target.payload)) {
1899
- // Payload already identical: the only difference is which falsy value
1900
- // spends the absence, so this is `rebrandAbsence` alone (see above).
1901
- if (source.absence === target.absence)
2022
+ // The same admission for a dictionary whose values widen into ONE
2023
+ // dictionary arm of the union -- the string dictionary `@hono/node-server`
2024
+ // merges into `[string, string][] | OutgoingHttpHeaders`. Only a SOLE
2025
+ // castable arm, for the same reason as the record rule: two would make
2026
+ // the choice of arm a guess. `emit-narrowing.ts`'s `widenedStoreText`
2027
+ // renders it through `recastedDictionaryText` at the arm it finds first,
2028
+ // which under this admission is the only one.
2029
+ if (source.kind === 'dictionary' && target.kind === 'tagged-union') {
2030
+ const recastable = target.arms
2031
+ .map((arm) => arm.value)
2032
+ .filter((arm) => arm.kind === 'dictionary' && dictionaryCastableToDictionary(source, arm));
2033
+ if (recastable.length !== 1)
1902
2034
  return null;
1903
2035
  return {
1904
- classifier: { id: 'gea::Optional::rebrandAbsence', domain: `recast:${pairKey()}` },
1905
- materializer: { id: 'gea::Optional::rebrandAbsence', domain: `recast:${pairKey()}`, allocates: false }
2036
+ classifier: { id: 'gea::TaggedUnion::ofArm', domain: `arm-recast:${pairKey()}` },
2037
+ materializer: { id: 'gea::TaggedUnion::ofArm', domain: `arm-recast:${pairKey()}`, allocates: true, nativeFieldProtocol: 'unused' }
1906
2038
  };
1907
2039
  }
1908
- // The payload is a record recast one level in: `return toSearchResult(
1909
- // undefined)` where the copy at `T = undefined` returns `{ value:
1910
- // undefined } | undefined` into a slot declared `SearchResult<Resolved>`
1911
- // (13 rows on tsc's moduleNameResolver.ts). The bare pair is already
1912
- // admitted just below (`gea::record::recast`); the presence bit adds
1913
- // nothing to convert, only a branch to render, so the admission is the
1914
- // same question asked of the payloads. Same absence on both sides, as
1915
- // for the union case: an absence-tag difference alongside a reshaping is
1916
- // two conversions, not one.
1917
- if (source.payload.kind === 'record' &&
1918
- target.payload.kind === 'record' &&
1919
- source.absence === target.absence &&
1920
- recordsRecastable(source.payload, target.payload)) {
2040
+ if (source.kind === 'record' && target.kind === 'record') {
2041
+ if (!recordsRecastable(source, target))
2042
+ return null;
1921
2043
  return {
1922
- classifier: { id: 'gea::Optional::has_value', domain: `recast:${pairKey()}` },
2044
+ classifier: { id: 'gea::record::recast', domain: `recast:${pairKey()}` },
1923
2045
  materializer: {
1924
- id: 'gea::Optional::recastPayload',
2046
+ id: 'gea::record::recast',
1925
2047
  domain: `recast:${pairKey()}`,
1926
- allocates: target.payload.ownership === 'shared-refcount',
1927
- nativeFieldProtocol: 'unused'
2048
+ allocates: target.ownership === 'shared-refcount',
2049
+ // This renderer only copies fields, injects native alternatives and
2050
+ // recursively rebuilds records. It never asks a dynamic field table
2051
+ // -- unless a field it copies is boxed into (or unboxed out of) a
2052
+ // `dynamic` destination: that payload is read through its own field
2053
+ // protocol by every later dynamic read, so the claim is withheld
2054
+ // (`recordRecastCrossesDynamic`) and the payload keeps its protocol.
2055
+ ...(recordRecastCrossesDynamic(source, target) ? {} : { nativeFieldProtocol: 'unused' })
1928
2056
  }
1929
2057
  };
1930
2058
  }
1931
- // The payload is a dictionary reaching the one wider dictionary arm of
1932
- // the target's union, still wrapped in its presence bit: `cache[2] ||
1933
- // (... ? undefined : { 'content-type': ... })` merged as `optional(
1934
- // dictionary(string, string))` into `optional([string, string][] |
1935
- // OutgoingHttpHeaders)`. The bare pair is the arm-recast admission just
1936
- // above; the presence bit adds only the branch `emit-narrowing.ts`'s
1937
- // `optional-payload-convert` already renders around any converted
1938
- // payload. Same absence on both sides, as for every optional pair here.
1939
- const sourceDictionary = source.payload.kind === 'dictionary' ? source.payload : null;
1940
- if (sourceDictionary !== null &&
1941
- target.payload.kind === 'tagged-union' &&
1942
- source.absence === target.absence &&
1943
- target.payload.arms.filter((arm) => arm.value.kind === 'dictionary' && dictionaryCastableToDictionary(sourceDictionary, arm.value))
1944
- .length === 1) {
2059
+ // A closed record's fields poured into an open dictionary -- one level out
2060
+ // from the record-to-record recast just above, and sound for the same
2061
+ // reason: the dictionary can hold every field the record has, so nothing
2062
+ // is lost going from the closed shape to the open one. `derive.ts`'s
2063
+ // `dictionary` case is the mirror refusal (recovering a closed field list
2064
+ // from an open one is not derivable); this direction has no such gap.
2065
+ // `emit-narrowing.ts`'s `recordCastableToDictionary` is the one authority
2066
+ // for which pairs actually rebuild, asked here rather than restated.
2067
+ // A named interface is the same closed field list, resolved through the
2068
+ // layout it names (`asRecord`): mongodb builds `OIDCCommand` and hands it
2069
+ // to `connection.command(ns, cmd: Document)`.
2070
+ // A record that also carries an open string index -- mongodb's
2071
+ // `Filter<TSchema>`, or a named interface whose layout declares one --
2072
+ // poured into an open string dictionary, or into the ONE dictionary arm of
2073
+ // a union (`Document | Document[]`): the named fields, then every
2074
+ // enumerable index entry (`indexedRecordCastableToDictionary`). Ahead of
2075
+ // the plain recast below, which knows only the named fields and would drop
2076
+ // the rest. A `dynamic` arm beside the dictionary is not a second home:
2077
+ // the typed dictionary holds the document natively.
2078
+ // A shared record handed to an open `any` Document is that record, viewed
2079
+ // (`classDocumentViewText`, in the chain): a table of its fields would be
2080
+ // a second object, deaf to every write made through either name after.
2081
+ if (classDocumentViewText(source, target, 'gea_view_probe') !== null)
2082
+ return null;
2083
+ const indexedView = indexedRecordViewOf(source, layouts);
2084
+ if (indexedView !== null && target.kind === 'dictionary') {
2085
+ if (!indexedRecordCastableToDictionary(indexedView, target))
2086
+ return null;
1945
2087
  return {
1946
- classifier: { id: 'gea::Optional::has_value', domain: `recast:${pairKey()}` },
2088
+ classifier: { id: INDEXED_RECORD_TO_DICTIONARY, domain: `recast:${pairKey()}` },
2089
+ materializer: { id: INDEXED_RECORD_TO_DICTIONARY, domain: `recast:${pairKey()}`, allocates: true }
2090
+ };
2091
+ }
2092
+ if (indexedView !== null && target.kind === 'tagged-union' && indexedRecordDictionaryArmOf(indexedView, target) !== null) {
2093
+ return {
2094
+ classifier: { id: INDEXED_RECORD_INTO_DICTIONARY_ARM, domain: `arm-recast:${pairKey()}` },
2095
+ materializer: { id: INDEXED_RECORD_INTO_DICTIONARY_ARM, domain: `arm-recast:${pairKey()}`, allocates: true }
2096
+ };
2097
+ }
2098
+ if ((source.kind === 'record' || (source.kind === 'native-record-ref' && !source.recursive)) && target.kind === 'dictionary') {
2099
+ const viewed = asRecord(source);
2100
+ if (viewed.kind !== 'record' || !recordCastableToDictionary(viewed, target))
2101
+ return null;
2102
+ return {
2103
+ classifier: { id: 'gea::record::recastToDictionary', domain: `recast:${pairKey()}` },
2104
+ materializer: { id: 'gea::record::recastToDictionary', domain: `recast:${pairKey()}`, allocates: true }
2105
+ };
2106
+ }
2107
+ // One shape wider: an open dictionary's values widened into another open
2108
+ // dictionary's -- `Record<string, string>` reaching `OutgoingHttpHeaders`.
2109
+ // `emit-narrowing.ts`'s `dictionaryCastableToDictionary` is the one
2110
+ // authority for which pairs rebuild, asked here rather than restated.
2111
+ if (source.kind === 'dictionary' && target.kind === 'dictionary') {
2112
+ if (!dictionaryCastableToDictionary(source, target))
2113
+ return null;
2114
+ return {
2115
+ classifier: { id: 'gea::dictionary::recastValues', domain: `recast:${pairKey()}` },
2116
+ materializer: { id: 'gea::dictionary::recastValues', domain: `recast:${pairKey()}`, allocates: true }
2117
+ };
2118
+ }
2119
+ // A third recast at the same distance: a closed, contiguous-numeric-keyed
2120
+ // record -- an unannotated rest parameter's open-arity tuple view, from
2121
+ // `semantics/normalize/structural.ts`'s `restParameterArrayElementAt` --
2122
+ // poured into the array it physically is. `emit-narrowing.ts`'s
2123
+ // `recordCastableToArray` is the one authority for which pairs rebuild.
2124
+ if (source.kind === 'record' && target.kind === 'array-object') {
2125
+ if (!recordCastableToArray(source, target))
2126
+ return null;
2127
+ return {
2128
+ classifier: { id: 'gea::record::recastToArray', domain: `recast:${pairKey()}` },
2129
+ materializer: { id: 'gea::record::recastToArray', domain: `recast:${pairKey()}`, allocates: true }
2130
+ };
2131
+ }
2132
+ // Two optionals over the IDENTICAL payload that disagree only on which
2133
+ // falsy JS value spends the absence -- `string | null` widened into a
2134
+ // `string | undefined` slot (`request.ts`'s `this.raw.headers.get(name) ??
2135
+ // undefined`, where DOM `Headers.get` returns `string | null`). `gea::
2136
+ // Optional<T>` has no field for which value caused the empty state --
2137
+ // `cppTypeOf` never reads `.absence` -- so the two carriers are one C++
2138
+ // type under two identities, and `emit-narrowing.ts`'s `convertedValueText`
2139
+ // already renders this as the value unchanged (its `cppTypeOf(source) ===
2140
+ // cppTypeOf(target)` shortcut). This only asks whether the CAPABILITY
2141
+ // exists; a payload that itself still needs converting is refused here and
2142
+ // left to the ordinary narrowing/widening obligations to require.
2143
+ if (source.kind === 'optional' && target.kind === 'optional') {
2144
+ if (representationKey(source.payload) === representationKey(target.payload)) {
2145
+ // Payload already identical: the only difference is which falsy value
2146
+ // spends the absence, so this is `rebrandAbsence` alone (see above).
2147
+ if (source.absence === target.absence)
2148
+ return null;
2149
+ return {
2150
+ classifier: { id: 'gea::Optional::rebrandAbsence', domain: `recast:${pairKey()}` },
2151
+ // Same payload, only the absence tag is renamed: no field is read.
2152
+ materializer: {
2153
+ id: 'gea::Optional::rebrandAbsence',
2154
+ domain: `recast:${pairKey()}`,
2155
+ allocates: false,
2156
+ nativeFieldProtocol: 'unused',
2157
+ nativePayloadTransport: 'preserved'
2158
+ }
2159
+ };
2160
+ }
2161
+ // The payload is a record recast one level in: `return toSearchResult(
2162
+ // undefined)` where the copy at `T = undefined` returns `{ value:
2163
+ // undefined } | undefined` into a slot declared `SearchResult<Resolved>`
2164
+ // (13 rows on tsc's moduleNameResolver.ts). The bare pair is already
2165
+ // admitted just below (`gea::record::recast`); the presence bit adds
2166
+ // nothing to convert, only a branch to render, so the admission is the
2167
+ // same question asked of the payloads. Same absence on both sides, as
2168
+ // for the union case: an absence-tag difference alongside a reshaping is
2169
+ // two conversions, not one.
2170
+ if (source.payload.kind === 'record' &&
2171
+ target.payload.kind === 'record' &&
2172
+ source.absence === target.absence &&
2173
+ recordsRecastable(source.payload, target.payload)) {
2174
+ return {
2175
+ classifier: { id: 'gea::Optional::has_value', domain: `recast:${pairKey()}` },
2176
+ materializer: {
2177
+ id: 'gea::Optional::recastPayload',
2178
+ domain: `recast:${pairKey()}`,
2179
+ allocates: target.payload.ownership === 'shared-refcount',
2180
+ nativeFieldProtocol: 'unused'
2181
+ }
2182
+ };
2183
+ }
2184
+ // The payload is a dictionary reaching the one wider dictionary arm of
2185
+ // the target's union, still wrapped in its presence bit: `cache[2] ||
2186
+ // (... ? undefined : { 'content-type': ... })` merged as `optional(
2187
+ // dictionary(string, string))` into `optional([string, string][] |
2188
+ // OutgoingHttpHeaders)`. The bare pair is the arm-recast admission just
2189
+ // above; the presence bit adds only the branch `emit-narrowing.ts`'s
2190
+ // `optional-payload-convert` already renders around any converted
2191
+ // payload. Same absence on both sides, as for every optional pair here.
2192
+ const sourceDictionary = source.payload.kind === 'dictionary' ? source.payload : null;
2193
+ if (sourceDictionary !== null &&
2194
+ target.payload.kind === 'tagged-union' &&
2195
+ source.absence === target.absence &&
2196
+ target.payload.arms.filter((arm) => arm.value.kind === 'dictionary' && dictionaryCastableToDictionary(sourceDictionary, arm.value)).length === 1) {
2197
+ return {
2198
+ classifier: { id: 'gea::Optional::has_value', domain: `recast:${pairKey()}` },
2199
+ materializer: {
2200
+ id: 'gea::Optional::recastPayloadArm',
2201
+ domain: `recast:${pairKey()}`,
2202
+ allocates: true,
2203
+ nativeFieldProtocol: 'unused'
2204
+ }
2205
+ };
2206
+ }
2207
+ // The payload itself is a union recast one level in -- `optional(string |
2208
+ // boolean, undefined)` merged against `optional(boolean | string,
2209
+ // undefined)`, the two branches of a control-flow merge each arriving
2210
+ // through an independently-declared union (the SAME shape
2211
+ // `recastedUnionText` handles for a bare union, just still wrapped in the
2212
+ // presence bit). Both payloads must be tagged unions built from the same
2213
+ // member set for this to be sound -- an absence-tag difference alongside
2214
+ // a genuine payload reshaping is two conversions, not one, and is left
2215
+ // unclaimed rather than composed here.
2216
+ if (source.payload.kind !== 'tagged-union' || target.payload.kind !== 'tagged-union')
2217
+ return null;
2218
+ if (source.absence !== target.absence)
2219
+ return null;
2220
+ const payloadTargetKeys = target.payload.arms.map((arm) => representationKey(arm.value));
2221
+ if (!source.payload.arms.every((arm) => payloadTargetKeys.includes(representationKey(arm.value))))
2222
+ return null;
2223
+ return {
2224
+ classifier: { id: 'gea::TaggedUnion::is', domain: `recast:${pairKey()}` },
2225
+ // Every source arm is a target arm BY KEY, so `recastedUnionText`
2226
+ // homes each one exact (`ofArm<j>(get<i>())`): a re-tag, no field read.
1947
2227
  materializer: {
1948
- id: 'gea::Optional::recastPayloadArm',
2228
+ id: 'gea::TaggedUnion::ofArm',
1949
2229
  domain: `recast:${pairKey()}`,
1950
- allocates: true,
1951
- nativeFieldProtocol: 'unused'
2230
+ allocates: false,
2231
+ nativeFieldProtocol: 'unused',
2232
+ nativePayloadTransport: 'preserved'
1952
2233
  }
1953
2234
  };
1954
2235
  }
1955
- // The payload itself is a union recast one level in -- `optional(string |
1956
- // boolean, undefined)` merged against `optional(boolean | string,
1957
- // undefined)`, the two branches of a control-flow merge each arriving
1958
- // through an independently-declared union (the SAME shape
1959
- // `recastedUnionText` handles for a bare union, just still wrapped in the
1960
- // presence bit). Both payloads must be tagged unions built from the same
1961
- // member set for this to be sound -- an absence-tag difference alongside
1962
- // a genuine payload reshaping is two conversions, not one, and is left
1963
- // unclaimed rather than composed here.
1964
- if (source.payload.kind !== 'tagged-union' || target.payload.kind !== 'tagged-union')
1965
- return null;
1966
- if (source.absence !== target.absence)
2236
+ // A sum every arm of which reaches ONE payload, wrapped in the presence
2237
+ // bit: `fn === undefined ? node : fn(node, ...)` returned as `T |
2238
+ // undefined` from tsc's `visitEachChild<T>` -- `tagged-union(
2239
+ // native-record-ref | dynamic)` into `optional(native-record-ref)`, 74
2240
+ // rows from one site on the self-compile, one per instantiation. The
2241
+ // typed arm is the payload and the dynamic arm is the checked unbox, and
2242
+ // `emit-narrowing.ts`'s `sumIntoPayloadText` is asked here so the pair is
2243
+ // admitted on exactly the render that will spell it.
2244
+ if (source.kind === 'tagged-union' &&
2245
+ target.kind === 'optional' &&
2246
+ target.absence === 'undefined' &&
2247
+ sumIntoPayloadText(source, target.payload, 'gea_sum', (arm) => arm) !== null) {
2248
+ return {
2249
+ classifier: { id: 'gea::TaggedUnion::is', domain: `sum-into-payload:${pairKey()}` },
2250
+ materializer: { id: 'gea::TaggedUnion::intoPayload', domain: `sum-into-payload:${pairKey()}`, allocates: false }
2251
+ };
2252
+ }
2253
+ if (source.kind !== 'tagged-union' || target.kind !== 'tagged-union')
1967
2254
  return null;
1968
- const payloadTargetKeys = target.payload.arms.map((arm) => representationKey(arm.value));
1969
- if (!source.payload.arms.every((arm) => payloadTargetKeys.includes(representationKey(arm.value))))
2255
+ const targetKeys = target.arms.map((arm) => representationKey(arm.value));
2256
+ if (!source.arms.every((arm) => targetKeys.includes(representationKey(arm.value))))
1970
2257
  return null;
1971
2258
  return {
1972
2259
  classifier: { id: 'gea::TaggedUnion::is', domain: `recast:${pairKey()}` },
1973
- materializer: { id: 'gea::TaggedUnion::ofArm', domain: `recast:${pairKey()}`, allocates: false }
1974
- };
1975
- }
1976
- // A sum every arm of which reaches ONE payload, wrapped in the presence
1977
- // bit: `fn === undefined ? node : fn(node, ...)` returned as `T |
1978
- // undefined` from tsc's `visitEachChild<T>` -- `tagged-union(
1979
- // native-record-ref | dynamic)` into `optional(native-record-ref)`, 74
1980
- // rows from one site on the self-compile, one per instantiation. The
1981
- // typed arm is the payload and the dynamic arm is the checked unbox, and
1982
- // `emit-narrowing.ts`'s `sumIntoPayloadText` is asked here so the pair is
1983
- // admitted on exactly the render that will spell it.
1984
- if (source.kind === 'tagged-union' &&
1985
- target.kind === 'optional' &&
1986
- target.absence === 'undefined' &&
1987
- sumIntoPayloadText(source, target.payload, 'gea_sum', (arm) => arm) !== null) {
1988
- return {
1989
- classifier: { id: 'gea::TaggedUnion::is', domain: `sum-into-payload:${pairKey()}` },
1990
- materializer: { id: 'gea::TaggedUnion::intoPayload', domain: `sum-into-payload:${pairKey()}`, allocates: false }
2260
+ // A pure re-tag, as the optional-wrapped twin above.
2261
+ materializer: {
2262
+ id: 'gea::TaggedUnion::ofArm',
2263
+ domain: `recast:${pairKey()}`,
2264
+ allocates: false,
2265
+ nativeFieldProtocol: 'unused',
2266
+ nativePayloadTransport: 'preserved'
2267
+ }
1991
2268
  };
1992
- }
1993
- if (source.kind !== 'tagged-union' || target.kind !== 'tagged-union')
1994
- return null;
1995
- const targetKeys = target.arms.map((arm) => representationKey(arm.value));
1996
- if (!source.arms.every((arm) => targetKeys.includes(representationKey(arm.value))))
1997
- return null;
1998
- return {
1999
- classifier: { id: 'gea::TaggedUnion::is', domain: `recast:${pairKey()}` },
2000
- materializer: { id: 'gea::TaggedUnion::ofArm', domain: `recast:${pairKey()}`, allocates: false }
2001
- };
2002
- },
2003
- /**
2004
- * Asked of the printer's own chain (`emit-narrowing.ts`'s
2005
- * `conversionChain`), so the census answers exactly what the printer
2006
- * renders. The chain's step ids are the recipe ids; a step that claims the
2007
- * pair but cannot render it is reported as no recipe, which is the same
2008
- * refusal the printer would raise at emission. `allocates` is stated per
2009
- * step: the recipes that mint a fresh value are the ones that construct
2010
- * a target from parts.
2011
- */
2012
- // Installed exactly when the printer's own renderer has a text for it
2013
- // (`emit-coercion.ts` says why the same function answers both).
2014
- coercion: (source, operation) => coercionText(operation, 'x', source, layouts) === null
2015
- ? null
2016
- : { id: `coercion:${operation}`, domain: `coercion:${operation}:${representationKey(source)}`, allocates: operation === 'ToString' },
2017
- staticRecipe: (source, target) => {
2018
- if (!isSpellable(source) || !isSpellable(target))
2019
- return null;
2020
- if (classArmWithoutHome(layouts, source, target))
2269
+ },
2270
+ /**
2271
+ * Asked of the printer's own chain (`emit-narrowing.ts`'s
2272
+ * `conversionChain`), so the census answers exactly what the printer
2273
+ * renders. The chain's step ids are the recipe ids; a step that claims the
2274
+ * pair but cannot render it is reported as no recipe, which is the same
2275
+ * refusal the printer would raise at emission. `allocates` is stated per
2276
+ * step: the recipes that mint a fresh value are the ones that construct
2277
+ * a target from parts.
2278
+ */
2279
+ // Installed exactly when the printer's own renderer has a text for it
2280
+ // (`emit-coercion.ts` says why the same function answers both).
2281
+ coercion: (source, operation) => coercionText(operation, 'x', source, layouts) === null
2282
+ ? null
2283
+ : {
2284
+ id: `coercion:${operation}`,
2285
+ domain: `coercion:${operation}:${representationKey(source)}`,
2286
+ allocates: operation === 'ToString'
2287
+ },
2288
+ staticRecipe: (source, target) => {
2289
+ if (!isSpellable(source) || !isSpellable(target))
2290
+ return null;
2291
+ if (classArmWithoutHome(layouts, source, target))
2292
+ return null;
2293
+ if (proxyArmWithoutHome(source, target))
2294
+ return null;
2295
+ // A sum some arm of which reaches the record-shaped target only through
2296
+ // the structural view is that view's `dispatch` plan, asked BEFORE the
2297
+ // chain: the chain answers the pair too, by selecting the exact arm, and
2298
+ // that selection is the narrowing this table's `narrowing` entry has
2299
+ // already declined for the pair (`recordViewDispatchesArms`). The
2300
+ // printer renders in the same order (`emit-narrowing.ts`'s `recipeText`).
2301
+ const dispatching = viewPlanFor(layouts, source, target);
2302
+ if (dispatching !== null && recordViewDispatchesArms(dispatching))
2303
+ return {
2304
+ id: 'view:structural-record',
2305
+ domain: 'static:structural-record-view',
2306
+ allocates: true,
2307
+ ...viewProtocolOf(dispatching)
2308
+ };
2309
+ const recipe = conversionRecipeOf(source, target);
2310
+ if (recipe !== null && recipe.renders) {
2311
+ // `unreachable-value` spells either `unreachableValue<T>()` (a throw that
2312
+ // reads nothing) or a discard into `undefined`: no field is read and no
2313
+ // payload is built. `same-cpp-type` spells the value itself -- the two
2314
+ // carriers are one C++ type -- so it is identity at run time: gea's
2315
+ // `constructor-family` into `new () => C`, or a `jsx-element` handle
2316
+ // stored as `GeaElement` where one host type carries both. A `narrowed-load` out of a sum is the structural
2317
+ // load whose contract its leaf pairs compose (see `nativeNarrowing`).
2318
+ // `optional-wrap-converted` spells `Optional<P>{P{inner}}` around the
2319
+ // chain's own text for (source, payload), so it reads a field table
2320
+ // exactly when that inner conversion does (`nativeWrappedPayload`).
2321
+ const native = recipe.id === 'unreachable-value' || recipe.id === 'same-cpp-type'
2322
+ ? { nativeFieldProtocol: 'unused', nativePayloadTransport: 'preserved' }
2323
+ : recipe.id === 'narrowed-load' && (source.kind === 'optional' || source.kind === 'tagged-union')
2324
+ ? nativeNarrowing(source, target)
2325
+ : recipe.id === 'optional-wrap-converted' && target.kind === 'optional'
2326
+ ? nativeWrappedPayload(source, target.payload)
2327
+ : // `optional-payload-convert` spells `has_value() ? T{P{convert(*x)}} : T{}`,
2328
+ // the same shape around the payload's own conversion.
2329
+ recipe.id === 'optional-payload-convert' && source.kind === 'optional' && target.kind === 'optional'
2330
+ ? nativeWrappedPayload(source.payload, target.payload)
2331
+ : {};
2332
+ return { id: `chain:${recipe.id}`, domain: `static:${recipe.id}`, allocates: allocatingRecipes.has(recipe.id), ...native };
2333
+ }
2334
+ // After the chain, as the printer asks (`emit.ts`'s `emitConvert`): a
2335
+ // record rebuilt as another shape it satisfies, decided by the plan the
2336
+ // printer renders from (`conversion/record-view.ts`). `viewPlanFor`
2337
+ // caches this build so the printer's later render of the same node
2338
+ // (`emit-record-view.ts`'s `structuralRecordViewText`) reads the plan
2339
+ // this existence check already built rather than rebuilding it.
2340
+ const view = viewPlanFor(layouts, source, target);
2341
+ if (view !== null) {
2342
+ const heldUnused = heldPairUnusedOf(nativeWrappedPayload);
2343
+ if (process.env.GEA_REFLECTION_DEBUG !== undefined) {
2344
+ const indirect = recordViewIndirectReads(view, heldUnused);
2345
+ if (indirect.length > 0)
2346
+ console.error(`[VIEW-INDIRECT] ${representationKey(source).slice(0, 100)} -> ${representationKey(target).slice(0, 100)} reads=${indirect.join(',').slice(0, 300)}`);
2347
+ }
2348
+ return {
2349
+ id: 'view:structural-record',
2350
+ domain: 'static:structural-record-view',
2351
+ allocates: true,
2352
+ ...viewProtocolOf(view)
2353
+ };
2354
+ }
2355
+ // A callable whose parameter reaches the source's only through a record
2356
+ // view (`emit-narrowing.ts`'s `VIEW_ADAPTED_CALLABLE`): the chain's own
2357
+ // adapter asked the same parameters and found no layout-free conversion.
2358
+ if (source.kind === 'function-value-dispatch' &&
2359
+ target.kind === 'function-value-dispatch' &&
2360
+ !containsUnresolved(source) &&
2361
+ !containsUnresolved(target) &&
2362
+ tryCandidateText(() => resultAdaptedCallableText(source, target, 'gea_conversion_probe', (from, to, text) => viewPlanFor(layouts, from, to) === null ? null : `gea_view(${text})`)) !== null)
2363
+ return { id: VIEW_ADAPTED_CALLABLE, domain: 'static:adapted-callable', allocates: true };
2364
+ // Some arms homed, some with no home anywhere (`CHECKED_ARM_NARROWING`).
2365
+ if (checkedArmNarrowingText(source, target, 'gea_conversion_probe') !== null)
2366
+ return { id: CHECKED_ARM_NARROWING, domain: 'static:checked-arm-narrowing', allocates: false };
2367
+ // The printer's own last resort behind the view (`structuralRecordViewText`).
2368
+ if (boxedAssertionText(source, target, 'gea_conversion_probe') !== null)
2369
+ return { id: 'view:boxed-assertion', domain: 'static:boxed-assertion', allocates: true };
2021
2370
  return null;
2022
- // A sum some arm of which reaches the record-shaped target only through
2023
- // the structural view is that view's `dispatch` plan, asked BEFORE the
2024
- // chain: the chain answers the pair too, by selecting the exact arm, and
2025
- // that selection is the narrowing this table's `narrowing` entry has
2026
- // already declined for the pair (`recordViewDispatchesArms`). The
2027
- // printer renders in the same order (`emit-narrowing.ts`'s `recipeText`).
2028
- const dispatching = viewPlanFor(layouts, source, target);
2029
- if (dispatching !== null && recordViewDispatchesArms(dispatching))
2371
+ },
2372
+ // The same view, knowing which family members the site named; rendered by
2373
+ // `emit-record-view.ts`'s `familyMemberViewText` from the node's own
2374
+ // `familyMembers`. No boxed fallback: a pair this plan refuses stays refused.
2375
+ familyMemberView: (source, target, members) => {
2376
+ if (!isSpellable(source) || !isSpellable(target))
2377
+ return null;
2378
+ if (classArmWithoutHome(layouts, source, target))
2379
+ return null;
2380
+ if (proxyArmWithoutHome(source, target))
2381
+ return null;
2382
+ const view = familyMemberViewPlanFor(layouts, source, target, members);
2383
+ if (view === null)
2384
+ return null;
2030
2385
  return {
2031
- id: 'view:structural-record',
2032
- domain: 'static:structural-record-view',
2386
+ id: FAMILY_MEMBER_VIEW_MATERIALIZER,
2387
+ domain: 'static:family-member-record-view',
2033
2388
  allocates: true,
2034
- ...(recordViewUsesOnlyDirectFields(dispatching) ? { nativeFieldProtocol: 'unused' } : {})
2389
+ ...viewProtocolOf(view)
2035
2390
  };
2036
- const recipe = conversionRecipeOf(source, target);
2037
- if (recipe !== null && recipe.renders) {
2038
- // `unreachable-value` spells either `unreachableValue<T>()` (a throw that
2039
- // reads nothing) or a discard into `undefined`: no field is read and no
2040
- // payload is built. A `narrowed-load` out of a sum is the structural
2041
- // load whose contract its leaf pairs compose (see `nativeNarrowing`).
2042
- // `optional-wrap-converted` spells `Optional<P>{P{inner}}` around the
2043
- // chain's own text for (source, payload), so it reads a field table
2044
- // exactly when that inner conversion does (`nativeWrappedPayload`).
2045
- const native = recipe.id === 'unreachable-value'
2046
- ? { nativeFieldProtocol: 'unused', nativePayloadTransport: 'preserved' }
2047
- : recipe.id === 'narrowed-load' && (source.kind === 'optional' || source.kind === 'tagged-union')
2048
- ? nativeNarrowing(source, target)
2049
- : recipe.id === 'optional-wrap-converted' && target.kind === 'optional'
2050
- ? nativeWrappedPayload(source, target.payload)
2051
- : {};
2052
- return { id: `chain:${recipe.id}`, domain: `static:${recipe.id}`, allocates: allocatingRecipes.has(recipe.id), ...native };
2053
2391
  }
2054
- // After the chain, as the printer asks (`emit.ts`'s `emitConvert`): a
2055
- // record rebuilt as another shape it satisfies, decided by the plan the
2056
- // printer renders from (`conversion/record-view.ts`). `viewPlanFor`
2057
- // caches this build so the printer's later render of the same node
2058
- // (`emit-record-view.ts`'s `structuralRecordViewText`) reads the plan
2059
- // this existence check already built rather than rebuilding it.
2060
- const view = viewPlanFor(layouts, source, target);
2061
- if (view !== null)
2062
- return {
2063
- id: 'view:structural-record',
2064
- domain: 'static:structural-record-view',
2065
- allocates: true,
2066
- ...(recordViewUsesOnlyDirectFields(view) ? { nativeFieldProtocol: 'unused' } : {})
2067
- };
2068
- // The printer's own last resort behind the view (`structuralRecordViewText`).
2069
- if (boxedAssertionText(source, target, 'gea_conversion_probe') !== null)
2070
- return { id: 'view:boxed-assertion', domain: 'static:boxed-assertion', allocates: true };
2071
- return null;
2072
- }
2073
- });
2392
+ };
2393
+ };
2074
2394
  const allocatingRecipes = new Set([
2395
+ // A host may lazily allocate the per-object state behind its view.
2396
+ 'native-handle-view',
2075
2397
  'array-element-recast',
2076
2398
  'array-copy-recast',
2077
2399
  'empty-record-into-native',
@@ -2084,6 +2406,9 @@ const allocatingRecipes = new Set([
2084
2406
  'optional-record-recast',
2085
2407
  'record-to-dictionary',
2086
2408
  'dictionary-to-record',
2409
+ 'class-document-view',
2087
2410
  'record-to-array',
2088
- 'promise-payload'
2411
+ 'promise-payload',
2412
+ 'readonly-map-view',
2413
+ 'dynamic-map-arm-view'
2089
2414
  ]);