@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,18 +1,28 @@
1
- import { classRefTransportKind, constructorUpcastMember } from './class-ref-transport.js';
2
- import { abiKey, arrayExtensionKey, containsUnresolved, isBooleanShapedMergeTarget, isCanonicalNumberPropertyKeyText, representationKey, walkRepresentation, carriesUndefined } from '../../representation/model.js';
1
+ import { isNativeCallableCarrier } from '../../representation/callable-object.js';
2
+ import { isNativeError } from './error-types.js';
3
+ import { proxyArmWithoutHome } from '../../representation/proxy-carriers.js';
4
+ import { cppRecordIndexSidecarName, tailAwareFieldReadText, tailAwareFieldWriteText, tailFieldsOf } from './records.js';
5
+ import { classRefTransportKind, constructorFamilyUpcastMembers, constructorUpcastMember, nativeRecordBaseTransportKind, nativePromiseBaseOf } from './class-ref-transport.js';
6
+ import { abiKey, arrayExtensionKey, containsUnresolved, isBooleanShapedMergeTarget, isCanonicalNumberPropertyKeyText, isOpenDocument, representationKey, standInRefuses, walkRepresentation, carriesUndefined } from '../../representation/model.js';
3
7
  import { transferOf } from '../../ir/transfer.js';
4
8
  import { coercionText } from './emit-coercion.js';
5
- import { EXACT_ARM_MATERIALIZER, exactArmIndexOf } from '../../conversion/nodes.js';
6
- import { structuralRecordViewText, viewPlanFor } from './emit-record-view.js';
9
+ import { ARM_VIEW_MATERIALIZER, ASSERTED_UNION_MATERIALIZER, ASSERTED_UNION_COPY_MATERIALIZER, EXACT_ARM_MATERIALIZER, FAMILY_MEMBER_VIEW_MATERIALIZER, CAUGHT_HANDOFF_MATERIALIZER, NULLISH_OPTIONAL_MATERIALIZER, NATIVE_BASE_VIEW_MATERIALIZER, exactArmIndexOf, isNativeCollectionUpcast } from '../../conversion/nodes.js';
10
+ import { familyMemberViewText, structuralRecordViewText, unionRecastPlanOf, viewPlanFor } from './emit-record-view.js';
11
+ import { PROTOCOL_ITERATOR, protocolIteratorText } from './emit-protocol-iterator.js';
12
+ import { ITERABLE_OBJECT_VIEW, iterableObjectViewText } from './emit-iterable-object-view.js';
13
+ import { ITERATOR_OBJECT_VIEW, iteratorObjectViewText } from './emit-iterator-object-view.js';
14
+ import { CONSTRUCTOR_DISPATCH_FAMILY, CONSTRUCTOR_IDENTITY_FAMILY, constructorDispatchFamilyText, constructorIdentityFamilyText } from './emit-constructor-identity-family.js';
7
15
  import { recordViewDispatchesArms } from '../../conversion/record-view.js';
8
16
  import { createCppEmitBlockedError, cppConstructThunkName, cppThunkName, defineValue, isCppEmitBlockedError, isDeferredValue, operandText } from './emit-context.js';
9
17
  import { booleanTestText } from './emit-presence.js';
10
18
  import { recastedRecordToArrayText } from './emit-arrays.js';
11
- import { cppAbiParameterType, cppAbiType, cppClassName, cppConstantLiteral, cppRecordFieldName, cppRecordFieldPresenceName, cppRecordStructName, cppResultTypeOf, cppStringLiteral, cppTypeOf, cppUndefinedIn, cppUndefinedValue } from './types.js';
19
+ import { cppAbiParameterType, cppAbiType, cppClassName, cppConstantLiteral, cppRecordFieldName, cppRecordFieldKeyIsSymbol, cppRecordFieldPresenceName, cppRecordStructName, cppResultTypeOf, cppStringLiteral, cppTypeOf, cppNarrowedIntegerType, cppUndefinedIn, cppUndefinedValue, storageSlotIsNarrowed, unitFunctionName, withoutUnitFunctions } from './types.js';
20
+ import { integerStorageSlot } from '../../ir/integer-storage.js';
12
21
  import { cppRegExpNativeTypes, cppStringObjectNativeType } from './regexp-types.js';
13
22
  import { widenedNativeSumText } from './emit-sum-widening.js';
14
23
  import { nativeSelectionText } from './emit-native-selection.js';
15
24
  import { narrowingReachesTarget } from '../../conversion/build.js';
25
+ import { evaluatedOnceText } from './evaluated-once.js';
16
26
  /**
17
27
  * `native-record-ref` (the String WRAPPER OBJECT, `new String(x)`) -> `string`,
18
28
  * the one direction `convertedValueText` needs that neither `narrowedLoadText`
@@ -50,14 +60,15 @@ export const promisePayloadConvertible = (source, target) => {
50
60
  // fulfils a promise resolved with nothing with `undefined`, and this runtime
51
61
  // elides that `undefined` entirely for `void` (`cppResultTypeOf`). So the
52
62
  // unit pair reconciles by supplying or dropping the value, in either
53
- // direction, while `void` against any richer payload stays a hole.
63
+ // direction. An unknown payload can also hold that undefined value; it must
64
+ // receive the fulfillment value rather than a boxed source promise.
54
65
  // `@hono/node-server`'s `listener.ts` needs exactly this: `responseViaCache`
55
66
  // is declared `Promise<undefined | void>` and both callers `return` its
56
67
  // promise from an async function whose own result is `Promise<void>`.
57
68
  if (target.kind === 'void')
58
69
  return isUnitPromisePayload(source);
59
70
  if (source.kind === 'void')
60
- return source.bottom === true || isUnitPromisePayload(target);
71
+ return source.bottom === true || acceptsVoidPromisePayload(target);
61
72
  try {
62
73
  return convertedValueText(source, target, 'gea_promise_payload') !== null;
63
74
  }
@@ -69,6 +80,8 @@ export const promisePayloadConvertible = (source, target) => {
69
80
  };
70
81
  /** A promise payload that carries no information: `void`, and the `undefined` it is spelled as wherever a value is required. */
71
82
  const isUnitPromisePayload = (payload) => payload.kind === 'void' || payload.kind === 'undefined';
83
+ /** A void fulfillment supplies undefined, including at an explicitly unknown boundary. */
84
+ const acceptsVoidPromisePayload = (payload) => isUnitPromisePayload(payload) || payload.kind === 'dynamic';
72
85
  /** `RegExpMatchArray` read through the `Array<string>` base it inherits. */
73
86
  const regexpMatchArrayBaseText = (source, target, text) => source.kind === 'native-record-ref' &&
74
87
  source.native === cppRegExpNativeTypes['match-result'] &&
@@ -79,7 +92,7 @@ const regexpMatchArrayBaseText = (source, target, text) => source.kind === 'nati
79
92
  ? `${cppTypeOf(target)}(${text})`
80
93
  : null;
81
94
  /** A failed candidate is not a failed search when another union arm can carry the value. */
82
- const tryCandidateText = (build) => {
95
+ export const tryCandidateText = (build) => {
83
96
  try {
84
97
  return build();
85
98
  }
@@ -189,7 +202,7 @@ export const classFamilyLoadText = (ctx, held, read, text) => {
189
202
  * through to the last without testing it, because the narrowing already proved
190
203
  * one of them is live and a test with no else has nothing to return.
191
204
  */
192
- const taggedUnionArmText = (union, target, text) => {
205
+ const taggedUnionArmText = (union, target, text, unhomed = 'refuse') => {
193
206
  const targetKey = representationKey(target);
194
207
  const exact = union.arms
195
208
  .map((arm, index) => ({ arm, index }))
@@ -226,9 +239,23 @@ const taggedUnionArmText = (union, target, text) => {
226
239
  // A union target that some arm only WIDENS into is a recast, not a
227
240
  // narrowing: the narrowing proved nothing about which arm is live, so every
228
241
  // arm needs its home or the read would rebuild a live arm as another.
242
+ // Whatever the uncovered arm is: a class or a named record left without a
243
+ // home is dropped just as surely as a structural one, and the chain then
244
+ // reads the wrong arm's payload. mongodb's `resolveOptions(parent:
245
+ // OperationParent)` handed a Collection to `resolveBSONOptions`'s
246
+ // `Db | MongoClient | { bsonOptions? }` parameter and read it as a Db.
229
247
  const partialWidening = target.kind === 'tagged-union' &&
230
248
  candidates.some((candidate) => !exact.includes(candidate)) &&
231
- union.arms.some((arm, index) => arm.value.kind === 'record' && !candidates.some((candidate) => candidate.index === index));
249
+ union.arms.some((_, index) => !candidates.some((candidate) => candidate.index === index));
250
+ if (unhomed === 'throw' && last && partialWidening) {
251
+ // `CHECKED_ARM_NARROWING`: every arm without a home throws, checked by
252
+ // its own discriminant, so none is ever read as another.
253
+ const targetType = cppTypeOf(target);
254
+ let result = `gea::host::unhomedUnionArm<${targetType}>(${text}.index())`;
255
+ for (const entry of [...candidates].reverse())
256
+ result = `${text}.is<${entry.index}>() ? ${entry.text} : (${result})`;
257
+ return `(${result})`;
258
+ }
232
259
  if (!last || partialWidening) {
233
260
  throw createCppEmitBlockedError(`conversion:${representationKey(union)}->${targetKey}`, `narrows tagged union "${representationKey(union)}" to "${targetKey}", which none of its arms carries`);
234
261
  }
@@ -369,6 +396,10 @@ const narrowedUnionSubsetText = (inner, read, text) => {
369
396
  export const narrowedLoadText = (held, read, text) => {
370
397
  if (representationKey(held) === representationKey(read))
371
398
  return null;
399
+ // No guard the checker proved can have ruled a proxy arm out; the census
400
+ // refuses the pair (`proxyArmWithoutHome`), and so does every printer path.
401
+ if (proxyArmWithoutHome(held, read))
402
+ return null;
372
403
  const remappedSet = genericFunctionSetWideningText(held, read, text);
373
404
  if (remappedSet !== null)
374
405
  return remappedSet;
@@ -437,10 +468,11 @@ export const narrowedLoadText = (held, read, text) => {
437
468
  // This direction is a store-style widening, so it is proved from the
438
469
  // source's ancestry. The downcast immediately below proves the inverse
439
470
  // direction from the target's ancestry and remains the checked narrowing.
440
- if (inner.kind === 'class-ref' &&
471
+ if ((inner.kind === 'class-ref' &&
441
472
  read.kind === 'class-ref' &&
442
473
  inner.ownership === read.ownership &&
443
- inner.ancestors.includes(read.declaration)) {
474
+ inner.ancestors.includes(read.declaration)) ||
475
+ nativeRecordBaseTransportKind(inner, read) === 'upcast') {
444
476
  return `${cppTypeOf(read)}(${unwrapped})`;
445
477
  }
446
478
  // A program-class handle read at a DERIVED class -- `part instanceof Mesh`
@@ -461,10 +493,9 @@ export const narrowedLoadText = (held, read, text) => {
461
493
  // widening and `widenedStoreText` answers it with `Ref`'s own converting
462
494
  // constructor. Ownership must agree -- a handle and a by-value struct of the
463
495
  // same class are different physical things, not a heritage question.
464
- if (inner.kind === 'class-ref' &&
465
- read.kind === 'class-ref' &&
466
- inner.ownership === read.ownership &&
467
- read.ancestors.includes(inner.declaration)) {
496
+ if (read.kind === 'class-ref' &&
497
+ ((inner.kind === 'class-ref' && inner.ownership === read.ownership && read.ancestors.includes(inner.declaration)) ||
498
+ nativeRecordBaseTransportKind(inner, read) === 'downcast')) {
468
499
  return `gea::host::downcastClassRef<${cppClassName(read.declaration)}>(${unwrapped})`;
469
500
  }
470
501
  // A cell that provably holds nothing but absence, read at a place declared
@@ -773,6 +804,12 @@ export const dynamicTagFor = (representation) => {
773
804
  // widenings `targets/cpp/conversions.ts`'s `widening` registry asks this
774
805
  // exact function about.
775
806
  case 'typed-array':
807
+ // A DataView is the third ArrayBuffer view kind and boxes the same way:
808
+ // `gea::Ref<gea::DataView>` is one monomorphic payload address, which
809
+ // `gea::host::isArrayBufferView` and `instanceOfDataView` already read
810
+ // back. Missing here left `unknown`-held DataViews unrepresentable in a
811
+ // box, and the reverse read an `instanceof DataView` guard narrows to.
812
+ case 'data-view':
776
813
  return 'Object';
777
814
  // A `gea::Promise<T>` is a JS Object too -- `typeof new Promise(...) ===
778
815
  // 'object'` -- and `Value::box` needs nothing case-specific to hold one:
@@ -908,8 +945,107 @@ export const dynamicCarrierBoxText = (carrier, storage) => widenedStoreText({ ki
908
945
  * than fulfils with (ECMA-262 27.2.1.3.2), so the choice is made at run time
909
946
  * by `gea::detail::promiseFromDynamic` -- the store-direction recipe below.
910
947
  */
911
- export const dynamicPromiseAdoptionText = (result, text) => widenedStoreText(result, { kind: 'dynamic', reason: 'declared-any-never-narrowed' }, text);
912
- export const widenedStoreText = (held, written, text) => {
948
+ export const dynamicPromiseAdoptionText = (result, text, layouts) => {
949
+ // A settled value read as a NAMED record is rebuilt from its layout, as a
950
+ // plain `any -> T` read is (`dynamicNamedRecordText`): mongodb's
951
+ // `tryOperation` returns `operation.handleOk(result)` -- typed `any`,
952
+ // holding a Document -- from a body declared `Promise<InsertOneResult>`,
953
+ // and the layout-free load below would unbox it by identity only.
954
+ if (layouts !== undefined && result.value.kind !== 'void') {
955
+ const settledType = cppTypeOf(result.value);
956
+ const settled = dynamicNamedRecordText(layouts, { kind: 'dynamic', reason: 'declared-any-never-narrowed' }, result.value, 'gea_settled');
957
+ if (settled !== null)
958
+ return `gea::detail::promiseFromDynamic<${settledType}>(${text}, [](const gea::Value& gea_settled) { return ${settledType}(${settled}); })`;
959
+ }
960
+ return widenedStoreText(result, { kind: 'dynamic', reason: 'declared-any-never-narrowed' }, text);
961
+ };
962
+ /**
963
+ * A `Map<K, U>` stored where `ReadonlyMap<K, V>` is declared, `U` narrower
964
+ * than `V`: the SAME map, read through a view that widens each value it hands
965
+ * out (`gea::mapReadOnlyView`). Never a copy -- a copy would lose every later
966
+ * `set` on the source, which the read-only name observes in JavaScript.
967
+ *
968
+ * `null` unless the target is marked `readOnlyView`: a mutable `Map<K, V>`
969
+ * target could be written through, and a view cannot store a `V` the
970
+ * source's `U` does not admit. `null` too where the two value carriers are
971
+ * one C++ type, which needs no view -- `same-cpp-type` shares the object as
972
+ * it stands. The per-value widening is `convertedValueText`'s own answer for
973
+ * `U -> V`, so the view widens exactly as any other store of a `U` into a `V`.
974
+ */
975
+ export const readOnlyMapViewText = (source, target, text) => {
976
+ if (source.kind !== 'keyed-collection' || target.kind !== 'keyed-collection')
977
+ return null;
978
+ if (source.family !== 'map' || target.family !== 'map' || target.readOnlyView !== true)
979
+ return null;
980
+ if (source.recursive !== undefined || target.recursive !== undefined)
981
+ return null;
982
+ if (source.ownership !== 'shared-refcount' || target.ownership !== 'shared-refcount')
983
+ return null;
984
+ if (source.value === null || target.value === null)
985
+ return null;
986
+ if (representationKey(source.key) !== representationKey(target.key))
987
+ return null;
988
+ const from = cppTypeOf(source.value);
989
+ const to = cppTypeOf(target.value);
990
+ if (from === to)
991
+ return null;
992
+ const widened = tryCandidateText(() => convertedValueText(source.value, target.value, 'gea_map_value'));
993
+ if (widened === null)
994
+ return null;
995
+ return `gea::mapReadOnlyView<${to}>(${text}, [](const ${from}& gea_map_value) -> ${to} { return ${widened}; })`;
996
+ };
997
+ /** `readOnlyMapViewText` into its target's own home: the bare collection, an optional of it, or the union arm that is one. */
998
+ const readOnlyMapViewStoreText = (held, written, text) => {
999
+ if (written.kind !== 'keyed-collection')
1000
+ return null;
1001
+ if (held.kind === 'optional')
1002
+ return readOnlyMapViewStoreText(held.payload, written, text);
1003
+ if (held.kind !== 'tagged-union')
1004
+ return readOnlyMapViewText(written, held, text);
1005
+ // An arm the written map already IS, or shares a C++ type with, is its
1006
+ // home as it stands (`widenedStoreText`); a view is only for the rest.
1007
+ if (held.arms.some((arm) => cppTypeOf(arm.value) === cppTypeOf(written)))
1008
+ return null;
1009
+ for (const [armIndex, arm] of held.arms.entries()) {
1010
+ const inner = readOnlyMapViewStoreText(arm.value, written, text);
1011
+ if (inner !== null)
1012
+ return `${cppTypeOf(held)}::ofArm<${armIndex}>(${inner})`;
1013
+ }
1014
+ return null;
1015
+ };
1016
+ /**
1017
+ * A typed `Map<K, V>` stored where a union holding `Map<unknown, unknown>` --
1018
+ * and no arm of the written map's own C++ type -- is declared: the SAME map,
1019
+ * boxed and read back through `unboxDynamicMap`'s `DynamicMapSource` view.
1020
+ * bson's `serialize(object: Document)` walks such a parameter under
1021
+ * `object instanceof Map`, so a copy would be a different object and would
1022
+ * miss every later `set` (mongodb's client_metadata `LimitedSizeDocument`).
1023
+ */
1024
+ const dynamicMapArmViewStoreText = (held, written, text) => {
1025
+ if (written.kind !== 'keyed-collection' || written.family !== 'map' || written.ownership !== 'shared-refcount')
1026
+ return null;
1027
+ if (written.recursive !== undefined || written.value === null)
1028
+ return null;
1029
+ if (held.kind !== 'tagged-union')
1030
+ return null;
1031
+ if (held.arms.some((arm) => cppTypeOf(arm.value) === cppTypeOf(written)))
1032
+ return null;
1033
+ for (const [armIndex, arm] of held.arms.entries()) {
1034
+ const target = arm.value;
1035
+ if (target.kind !== 'keyed-collection' || target.family !== 'map' || target.ownership !== 'shared-refcount')
1036
+ continue;
1037
+ if (target.recursive !== undefined || target.readOnlyView === true)
1038
+ continue;
1039
+ if (target.key.kind !== 'dynamic' || target.value?.kind !== 'dynamic')
1040
+ continue;
1041
+ const view = `gea::detail::unboxDynamicMap(gea::Value::box(gea::Value::Tag::Object, ${text}), ${cppStringLiteral(assertionSite(target))})`;
1042
+ return `${cppTypeOf(held)}::ofArm<${armIndex}>(${view})`;
1043
+ }
1044
+ return null;
1045
+ };
1046
+ /** `renderedWidenedStoreText` with its source evaluated once -- see `evaluated-once.ts`. */
1047
+ export const widenedStoreText = (held, written, text) => evaluatedOnceText(text, (operand) => renderedWidenedStoreText(held, written, operand));
1048
+ const renderedWidenedStoreText = (held, written, text) => {
913
1049
  if (representationKey(held) === representationKey(written))
914
1050
  return null;
915
1051
  const remappedSet = genericFunctionSetWideningText(written, held, text);
@@ -1136,6 +1272,22 @@ export const widenedStoreText = (held, written, text) => {
1136
1272
  const index = held.arms.findIndex((arm) => representationKey(arm.value) === writtenKey);
1137
1273
  if (index >= 0)
1138
1274
  return `${cppTypeOf(held)}::ofArm<${index}>(${text})`;
1275
+ // An open Document into the ONE record arm it can be adopted as, beside a
1276
+ // `dynamic` arm: mongodb's `decorateDecryptionResult(decrypted: Document & {
1277
+ // [kDecoratedKeys]?: string[] })` takes the caller's Document and, through
1278
+ // its own recursion, any `decrypted[k]`. The record arm is the Document's
1279
+ // home -- adopted, the Document views it, so the symbol-keyed member the
1280
+ // body defines is the one a later read through the Document finds -- while
1281
+ // boxing it into the `dynamic` arm would leave that member nowhere to live.
1282
+ if (isOpenDocument(written)) {
1283
+ const adoptions = held.arms.flatMap((arm, armIndex) => {
1284
+ const fields = arm.value.kind === 'record' || arm.value.kind === 'record-with-index' ? arm.value.fields : null;
1285
+ const adopted = fields === null ? null : documentAdoptionText(written, arm.value, fields, text);
1286
+ return adopted === null ? [] : [`${cppTypeOf(held)}::ofArm<${armIndex}>(${adopted})`];
1287
+ });
1288
+ if (adoptions.length === 1)
1289
+ return adoptions[0];
1290
+ }
1139
1291
  // A join can nest: `string | number | boolean | null | undefined` derives as
1140
1292
  // an outer union over the two absence arms and an *inner* union over the
1141
1293
  // three value arms, so a written `bool` is an arm of an arm and reaches its
@@ -1172,12 +1324,16 @@ export const widenedStoreText = (held, written, text) => {
1172
1324
  discardsResultIntoVoid(written, arm.value)) {
1173
1325
  return `${cppTypeOf(held)}::ofArm<${armIndex}>(${text})`;
1174
1326
  }
1175
- if (written.kind === 'class-ref' &&
1327
+ if ((written.kind === 'class-ref' &&
1176
1328
  arm.value.kind === 'class-ref' &&
1177
1329
  written.ownership === arm.value.ownership &&
1178
- written.ancestors.includes(arm.value.declaration)) {
1330
+ written.ancestors.includes(arm.value.declaration)) ||
1331
+ nativeRecordBaseTransportKind(written, arm.value) === 'upcast') {
1179
1332
  return `${cppTypeOf(held)}::ofArm<${armIndex}>(${cppTypeOf(arm.value)}(${text}))`;
1180
1333
  }
1334
+ const view = readOnlyMapViewText(written, arm.value, text);
1335
+ if (view !== null)
1336
+ return `${cppTypeOf(held)}::ofArm<${armIndex}>(${view})`;
1181
1337
  // The fifth pair is not an implicit constructor, so it wraps the text
1182
1338
  // rather than passing it through -- see `resultAdapterOf`. hono's `H =
1183
1339
  // Handler | MiddlewareHandler` reaches its arm exactly here: same frame,
@@ -1199,7 +1355,9 @@ export const widenedStoreText = (held, written, text) => {
1199
1355
  : null
1200
1356
  : written.kind === 'dictionary' && arm.value.kind === 'dictionary'
1201
1357
  ? recastedDictionaryText(written, arm.value, text)
1202
- : null;
1358
+ : written.kind === 'record-with-index' && arm.value.kind === 'dictionary'
1359
+ ? recastedIndexedRecordToDictionaryText(written, arm.value, text)
1360
+ : null;
1203
1361
  if (recast !== null)
1204
1362
  return `${cppTypeOf(held)}::ofArm<${armIndex}>(${recast})`;
1205
1363
  }
@@ -1263,6 +1421,41 @@ export const sumIntoPayloadText = (source, payload, text, wrap) => {
1263
1421
  result = `${text}.is<${index}>() ? ${homes[index]} : (${result})`;
1264
1422
  return `(${result})`;
1265
1423
  };
1424
+ /**
1425
+ * `nodes.ts`'s `armViewFor`, rendered: a census-built sum read as the Map or
1426
+ * Array the program asserts, EACH arm converted rather than one selected by its
1427
+ * tag -- the collection as it is, another Map through the all-dynamic view of
1428
+ * the same object, a box through its checked unbox, an open Document through
1429
+ * the object it views (`documentViewedObjectText`). `null` for an arm with no
1430
+ * such read, which the printer refuses.
1431
+ */
1432
+ export const armViewText = (source, target, text) => {
1433
+ if (source.kind !== 'tagged-union')
1434
+ return null;
1435
+ const key = representationKey(target);
1436
+ const homes = [];
1437
+ for (const [index, arm] of source.arms.entries()) {
1438
+ const armText = `${text}.get<${index}>()`;
1439
+ const loaded = representationKey(arm.value) === key
1440
+ ? armText
1441
+ : arm.value.kind === 'dynamic'
1442
+ ? unboxedLoadText(target, armText)
1443
+ : isOpenDocument(arm.value)
1444
+ ? documentViewedObjectText(arm.value, target, armText)
1445
+ : arm.value.kind === 'keyed-collection' && target.kind === 'keyed-collection'
1446
+ ? unboxedLoadText(target, `gea::Value::box(gea::Value::Tag::Object, ${armText})`)
1447
+ : null;
1448
+ if (loaded === null)
1449
+ return null;
1450
+ homes.push(loaded);
1451
+ }
1452
+ let result = homes[homes.length - 1] ?? null;
1453
+ if (result === null)
1454
+ return null;
1455
+ for (let index = homes.length - 2; index >= 0; index--)
1456
+ result = `${text}.is<${index}>() ? ${homes[index]} : (${result})`;
1457
+ return `[&]() -> ${cppTypeOf(target)} { return ${result}; }()`;
1458
+ };
1266
1459
  export const recastedUnionText = (source, target, text,
1267
1460
  // A third resolver for an arm pair this module cannot answer alone. A
1268
1461
  // `native-record-ref` names a layout instead of carrying one, so the field
@@ -1562,8 +1755,10 @@ const recastableFieldValue = (from, to, seen) => {
1562
1755
  return tryCandidateText(() => dynamicCarrierBoxText(from, 'gea_probe')) !== null;
1563
1756
  // A callable field whose convention differs from the declared one's is
1564
1757
  // copied through the same adapter a direct store of it takes.
1758
+ // A convention naming a lattice-bottom carrier has no C++ type to adapt
1759
+ // through; that is a "no", not a crash of the whole conversion registry.
1565
1760
  if (from.kind === 'function-value-dispatch' && to.kind === 'function-value-dispatch')
1566
- return resultAdapterOf(from, to) !== null;
1761
+ return !containsUnresolved(from) && !containsUnresolved(to) && resultAdapterOf(from, to) !== null;
1567
1762
  // Containers copy element by element (`array-copy-recast`,
1568
1763
  // `dictionary-to-dictionary`), so a field holding one recasts when its
1569
1764
  // elements convert.
@@ -1611,6 +1806,8 @@ const recordRecastAnswers = new WeakMap();
1611
1806
  const recordsRecastableIn = (source, target, seen) => {
1612
1807
  if (source.kind !== 'record' || target.kind !== 'record')
1613
1808
  return false;
1809
+ if (standInRefuses(source, target))
1810
+ return false;
1614
1811
  if (source.accessors.length > 0 || target.accessors.length > 0)
1615
1812
  return false;
1616
1813
  if (seen !== null) {
@@ -1758,7 +1955,7 @@ const recastedRecordText = (source, target, text, depth = 0) => {
1758
1955
  return recastedRecordText(from, to, read, nestedDepth + 1);
1759
1956
  };
1760
1957
  const reads = target.fields.map((field) => {
1761
- const read = `${holder}${arrow}${cppRecordFieldName(field.key)}`;
1958
+ const read = tailAwareFieldReadText(source.fields, field.key, `${holder}${arrow}`);
1762
1959
  const match = source.fields.find((candidate) => candidate.key === field.key);
1763
1960
  // A field the target declares and the source does not: the carrier's own
1764
1961
  // absent value, which `recordsRecastable` already proved exists.
@@ -1785,16 +1982,45 @@ const recastedRecordText = (source, target, text, depth = 0) => {
1785
1982
  });
1786
1983
  if (reads.some((read) => read === null))
1787
1984
  return null;
1985
+ // Presence bits are ASSIGNED after the build, never initialized by
1986
+ // position. `records.ts` lays out one bit per field, required ones included,
1987
+ // and makes a required bit a `static` member only when the program never
1988
+ // deletes/freezes a declared field -- so a positional list that skips the
1989
+ // required bits lands each optional bit on a REQUIRED one whenever that
1990
+ // census says no. mongodb's `TimeoutContext.create` then saw
1991
+ // `'serverSelectionTimeoutMS' in options` answer false. Left alone, every
1992
+ // bit keeps its declared default (required present, optional absent).
1993
+ const target_ = target.ownership === 'shared-refcount' ? '->' : '.';
1788
1994
  const presences = target.fields.flatMap((field) => {
1789
1995
  if (field.required)
1790
1996
  return [];
1791
1997
  const match = source.fields.find((candidate) => candidate.key === field.key);
1792
1998
  if (match === undefined)
1793
- return ['false'];
1794
- return [match.required ? 'true' : `${holder}${arrow}${cppRecordFieldPresenceName(field.key)}`];
1999
+ return [];
2000
+ const present = match.required ? 'true' : `${holder}${arrow}${cppRecordFieldPresenceName(field.key)}`;
2001
+ return [`gea_recast${target_}${cppRecordFieldPresenceName(field.key)} = ${present};`];
1795
2002
  });
1796
- const structure = `${cppRecordStructName(target.shapeId)}{${[...reads, ...presences].join(', ')}}`;
1797
- const built = target.ownership === 'shared-refcount' ? `gea::makeRef<${cppRecordStructName(target.shapeId)}>(${structure})` : structure;
2003
+ // A target whose layout moved fields behind its `RecordTail` has no
2004
+ // positional form, and storing an absent field would allocate the tail for
2005
+ // nothing, so it is filled by name, present fields only.
2006
+ if (tailFieldsOf({ fields: target.fields }).size > 0) {
2007
+ const structName = cppRecordStructName(target.shapeId);
2008
+ const stores = target.fields.flatMap((field, index) => {
2009
+ const match = source.fields.find((candidate) => candidate.key === field.key);
2010
+ if (match === undefined)
2011
+ return [];
2012
+ const store = `gea_recast${target_}${tailAwareFieldWriteText(target.fields, field.key)} = ${reads[index]};`;
2013
+ if (field.required)
2014
+ return [store];
2015
+ const present = match.required ? 'true' : `${holder}${arrow}${cppRecordFieldPresenceName(field.key)}`;
2016
+ return [`if (${present}) { ${store} gea_recast${target_}${cppRecordFieldPresenceName(field.key)} = true; }`];
2017
+ });
2018
+ const declared = target.ownership === 'shared-refcount' ? `auto gea_recast = gea::makeRef<${structName}>();` : `${structName} gea_recast{};`;
2019
+ return `[](const ${cppTypeOf(source)}& ${holder}) { return ([&]() { ${declared} ${stores.join(' ')} return gea_recast; }()); }(${text})`;
2020
+ }
2021
+ const structure = `${cppRecordStructName(target.shapeId)}{${reads.join(', ')}}`;
2022
+ const allocated = target.ownership === 'shared-refcount' ? `gea::makeRef<${cppRecordStructName(target.shapeId)}>(${structure})` : structure;
2023
+ const built = presences.length === 0 ? allocated : `([&]() { auto gea_recast = ${allocated}; ${presences.join(' ')} return gea_recast; }())`;
1798
2024
  return `[](const ${cppTypeOf(source)}& ${holder}) { return ${built}; }(${text})`;
1799
2025
  };
1800
2026
  /**
@@ -1849,7 +2075,7 @@ export const recordCastableToDictionary = (source, target) => {
1849
2075
  }
1850
2076
  });
1851
2077
  };
1852
- const recastedRecordToDictionaryText = (source, target, text) => {
2078
+ const recastedRecordToDictionaryText = (source, target, text, sourceType = cppTypeOf(source), inCreationOrder = true) => {
1853
2079
  if (!recordCastableToDictionary(source, target))
1854
2080
  return null;
1855
2081
  const fieldArrow = source.ownership === 'shared-refcount' ? '->' : '.';
@@ -1864,13 +2090,102 @@ const recastedRecordToDictionaryText = (source, target, text) => {
1864
2090
  const converted = convertedValueText(field.value, target.value, read);
1865
2091
  if (converted === null)
1866
2092
  return null;
1867
- return `gea_dict${dictArrow}operator[](${key}) = ${converted};`;
2093
+ const insert = `gea_dict${dictArrow}operator[](${key}) = ${converted};`;
2094
+ // An optional field never written is no own property, and the dictionary
2095
+ // must not gain the key: a BSON document would serialize it as `null`.
2096
+ return field.required ? insert : `if (gea_from${fieldArrow}${cppRecordFieldPresenceName(field.key)}) ${insert}`;
1868
2097
  });
1869
2098
  if (inserts.some((insert) => insert === null))
1870
2099
  return null;
1871
2100
  const statements = inserts.join(' ');
1872
2101
  const construct = target.ownership === 'shared-refcount' ? `auto gea_dict = gea::makeRef<${storage}>();` : `${storage} gea_dict{};`;
1873
- return `[](const ${cppTypeOf(source)}& gea_from) { ${construct} ${statements} return gea_dict; }(${text})`;
2102
+ // A key the record gained outside its layout is one of its own keys too; the
2103
+ // dictionary takes it, in creation order, as the indexed recast below does.
2104
+ const ordered = inCreationOrder ? creationOrderedDictionaryCopyText(source, target) : '';
2105
+ return `[](const ${sourceType}& gea_from) { ${ordered}${construct} ${statements} return gea_dict; }(${text})`;
2106
+ };
2107
+ /**
2108
+ * A record with an open string index poured into an open string dictionary:
2109
+ * mongodb's `Filter<TSchema>` -- named query operators plus
2110
+ * `[key: string]: any` -- handed to a `filter: Document` parameter. The named
2111
+ * fields go in as `recastedRecordToDictionaryText` puts them, and every
2112
+ * enumerable entry of the index sidecar after them, converted into the
2113
+ * dictionary's value carrier; a non-enumerable one is not an own property a
2114
+ * copy sees. Admitted on `recordCastableToDictionary`'s terms plus one index,
2115
+ * over string keys, whose values convert too.
2116
+ */
2117
+ export const indexedRecordCastableToDictionary = (source, target) => {
2118
+ if (target.key !== 'string' || source.indexes.length !== 1)
2119
+ return false;
2120
+ const index = source.indexes[0];
2121
+ if (index.key !== 'string')
2122
+ return false;
2123
+ if (!recordCastableToDictionary({ kind: 'record', shapeId: source.shapeId, ownership: source.ownership, fields: source.fields, accessors: [] }, target))
2124
+ return false;
2125
+ return tryCandidateText(() => convertedValueText(index.value, target.value, 'gea_index_value')) !== null;
2126
+ };
2127
+ export const recastedIndexedRecordToDictionaryText = (source, target, text, sourceType = cppTypeOf(source)) => {
2128
+ if (!indexedRecordCastableToDictionary(source, target))
2129
+ return null;
2130
+ const index = source.indexes[0];
2131
+ const fieldArrow = source.ownership === 'shared-refcount' ? '->' : '.';
2132
+ const dictArrow = target.ownership === 'shared-refcount' ? '->' : '.';
2133
+ const named = recastedRecordToDictionaryText({ kind: 'record', shapeId: source.shapeId, ownership: source.ownership, fields: source.fields, accessors: [] }, target, 'gea_from', sourceType, false);
2134
+ const entry = convertedValueText(index.value, target.value, `gea_from${fieldArrow}${cppRecordIndexSidecarName}.read(gea_key)`);
2135
+ if (named === null || entry === null)
2136
+ return null;
2137
+ return (`[](const ${sourceType}& gea_from) { ${creationOrderedDictionaryCopyText(source, target)}auto gea_dict = ${named}; ` +
2138
+ `for (const std::string& gea_key : gea_from${fieldArrow}${cppRecordIndexSidecarName}.enumerableKeys()) gea_dict${dictArrow}operator[](gea_key) = ${entry}; ` +
2139
+ `return gea_dict; }(${text})`);
2140
+ };
2141
+ /**
2142
+ * The recast above in the source's creation order, as a statement returning
2143
+ * the dictionary, or nothing when the copy cannot take that path.
2144
+ *
2145
+ * The static copy lists the named fields before the index entries, which is
2146
+ * the record's own order only until it has a key outside its layout -- a
2147
+ * command document gains its options that way, and a BSON command's first key
2148
+ * has to stay the command's name. The runtime then knows the order
2149
+ * (`gea::copyOwnPropertiesInCreationOrder`); each value it hands over is a
2150
+ * property read through the record's own protocol, converted into the
2151
+ * dictionary's carrier.
2152
+ */
2153
+ const creationOrderedDictionaryCopyText = (source, target) => {
2154
+ if (source.ownership !== 'shared-refcount' || target.key !== 'string')
2155
+ return '';
2156
+ const converted = tryCandidateText(() => convertedValueText({ kind: 'dynamic', reason: 'declared-any-never-narrowed' }, target.value, 'gea_value'));
2157
+ if (converted === null)
2158
+ return '';
2159
+ const storage = `gea::Dictionary<${cppTypeOf(target.value)}>`;
2160
+ const shared = target.ownership === 'shared-refcount';
2161
+ const construct = shared ? `auto gea_ordered = gea::makeRef<${storage}>();` : `${storage} gea_ordered{};`;
2162
+ return (`{ ${construct} if (gea::copyOwnPropertiesInCreationOrder(gea_from, [&](const std::string& gea_key, const gea::Value& gea_value) { ` +
2163
+ `gea_ordered${shared ? '->' : '.'}operator[](gea_key) = ${converted}; })) return gea_ordered; } `);
2164
+ };
2165
+ /**
2166
+ * The indexed record a carrier holds: itself, or the layout a named interface
2167
+ * resolves to when that layout declares an index -- mongodb's `WithoutId<TSchema>`
2168
+ * is a name. A named layout with NO index is the plain record recast's.
2169
+ */
2170
+ export const indexedRecordViewOf = (source, layouts) => {
2171
+ if (source.kind === 'record-with-index')
2172
+ return source;
2173
+ if (source.kind !== 'native-record-ref' || source.native !== null || source.recursive)
2174
+ return null;
2175
+ const fields = layouts.forShape(source.shapeId);
2176
+ const indexes = layouts.indexesForShape?.(source.shapeId) ?? [];
2177
+ if (fields === null || indexes.length === 0)
2178
+ return null;
2179
+ return { kind: 'record-with-index', shapeId: source.shapeId, fields, indexes, ownership: source.ownership };
2180
+ };
2181
+ export const INDEXED_RECORD_TO_DICTIONARY = 'gea::record::recastIndexedToDictionary';
2182
+ export const INDEXED_RECORD_INTO_DICTIONARY_ARM = 'gea::TaggedUnion::ofIndexedRecordArm';
2183
+ /** The ONE dictionary arm of `target` an indexed record pours into, or null when there is none or more than one. */
2184
+ export const indexedRecordDictionaryArmOf = (source, target) => {
2185
+ if (target.kind !== 'tagged-union')
2186
+ return null;
2187
+ const homes = target.arms.flatMap((arm, index) => arm.value.kind === 'dictionary' && indexedRecordCastableToDictionary(source, arm.value) ? [index] : []);
2188
+ return homes.length === 1 ? homes[0] : null;
1874
2189
  };
1875
2190
  /**
1876
2191
  * An open dictionary recast into another open dictionary over the same key
@@ -1901,7 +2216,12 @@ const recastedRecordToDictionaryText = (source, target, text) => {
1901
2216
  * them; a pair over either refuses by name rather than guessing a spelling.
1902
2217
  */
1903
2218
  export const dictionaryCastableToDictionary = (source, target) => {
1904
- if (source.key !== 'string' || target.key !== 'string')
2219
+ // A number-keyed table is the same store under canonical numeric keys
2220
+ // (`gea::NumericDictionary`), so it recasts into another number-keyed one
2221
+ // exactly as a string-keyed table does: mongodb's `insertMany` returns the
2222
+ // bulk result's `{ [key: number]: any }` id map as `InsertManyResult`'s
2223
+ // `{ [key: number]: InferIdType<TSchema> }`.
2224
+ if (source.key !== target.key || (source.key !== 'string' && source.key !== 'number'))
1905
2225
  return false;
1906
2226
  if (representationKey(source.value) === representationKey(target.value))
1907
2227
  return false;
@@ -1919,21 +2239,181 @@ export const dictionaryCastableToDictionary = (source, target) => {
1919
2239
  throw error;
1920
2240
  }
1921
2241
  };
2242
+ /**
2243
+ * A class instance handed where an open `{ [key: string]: any }` document is
2244
+ * declared, as a live VIEW of the instance (`gea::dictionary::aliasOf`): the
2245
+ * same object, read and written through its own property protocol.
2246
+ *
2247
+ * Not a copy. mongodb's `RenameOperation.handleOk(): Document` returns a
2248
+ * `Collection` its caller goes on to use as the collection, and
2249
+ * `ClientBulkWriteResultsMerger` reads `document.insertedCount` -- a
2250
+ * PROTOTYPE getter -- off a response class. A table of the instance's own
2251
+ * fields answers neither, and loses every write made through either name
2252
+ * afterwards; the view answers all of it because it is the object. Only the
2253
+ * one dictionary whose values are already `any` can view: every value read
2254
+ * through it is dynamic anyway, so viewing boxes nothing the program typed,
2255
+ * and the instance keeps its own native carrier everywhere else.
2256
+ */
2257
+ /**
2258
+ * Whether an open `any` Document can view `source` as the very object it is.
2259
+ * A union of such objects is viewable too -- mongodb's `{ message; code } |
2260
+ * WriteConcernError | AnyError` into `ErrorDescription` -- because its box
2261
+ * names whichever arm is live; so is the intrinsic Error.
2262
+ */
2263
+ export const documentViewable = (source) => {
2264
+ if (source.kind === 'tagged-union')
2265
+ return source.arms.every((arm) => isOpenDocument(arm.value) || documentViewable(arm.value));
2266
+ const viewable = source.kind === 'class-ref' ||
2267
+ source.kind === 'record' ||
2268
+ source.kind === 'record-with-index' ||
2269
+ (source.kind === 'native-record-ref' && !source.recursive) ||
2270
+ // An Array or a Map is an object as well: bson's serializer and
2271
+ // `calculate_size.ts` hold every nested value -- plain, array or Map -- in
2272
+ // one `Document` frame field, then walk it by what it turned out to be.
2273
+ source.kind === 'array-object' ||
2274
+ (source.kind === 'keyed-collection' && source.family === 'map');
2275
+ return viewable && source.ownership === 'shared-refcount';
2276
+ };
2277
+ export const classDocumentViewText = (source, target, text) => {
2278
+ // A shared record a copy could not be made of views the same way: mongodb's
2279
+ // `session.clusterTime` (`ClusterTime`) handed to a `Document | null` slot.
2280
+ // A record a Document adopted (`gea::dictionary::adopt`) is that Document.
2281
+ if (!isOpenDocument(target) || !documentViewable(source))
2282
+ return null;
2283
+ const boxed = dynamicCarrierBoxText(source, text);
2284
+ return boxed === null ? null : `gea::dictionary::aliasOf(${boxed})`;
2285
+ };
2286
+ /**
2287
+ * An open `any` Document read as a shared typed record: the record the
2288
+ * Document's entries are checked into, after which the Document views it
2289
+ * (`gea::dictionary::adopt`). A copy would give one JavaScript object two
2290
+ * identities -- a write through the typed name would never reach the Document.
2291
+ * A required symbol-keyed field cannot be in a string-keyed Document, so it
2292
+ * refuses here rather than at run time.
2293
+ */
2294
+ export const documentAdoptionText = (source, target, fields, text) => {
2295
+ if (!isOpenDocument(source))
2296
+ return null;
2297
+ if (target.kind !== 'record' && target.kind !== 'record-with-index' && target.kind !== 'native-record-ref')
2298
+ return null;
2299
+ if (target.ownership !== 'shared-refcount')
2300
+ return null;
2301
+ if (fields.some((field) => field.required && cppRecordFieldKeyIsSymbol(field.key)))
2302
+ return null;
2303
+ const keys = (required) => fields
2304
+ .filter((field) => field.required === required && !cppRecordFieldKeyIsSymbol(field.key))
2305
+ .map((field) => cppStringLiteral(field.key))
2306
+ .join(', ');
2307
+ return (`gea::dictionary::adopt<${cppRecordStructName(target.shapeId)}>(` +
2308
+ `${text}, {${keys(true)}}, {${keys(false)}}, ${cppStringLiteral(assertionSite(target))})`);
2309
+ };
2310
+ /**
2311
+ * An open `any` Document read as a class instance or a byte view: only the
2312
+ * object the Document views (`gea::dictionary::aliasOf`) can be one, so the
2313
+ * read is that object's checked unbox, and a Document holding its own entries
2314
+ * refuses. mongodb reaches it under `Buffer.isBuffer(options.schemaMap)`.
2315
+ */
2316
+ const documentViewedObjectText = (source, target, text) => {
2317
+ // `options.schemaMap?: Document` is optional; the guard that narrows it to a
2318
+ // Buffer has already proved it present, and an absent one refuses like any
2319
+ // other value that is not a Buffer.
2320
+ const optional = source.kind === 'optional' && isOpenDocument(source.payload);
2321
+ if (!optional && !isOpenDocument(source))
2322
+ return null;
2323
+ // bson reads a frame's `Document` back `as unknown[]` under
2324
+ // `Array.isArray`, and `as Map<string, unknown>` under `instanceof Map`.
2325
+ const viewable = target.kind === 'typed-array' ||
2326
+ target.kind === 'class-ref' ||
2327
+ target.kind === 'array-object' ||
2328
+ (target.kind === 'keyed-collection' && target.family === 'map');
2329
+ if (!viewable)
2330
+ return null;
2331
+ const viewed = 'gea_viewed';
2332
+ const load = unboxedLoadText(target, viewed);
2333
+ if (load === null)
2334
+ return null;
2335
+ const object = optional
2336
+ ? `gea_document.has_value() ? gea::dictionary::aliasedObject(*gea_document) : gea::Value()`
2337
+ : 'gea::dictionary::aliasedObject(gea_document)';
2338
+ return (`[](const ${cppTypeOf(source)}& gea_document) -> ${cppTypeOf(target)} { ` +
2339
+ `const gea::Value ${viewed} = ${object}; return ${load}; }(${text})`);
2340
+ };
1922
2341
  const dictionaryToRecordText = (source, target, text) => {
1923
2342
  if (source.kind !== 'dictionary' || source.key !== 'string' || source.value.kind !== 'dynamic' || source.ownership !== 'shared-refcount')
1924
2343
  return null;
2344
+ if (target.kind === 'record-with-index')
2345
+ return documentAdoptionText(source, target, target.fields, text);
1925
2346
  if (target.kind !== 'record' || target.accessors.length !== 0 || target.ownership === 'borrowed')
1926
2347
  return null;
2348
+ if (target.ownership === 'shared-refcount')
2349
+ return documentAdoptionText(source, target, target.fields, text);
1927
2350
  const boxed = dynamicCarrierBoxText(source, text);
1928
2351
  return boxed === null ? null : unboxedLoadText(target, boxed);
1929
2352
  };
2353
+ export const DYNAMIC_DICTIONARY_TO_NAMED_RECORD = 'gea::record::fromDynamicDictionary';
2354
+ export const CONSTRUCTOR_STATIC_VIEW = 'gea::constructorStaticView';
2355
+ /**
2356
+ * Whether a class's constructor object can be viewed as a record shape: the
2357
+ * view is the constructor's own properties for that shape
2358
+ * (`gea::constructorStaticView`), so every field must be one a constructor
2359
+ * may not have -- optional -- and the shape must be a plain shared record
2360
+ * whose identity the view can be.
2361
+ */
2362
+ export const constructorStaticViewAdmitted = (source, target, fields) => {
2363
+ if (source.kind !== 'constructor-family' && source.kind !== 'constructor-identity')
2364
+ return false;
2365
+ if (source.kind === 'constructor-family' && source.members.some((member) => member.includes('@')))
2366
+ return false;
2367
+ if (target.kind === 'record') {
2368
+ if (target.ownership !== 'shared-refcount' || target.accessors.length !== 0)
2369
+ return false;
2370
+ return target.fields.every((field) => !field.required);
2371
+ }
2372
+ if (target.kind !== 'native-record-ref' || target.native !== null || target.recursive || target.ownership !== 'shared-refcount')
2373
+ return false;
2374
+ return fields !== null && fields.every((field) => !field.required);
2375
+ };
2376
+ /** The class evaluation a constructor carrier names, then its own view as `target`'s struct. */
2377
+ export const constructorStaticViewText = (source, target, text) => {
2378
+ if (target.kind !== 'record' && target.kind !== 'native-record-ref')
2379
+ return null;
2380
+ const state = source.kind === 'constructor-identity'
2381
+ ? `(${text}).get()`
2382
+ : source.kind === 'constructor-family'
2383
+ ? `static_cast<gea::NativeClassMethodState*>((${text}).environment)`
2384
+ : null;
2385
+ if (state === null)
2386
+ return null;
2387
+ return `gea::constructorStaticView<${cppRecordStructName(target.shapeId)}>(${state})`;
2388
+ };
2389
+ /**
2390
+ * Whether an open `{ [key: string]: any }` document rebuilds as a named
2391
+ * interface's native record: every field has a checked unbox out of a
2392
+ * `gea::Value`, and every index the layout declares is a string index of
2393
+ * `any` the leftover keys can go into unchanged.
2394
+ */
2395
+ export const dynamicDictionaryToNamedRecordAdmitted = (source, target, fields, indexes) => {
2396
+ if (source.kind !== 'dictionary' || source.key !== 'string' || source.value.kind !== 'dynamic' || source.ownership !== 'shared-refcount')
2397
+ return false;
2398
+ if (target.kind !== 'native-record-ref' || target.native !== null || target.recursive || target.ownership !== 'shared-refcount')
2399
+ return false;
2400
+ if (fields === null || indexes.length > 1)
2401
+ return false;
2402
+ if (indexes.some((index) => index.key !== 'string' || index.value.kind !== 'dynamic'))
2403
+ return false;
2404
+ // A probe, so a field whose carrier never resolved answers `false` here
2405
+ // (see `containsUnresolved`) instead of throwing out of `cppTypeOf`.
2406
+ return fields.every((field) => field.value.kind === 'dynamic' ||
2407
+ (!containsUnresolved(field.value) &&
2408
+ withoutUnitFunctions(() => tryCandidateText(() => unboxedLoadText(field.value, 'gea_value'))) !== null));
2409
+ };
1930
2410
  const recastedDictionaryText = (source, target, text) => {
1931
2411
  if (!dictionaryCastableToDictionary(source, target))
1932
2412
  return null;
1933
2413
  const converted = convertedValueText(source.value, target.value, 'gea_entry.second');
1934
2414
  if (converted === null)
1935
2415
  return null;
1936
- const storage = `gea::Dictionary<${cppTypeOf(target.value)}>`;
2416
+ const storage = `gea::${target.key === 'number' ? 'NumericDictionary' : 'Dictionary'}<${cppTypeOf(target.value)}>`;
1937
2417
  const construct = target.ownership === 'shared-refcount' ? `auto gea_dict = gea::makeRef<${storage}>();` : `${storage} gea_dict{};`;
1938
2418
  const dictArrow = target.ownership === 'shared-refcount' ? '->' : '.';
1939
2419
  // `gea::Dictionary`'s own `const_iterator` walks entries in creation order,
@@ -2100,11 +2580,44 @@ export const boxedAssertionText = (source, target, text) => {
2100
2580
  const union = target.kind === 'optional' ? target.payload : target;
2101
2581
  if (!objectLike(source) || union.kind !== 'tagged-union')
2102
2582
  return null;
2583
+ if (!boxLandsInAnArm(source, union))
2584
+ return null;
2103
2585
  const boxed = dynamicCarrierBoxText(source, text);
2104
2586
  if (boxed === null)
2105
2587
  return null;
2106
2588
  return tryCandidateText(() => convertedValueText({ kind: 'dynamic', reason: 'declared-any-never-narrowed' }, target, boxed));
2107
2589
  };
2590
+ /**
2591
+ * Whether the box `boxedAssertionText` makes of `source` can pass the
2592
+ * dispatch `unboxedLoadText` runs over `union`: the union has a dynamic
2593
+ * remainder arm, or some arm's own discriminant matches what boxing `source`
2594
+ * records -- the same tag and C++ payload type, or, for a class arm, a class
2595
+ * allocation whose family the run-time identity check may find it in (a
2596
+ * downcast the program asserted).
2597
+ *
2598
+ * Anything else is a box no arm reads back: the dispatch's final
2599
+ * `refusePayloadMismatch` is the only path it has, so every value, however
2600
+ * well it satisfies the union's TypeScript type, aborts at run time. mongodb's
2601
+ * named `[key: string]: any` interface handed to `Document | Document[]` was
2602
+ * the measured case, before its own recast existed. Refusing here turns that
2603
+ * certain abort into the missing-conversion row certify names.
2604
+ */
2605
+ const boxLandsInAnArm = (source, union) => {
2606
+ if (union.arms.some((arm) => arm.value.kind === 'dynamic' && arm.value.reason !== 'untyped-callable'))
2607
+ return true;
2608
+ const boxed = boxDiscriminantsOf(source);
2609
+ if (boxed === null)
2610
+ return false;
2611
+ const payload = cppTypeOf(source);
2612
+ const admits = (accept, box) => {
2613
+ if (accept.callableMembers !== null || accept.tag !== box.tag)
2614
+ return false;
2615
+ if (accept.nominal !== null)
2616
+ return box.nominal !== null;
2617
+ return accept.payload === null || accept.payload === payload;
2618
+ };
2619
+ return union.arms.some((arm) => boxDiscriminantsOfArm(arm)?.some((accept) => boxed.some((box) => admits(accept, box))) === true);
2620
+ };
2108
2621
  /** The slot parameters from `first` on, packed into the source's rest Array -- see `restPack` in `resultAdapterOf`. */
2109
2622
  const restPackedActual = (slots, first, element) => {
2110
2623
  const elementType = cppTypeOf(element);
@@ -2201,7 +2714,7 @@ const recastUnionAliasName = 'GeaRecastArm';
2201
2714
  * - A pair whose parameters and result already share C++ spellings. It needs
2202
2715
  * no adapter and must not get one, or an identity store would allocate.
2203
2716
  */
2204
- const resultAdapterOf = (source, target) => {
2717
+ const resultAdapterOf = (source, target, viaView) => {
2205
2718
  const from = callableObjectAbi(source);
2206
2719
  const to = callableObjectAbi(target);
2207
2720
  if (!from || !to)
@@ -2271,9 +2784,13 @@ const resultAdapterOf = (source, target) => {
2271
2784
  }
2272
2785
  let receiverActual = null;
2273
2786
  if (from.receiver !== null && to.receiver !== null) {
2787
+ const narrowedReceiver = receiverDowncastText(to.receiver, from.receiver, adapterReceiverName);
2274
2788
  if (cppTypeOf(from.receiver) === cppTypeOf(to.receiver)) {
2275
2789
  receiverActual = adapterReceiverName;
2276
2790
  }
2791
+ else if (narrowedReceiver !== null) {
2792
+ receiverActual = narrowedReceiver;
2793
+ }
2277
2794
  else {
2278
2795
  try {
2279
2796
  receiverActual = convertedValueText(to.receiver, from.receiver, adapterReceiverName);
@@ -2317,39 +2834,57 @@ const resultAdapterOf = (source, target) => {
2317
2834
  actuals.push(formal);
2318
2835
  continue;
2319
2836
  }
2837
+ let converted;
2320
2838
  try {
2321
- const converted = convertedValueText(slot.value, parameter.value, formal);
2322
- if (converted === null)
2323
- return null;
2324
- actuals.push(converted);
2839
+ converted = convertedValueText(slot.value, parameter.value, formal);
2325
2840
  }
2326
2841
  catch (error) {
2327
- if (isCppEmitBlockedError(error))
2328
- return null;
2329
- throw error;
2842
+ if (!isCppEmitBlockedError(error))
2843
+ throw error;
2844
+ converted = null;
2330
2845
  }
2846
+ converted ??= viaView?.(slot.value, parameter.value, formal) ?? null;
2847
+ if (converted === null)
2848
+ return null;
2849
+ actuals.push(converted);
2331
2850
  }
2332
2851
  let convertedResult;
2333
2852
  if (to.result.kind === 'void') {
2334
2853
  convertedResult = null;
2335
2854
  }
2336
2855
  else if (from.result.kind === 'void') {
2337
- if (to.result.kind !== 'dynamic')
2856
+ // A body that completes without a value returns `undefined`, so a slot
2857
+ // whose result can hold `undefined` (`PromiseLike.then`'s
2858
+ // `TResult | PromiseLike<TResult>` at `TResult = void`) receives exactly
2859
+ // that; a slot that cannot is a genuine mismatch.
2860
+ convertedResult = cppUndefinedIn(to.result);
2861
+ if (convertedResult === null)
2338
2862
  return null;
2339
- convertedResult = `${cppTypeOf(to.result)}()`;
2340
2863
  }
2341
2864
  else if (cppTypeOf(from.result) === cppTypeOf(to.result)) {
2342
2865
  convertedResult = adapterResultName;
2343
2866
  }
2867
+ else if (from.overloadJoined === true &&
2868
+ from.result.kind === 'optional' &&
2869
+ to.result.kind !== 'optional' &&
2870
+ cppTypeOf(from.result.payload) === cppTypeOf(to.result)) {
2871
+ // A call naming one overload of a callback-joined set
2872
+ // (`host-abi.ts`'s `callbackOverloadJoinedAbi`): that overload answers
2873
+ // the value, so the joined frame's `undefined` is the OTHER overload's
2874
+ // answer -- the callee broke its own declaration, a TypeError, never a
2875
+ // default-constructed payload.
2876
+ convertedResult = `(*gea::host::presentOrThrow(${adapterResultName}))`;
2877
+ }
2344
2878
  else {
2345
2879
  try {
2346
2880
  convertedResult = convertedValueText(from.result, to.result, adapterResultName);
2347
2881
  }
2348
2882
  catch (error) {
2349
- if (isCppEmitBlockedError(error))
2350
- return null;
2351
- throw error;
2883
+ if (!isCppEmitBlockedError(error))
2884
+ throw error;
2885
+ convertedResult = null;
2352
2886
  }
2887
+ convertedResult ??= assertedResultNarrowingText(from.result, to.result, adapterResultName);
2353
2888
  if (convertedResult === null)
2354
2889
  return null;
2355
2890
  }
@@ -2358,7 +2893,13 @@ const resultAdapterOf = (source, target) => {
2358
2893
  const ignoresParameters = from.parameters.length < to.parameters.length;
2359
2894
  const parametersChange = actuals.some((actual, ordinal) => actual !== adapterFormalName(ordinal));
2360
2895
  const resultChanges = from.result.kind !== to.result.kind || (from.result.kind !== 'void' && cppTypeOf(from.result) !== cppTypeOf(to.result));
2361
- const nativeFieldProtocolUnused = !restSpread &&
2896
+ // A source whose fixed frame ends before the slot's rest reads no element
2897
+ // of that Array: nothing is unboxed and the Array itself is never passed.
2898
+ // mongodb hands `() => new Topology(...)`-shaped thunks to `(...args: any[])
2899
+ // => void` slots; counting that as a spread made the census publish the
2900
+ // thunk's result class, and everything it reaches, to full reflection.
2901
+ const spreadsRest = restSpread && to.restFrom !== null && from.parameters.length > to.restFrom;
2902
+ const nativeFieldProtocolUnused = !spreadsRest &&
2362
2903
  !restPack &&
2363
2904
  (!receiverChanges || nativeReceiverTransport) &&
2364
2905
  !parametersChange &&
@@ -2367,6 +2908,76 @@ const resultAdapterOf = (source, target) => {
2367
2908
  ? { from, to, receiverActual, actuals, convertedResult, nativeFieldProtocolUnused }
2368
2909
  : null;
2369
2910
  };
2911
+ /**
2912
+ * A callable's result read into a slot whose result union is NARROWER -- arms
2913
+ * of the source's result the slot does not declare.
2914
+ *
2915
+ * The checker admits a callable into such a slot only through an assertion:
2916
+ * a function's result must be assignable to its slot's, so the pair exists
2917
+ * because the program wrote `f as (...) => Narrower`. hono's `utils/url.ts`
2918
+ * is the measured case -- `_getQueryParam`'s `string | undefined |
2919
+ * Record<string, string> | string[] | Record<string, string[]>` asserted to
2920
+ * `string | undefined | Record<string, string>`, the two array arms reachable
2921
+ * only through the third parameter the slot omits. The assertion is checked
2922
+ * per call, the same `CHECKED_ARM_NARROWING` a union read into a slot homing
2923
+ * only some of its arms takes: each declared arm converts, and an undeclared
2924
+ * one is a `TypeError`, never read as another. An optional layer on both
2925
+ * sides passes its absence through.
2926
+ */
2927
+ const assertedResultNarrowingText = (from, to, text) => {
2928
+ if (from.kind === 'tagged-union' && to.kind === 'tagged-union')
2929
+ return checkedArmNarrowingText(from, to, text);
2930
+ if (from.kind !== 'optional' || to.kind !== 'optional' || from.absence !== to.absence)
2931
+ return null;
2932
+ if (from.payload.kind !== 'tagged-union' || to.payload.kind !== 'tagged-union')
2933
+ return null;
2934
+ const targetType = cppTypeOf(to);
2935
+ const present = checkedArmNarrowingText(from.payload, to.payload, '(*gea_adapt_present)');
2936
+ if (present === null)
2937
+ return null;
2938
+ return (`([&](const ${cppTypeOf(from)}& gea_adapt_present) -> ${targetType} { ` +
2939
+ `if (!gea_adapt_present.has_value()) return ${targetType}(); return ${targetType}(${present}); }(${text}))`);
2940
+ };
2941
+ /**
2942
+ * A callable whose `this` is a descendant class (or the copies of a split
2943
+ * generic class, `derive.ts`'s `anyCopyFamilyOf`) filling a slot whose
2944
+ * receiver is an ancestor: node's `EventEmitter` calls every listener with
2945
+ * `fn.apply(this, args)`, and the MongoDB driver registers `function
2946
+ * removeActiveCursor(this: AbstractCursor)` on its own cursors. The function
2947
+ * only ever runs against the object that emitted, so the receiver narrows to
2948
+ * the arm whose class the allocation extends -- most specific arm first, read
2949
+ * off the allocation's own `classBase` chain, which is emitted only from
2950
+ * checker-proven bases. A receiver no arm claims is a TypeError, never a
2951
+ * reinterpretation: TypeScript accepted the pair only through a `this`-free
2952
+ * signature, so nothing proved the call's receiver fits.
2953
+ */
2954
+ const receiverDowncastText = (held, wanted, text) => {
2955
+ if (held.kind !== 'class-ref')
2956
+ return null;
2957
+ const arms = wanted.kind === 'class-ref'
2958
+ ? [{ arm: wanted, index: -1 }]
2959
+ : wanted.kind === 'tagged-union' && wanted.arms.every((arm) => arm.value.kind === 'class-ref')
2960
+ ? wanted.arms.map((arm, index) => ({ arm: arm.value, index }))
2961
+ : null;
2962
+ if (arms === null || arms.length === 0)
2963
+ return null;
2964
+ if (!arms.every(({ arm }) => arm.ownership === held.ownership && arm.ancestors.includes(held.declaration)))
2965
+ return null;
2966
+ const ordered = [...arms].sort((left, right) => {
2967
+ const leftBelow = left.arm.ancestors.includes(right.arm.declaration);
2968
+ const rightBelow = right.arm.ancestors.includes(left.arm.declaration);
2969
+ return leftBelow === rightBelow ? left.index - right.index : leftBelow ? -1 : 1;
2970
+ });
2971
+ const wantedType = cppTypeOf(wanted);
2972
+ const identity = `gea::detail::refPayloadIdentity(${text})`;
2973
+ const branches = ordered.map(({ arm, index }) => {
2974
+ const narrowed = `gea::host::downcastClassRef<${cppClassName(arm.declaration)}>(${text})`;
2975
+ const value = index < 0 ? narrowed : `${wantedType}::ofArm<${index}>(${narrowed})`;
2976
+ return `if (gea::detail::classIdentityExtends(${identity}, &gea::detail::RefOperationsFor<${cppClassName(arm.declaration)}>::table)) return ${value};`;
2977
+ });
2978
+ return (`[&]() -> ${wantedType} { ${branches.join(' ')} ` +
2979
+ `gea::host::throwRuntimeError("TypeError", "a function was called with a receiver its this parameter does not accept"); }()`);
2980
+ };
2370
2981
  /** Whether `source` reaches `target` through a result adapter -- see `resultAdapterOf`. Exported so `conversions.ts` asks the identical question the render below answers. */
2371
2982
  export const adaptsResultIntoTarget = (source, target) => resultAdapterOf(source, target) !== null;
2372
2983
  /** The same adapter selection used by the printer publishes its transport facts to the conversion census. */
@@ -2374,9 +2985,94 @@ export const resultAdapterTransportOf = (source, target) => {
2374
2985
  const adapter = resultAdapterOf(source, target);
2375
2986
  return adapter === null ? null : { nativeConventions: adapter.nativeFieldProtocolUnused ? { from: adapter.from, to: adapter.to } : null };
2376
2987
  };
2377
- /** The adapter itself, or `null` for a pair that needs none -- see `resultAdapterOf`. */
2378
- export const resultAdaptedCallableText = (source, target, text) => {
2379
- const adapter = resultAdapterOf(source, target);
2988
+ /**
2989
+ * The materializer id of a callable adapter one of whose PARAMETERS converts
2990
+ * only through a structural view: bson's `ByteUtils.toLocalBufferType` slot
2991
+ * `(Uint8Array | ArrayBufferView | ArrayBuffer) => Uint8Array` holding the web
2992
+ * implementation declared over `Uint8Array | (ArrayBufferView & { [Symbol.toStringTag]?: string })
2993
+ * | ArrayBuffer`. The slot's `ArrayBufferView` arm is a `native-record-ref`
2994
+ * reaching the method's intersection record by a record view; the chain's
2995
+ * adapter has no layouts and could only select the arms the two share.
2996
+ */
2997
+ export const VIEW_ADAPTED_CALLABLE = 'view:adapted-callable';
2998
+ /**
2999
+ * A union read into a slot some of whose arms it homes and some of which it
3000
+ * does not, where no view homes them all -- the census's last recipe before
3001
+ * the boxed assertion (`conversions.ts`'s `staticRecipe`). The homed arms
3002
+ * convert as the chain's narrowing converts them; each unhomed arm is a
3003
+ * checked `TypeError` (`gea::host::unhomedUnionArm`), never read as another.
3004
+ * The chain's own narrowing refuses the pair instead (`partialWidening`), so
3005
+ * a whole-sum view is still asked first.
3006
+ */
3007
+ export const CHECKED_ARM_NARROWING = 'view:checked-arm-narrowing';
3008
+ /**
3009
+ * An `Array<any>` arm (`unknown[]`, `any[]`) the program asserts to an array
3010
+ * of a typed element, rebuilt element-wise: each element is admitted by its own
3011
+ * check (a `TypeError` for one that cannot be the element) and then unboxed.
3012
+ * The result is a fresh array -- the typed carrier cannot alias storage whose
3013
+ * elements are boxes. `null` for any other pair, and for an element with no
3014
+ * checked unbox.
3015
+ */
3016
+ const dynamicArrayRebuildText = (arm, target, text) => {
3017
+ if (arm.kind !== 'array-object' || target.kind !== 'array-object')
3018
+ return null;
3019
+ if (arm.ownership !== 'shared-refcount' || target.ownership !== 'shared-refcount')
3020
+ return null;
3021
+ if (arm.extension !== null || target.extension !== null)
3022
+ return null;
3023
+ if (arm.element.kind !== 'dynamic' || arm.element.reason === 'untyped-callable' || target.element.kind === 'dynamic')
3024
+ return null;
3025
+ const element = 'gea_element';
3026
+ const load = unboxedLoadText(target.element, element);
3027
+ if (load === null)
3028
+ return null;
3029
+ const admission = target.element.kind === 'class-ref' && target.element.ownership === 'shared-refcount'
3030
+ ? `gea::host::boxedClassRefAdmits<${cppClassName(target.element.declaration)}>(${element})`
3031
+ : dynamicFieldAdmissionText(target.element, element);
3032
+ const body = (admission === null
3033
+ ? ''
3034
+ : `if (!(${admission})) gea::host::throwRuntimeError("TypeError", "an array element cannot be the element type the array is asserted to"); `) +
3035
+ `return ${load};`;
3036
+ return `gea::host::rebuildDynamicArray<${cppTypeOf(target.element)}>(${text}, [](const gea::Value& ${element}) -> ${cppTypeOf(target.element)} { ${body} })`;
3037
+ };
3038
+ /**
3039
+ * `nodes.ts`'s `assertedUnionFor`, rendered: the live arm is dispatched on, never
3040
+ * assumed. An arm with a conversion into the target converts; an `Array<any>`
3041
+ * arm is rebuilt element-wise (`dynamicArrayRebuildText`) only where
3042
+ * `copyAllowed`, since the rebuild is a copy; an arm that cannot be the target
3043
+ * (or may not be copied) is a `TypeError` (`gea::host::unhomedUnionArm`). `null` when no arm
3044
+ * can be the target at all, which the printer refuses.
3045
+ */
3046
+ export const assertedUnionText = (source, target, text, copyAllowed) => {
3047
+ if (source.kind !== 'tagged-union')
3048
+ return null;
3049
+ const targetKey = representationKey(target);
3050
+ return tryCandidateText(() => evaluatedOnceText(text, (operand) => {
3051
+ const homes = source.arms.map((arm, index) => {
3052
+ const slot = `${operand}.get<${index}>()`;
3053
+ if (representationKey(arm.value) === targetKey)
3054
+ return slot;
3055
+ return (tryCandidateText(() => convertedValueText(arm.value, target, slot) ?? narrowedLoadText(arm.value, target, slot)) ??
3056
+ (copyAllowed ? dynamicArrayRebuildText(arm.value, target, slot) : null));
3057
+ });
3058
+ if (homes.every((home) => home === null))
3059
+ return null;
3060
+ let result = `gea::host::unhomedUnionArm<${cppTypeOf(target)}>(${operand}.index())`;
3061
+ for (let index = homes.length - 1; index >= 0; index -= 1) {
3062
+ const home = homes[index];
3063
+ if (home !== null && home !== undefined)
3064
+ result = `${operand}.is<${index}>() ? ${home} : (${result})`;
3065
+ }
3066
+ return `(${result})`;
3067
+ }));
3068
+ };
3069
+ export const checkedArmNarrowingText = (source, target, text) => {
3070
+ if (source.kind !== 'tagged-union' || target.kind !== 'tagged-union')
3071
+ return null;
3072
+ return tryCandidateText(() => evaluatedOnceText(text, (operand) => taggedUnionArmText(source, target, operand, 'throw')));
3073
+ };
3074
+ export const resultAdaptedCallableText = (source, target, text, viaView, knownFunction) => {
3075
+ const adapter = resultAdapterOf(source, target, viaView);
2380
3076
  if (adapter === null)
2381
3077
  return null;
2382
3078
  const sourceType = cppTypeOf(source);
@@ -2386,14 +3082,110 @@ export const resultAdaptedCallableText = (source, target, text) => {
2386
3082
  ...adapter.to.parameters.map((parameter, ordinal) => `${cppAbiParameterType(parameter)} ${adapterFormalName(ordinal)}`)
2387
3083
  ];
2388
3084
  const sourceActuals = [...(adapter.receiverActual === null ? [] : [adapter.receiverActual]), ...adapter.actuals];
2389
- const call = `static_cast<${sourceType}*>(${adapterEnvironmentName})->call(${sourceActuals.join(', ')})`;
3085
+ // A source that names its one function -- by its representation, or because the
3086
+ // emitter saw the expression allocate it -- is called through that function's
3087
+ // thunk on the environment it already has, so the adapted view allocates nothing
3088
+ // (`CallableObject::adaptSourceInPlace`); any other source is held in a block.
3089
+ const knownId = source.kind === 'function' ? source.functionId : (knownFunction ?? null);
3090
+ const known = knownId === null ? null : cppThunkName(knownId);
3091
+ const call = known === null
3092
+ ? `static_cast<${sourceType}*>(${adapterEnvironmentName})->call(${sourceActuals.join(', ')})`
3093
+ : `${known}(${[adapterEnvironmentName, ...sourceActuals].join(', ')})`;
2390
3094
  const body = adapter.from.result.kind === 'void'
2391
3095
  ? `${call};${adapter.convertedResult === null ? '' : ` return ${adapter.convertedResult};`}`
2392
3096
  : adapter.to.result.kind === 'void'
2393
3097
  ? `${call};`
2394
3098
  : `${cppTypeOf(adapter.from.result)} ${adapterResultName} = ${call}; return ${adapter.convertedResult};`;
2395
- return `${cppTypeOf(target)}::adaptSource(${sourceType}{${text}}, [](${formals.join(', ')}) -> ${cppResultTypeOf(adapter.to.result)} { ${body} })`;
3099
+ const adapt = known === null ? 'adaptSource' : `adaptSourceInPlace<&${known}>`;
3100
+ return `${cppTypeOf(target)}::${adapt}(${sourceType}{${text}}, [](${formals.join(', ')}) -> ${cppResultTypeOf(adapter.to.result)} { ${body} })`;
2396
3101
  };
3102
+ /**
3103
+ * A class stored into a construct-signature slot whose convention differs from
3104
+ * the class's own -- `const bindings: { MongoCrypt: MongoCryptConstructor } =
3105
+ * { MongoCrypt: NativeMongoCrypt }`, where the slot's `new` answers an
3106
+ * interface and the class's answers its own instance.
3107
+ *
3108
+ * The adapter keeps the class evaluation as its environment, so the value is
3109
+ * still the same constructor object: `===`, its `FunctionObjectIdentity` own
3110
+ * table and the class dispatch a property read performs
3111
+ * (`emit-dynamic-properties.ts`'s `constructorValueDispatchGetText`) all key on
3112
+ * that environment, not on the construct entry. Only the entry is rewritten, to
3113
+ * convert each slot argument into the class's formal and the class's instance
3114
+ * into the slot's result. Any piece that has no installed conversion refuses
3115
+ * the whole adapter, and the store with it.
3116
+ */
3117
+ const constructorDispatchAdapterText = (source, target, text) => {
3118
+ if (source.kind !== 'constructor-family' || target.kind !== 'constructor-value-dispatch')
3119
+ return null;
3120
+ const members = source.members;
3121
+ if (members.length === 0)
3122
+ return null;
3123
+ const from = source.abi;
3124
+ const to = target.abi;
3125
+ if (from.receiver !== null || to.receiver !== null)
3126
+ return null;
3127
+ if (from.restFrom !== null || to.restFrom !== null)
3128
+ return null;
3129
+ if (from.parameters.slice(to.parameters.length).some((parameter) => cppUndefinedIn(parameter.value) === null))
3130
+ return null;
3131
+ const formals = to.parameters.map((parameter, index) => `${cppAbiParameterType(parameter)} gea_argument_${index}`);
3132
+ const actuals = [];
3133
+ for (const [index, slot] of from.parameters.entries()) {
3134
+ const parameter = to.parameters[index];
3135
+ if (parameter === undefined) {
3136
+ actuals.push(cppUndefinedIn(slot.value));
3137
+ continue;
3138
+ }
3139
+ const name = `gea_argument_${index}`;
3140
+ if (cppAbiParameterType(parameter) === cppAbiParameterType(slot)) {
3141
+ actuals.push(`std::forward<${cppAbiParameterType(parameter)}>(${name})`);
3142
+ continue;
3143
+ }
3144
+ const converted = tryCandidateText(() => convertedValueText(parameter.value, slot.value, name));
3145
+ if (converted === null)
3146
+ return null;
3147
+ actuals.push(converted);
3148
+ }
3149
+ if (from.result.kind === 'void' || to.result.kind === 'void')
3150
+ return null;
3151
+ const invocationOf = (member) => `${cppConstructThunkName(member)}(gea_environment${actuals.map((actual) => `, ${actual}`).join('')})`;
3152
+ const resultType = cppResultTypeOf(to.result);
3153
+ let body;
3154
+ const [sole] = members;
3155
+ if (members.length === 1 && sole !== undefined) {
3156
+ const invocation = invocationOf(sole);
3157
+ const result = cppTypeOf(from.result) === cppTypeOf(to.result)
3158
+ ? invocation
3159
+ : tryCandidateText(() => convertedValueText(from.result, to.result, invocation));
3160
+ if (result === null)
3161
+ return null;
3162
+ body = `return ${result};`;
3163
+ }
3164
+ else {
3165
+ // Several classes: a construct entry cannot capture the one it replaces, so
3166
+ // the member is recognized by the class evaluation the environment IS --
3167
+ // the declaration token `allocateNativeClassMethodEnvironment` stamped --
3168
+ // and each member's own thunk runs, its instance handed back through the
3169
+ // slot's class-ref (`gea::Ref`'s converting constructor, which only
3170
+ // admits a derived-to-base pair). A class this family does not name
3171
+ // refuses rather than constructing through another body.
3172
+ if (to.result.kind !== 'class-ref')
3173
+ return null;
3174
+ const arms = members.map((member) => `if (gea_class == &gea::nativeClassMethodDeclaration<${cppClassName(member)}>) return ${resultType}(${invocationOf(member)}); `);
3175
+ body =
3176
+ `const void* gea_class = static_cast<gea::NativeClassMethodState*>(gea_environment)->declaration; ${arms.join('')}` +
3177
+ `gea::detail::refusePayloadMismatch("a constructor family value holds a class its family does not name");`;
3178
+ }
3179
+ return (`[](const ${cppTypeOf(source)}& gea_from) { ${cppTypeOf(target)} gea_to; ` +
3180
+ `gea_to.construct_ = +[](void* gea_environment${formals.map((formal) => `, ${formal}`).join('')}) -> ${resultType} { ` +
3181
+ `${body} }; ` +
3182
+ `gea_to.environment = gea_from.environment; gea_to.environmentOwner = gea_from.environmentOwner; return gea_to; }(${text})`);
3183
+ };
3184
+ /** Whether a class reaches a construct-signature slot through `constructorDispatchAdapterText`. Exported so `conversions.ts` asks the identical question the render answers. */
3185
+ export const adaptsConstructorIntoDispatch = (source, target) => source.kind === 'constructor-family' &&
3186
+ target.kind === 'constructor-value-dispatch' &&
3187
+ cppTypeOf(source) !== cppTypeOf(target) &&
3188
+ constructorDispatchAdapterText(source, target, 'gea_probe') !== null;
2397
3189
  /**
2398
3190
  * A callable filling a slot that declares MORE parameters than it does, the
2399
3191
  * extra ones landing after every one the source itself names./**
@@ -2554,9 +3346,10 @@ export const dropsAllParametersIntoResultArm = (source, target) => {
2554
3346
  * `gea_runtime.h`'s `CallableObject` composed converting constructor this
2555
3347
  * asks for discards whatever the source returns; see that constructor's own
2556
3348
  * comment for why doing so is never lossy for an async body specifically --
2557
- * this runtime's `Promise<V>` is a settled-value box, never a coroutine
2558
- * frame, so by the time a call returns here its entire body, `await`s
2559
- * included, has already run to completion.
3349
+ * the promise is only the caller's handle on the outcome: a suspended async
3350
+ * body's frame is owned by the reaction it is parked on, not by the promise
3351
+ * the call returned, so dropping that promise cancels nothing and the body
3352
+ * still runs to completion from the job queue.
2560
3353
  *
2561
3354
  * Gated the mirror of `dropsAllParametersIntoResultArm` above: parameters
2562
3355
  * must agree in COUNT and in every position's TYPE (this is not an arity
@@ -2748,7 +3541,7 @@ export const boxDiscriminantsOfArm = (arm) => {
2748
3541
  return null;
2749
3542
  if (discriminants === null)
2750
3543
  return null;
2751
- if (arm.runtimeDiscriminator.kind === 'carrier') {
3544
+ if (arm.runtimeDiscriminator.kind === 'carrier' || arm.runtimeDiscriminator.kind === 'record-literal') {
2752
3545
  return discriminants.some((entry) => entry.callableMembers !== null) ? null : discriminants;
2753
3546
  }
2754
3547
  const expected = [...arm.runtimeDiscriminator.members].sort();
@@ -2769,7 +3562,106 @@ export const boxDiscriminantsOfArm = (arm) => {
2769
3562
  * makes the message itself the answer.
2770
3563
  */
2771
3564
  const assertionSite = (target) => `an assertion out of a dynamic value to ${cppTypeOf(target)}`;
3565
+ /**
3566
+ * Whether reading `target` out of a box reaches a record through
3567
+ * `unboxedLoadText`'s own record conversion -- the one a runtime element rule
3568
+ * (`DynamicCarrier`) cannot restate, since only the compiler knows which
3569
+ * struct is a record rather than a class.
3570
+ */
3571
+ export const adoptsDynamicRecord = (target) => {
3572
+ if (target.kind === 'optional')
3573
+ return adoptsDynamicRecord(target.payload);
3574
+ if (target.kind === 'array-object')
3575
+ return adoptsDynamicRecord(target.element);
3576
+ const record = (target.kind === 'record' && target.accessors.length === 0) || target.kind === 'record-with-index';
3577
+ return record && target.ownership === 'shared-refcount';
3578
+ };
3579
+ /**
3580
+ * The condition `unboxedLoadText(target, value)` itself checks before its
3581
+ * exact payload load, for the carriers that load is the generic tag-and-payload
3582
+ * read of (an optional adds its own absence). A record's dynamic conversion
3583
+ * asks it first, so a mistyped field is a TypeError rather than the load's
3584
+ * abort. `null` for every carrier with a load of its own: those refuse (or
3585
+ * throw, for a nested record) themselves, and restating their rules here would
3586
+ * be a second authority.
3587
+ */
3588
+ const dynamicFieldAdmissionText = (target, value) => {
3589
+ if (target.kind === 'optional') {
3590
+ const payload = dynamicFieldAdmissionText(target.payload, value);
3591
+ if (payload === null)
3592
+ return null;
3593
+ return `${value}.tag() == gea::Value::Tag::${target.absence === 'null' ? 'Null' : 'Undefined'} || (${payload})`;
3594
+ }
3595
+ if (callableObjectAbi(target) !== null || isNativeError(target))
3596
+ return null;
3597
+ switch (target.kind) {
3598
+ case 'dynamic':
3599
+ case 'class-ref':
3600
+ case 'tagged-union':
3601
+ case 'array-object':
3602
+ case 'keyed-collection':
3603
+ case 'dictionary':
3604
+ case 'record':
3605
+ case 'record-with-index':
3606
+ case 'promise':
3607
+ return null;
3608
+ }
3609
+ const tag = dynamicTagFor(target);
3610
+ if (tag === null)
3611
+ return null;
3612
+ if (tag === 'Undefined' || tag === 'Null')
3613
+ return `${value}.tag() == gea::Value::Tag::${tag}`;
3614
+ return `${value}.tag() == gea::Value::Tag::${tag} && ${value}.payloadType() == gea::detail::payloadTypeTagFor<${cppTypeOf(target)}>()`;
3615
+ };
3616
+ /**
3617
+ * The checked load of `text`, a `gea::Value`, into `target`'s carrier.
3618
+ *
3619
+ * The load depends on nothing but the target, and the same one recurs at
3620
+ * every dynamic read of that carrier: each field of an `any -> record`
3621
+ * rebuild, each branch of a spread's key routing, each sidecar read of a
3622
+ * record view. A load longer than the call that replaces it is therefore
3623
+ * defined once as a unit function over its operand and called by name
3624
+ * (`unitFunctionName`); the operand is then evaluated once, where a load that
3625
+ * names it in a test and again in the payload read pasted it twice.
3626
+ */
3627
+ /**
3628
+ * The unit function that moves an unboxed `double` into a member the integer
3629
+ * census narrowed (`long long`), refusing what the storage cannot hold; see
3630
+ * the dynamic-to-record rebuild below for why the refusal is right.
3631
+ */
3632
+ const narrowedIntegerFromDynamicName = () => {
3633
+ const body = 'if (!(gea_value == gea_value) || gea_value != std::floor(gea_value) || gea_value > 9007199254740992.0 || gea_value < -9007199254740992.0) ' +
3634
+ 'gea::host::throwRuntimeError("TypeError", "a dynamic record\'s number field holds a value its integer storage cannot"); ' +
3635
+ `return static_cast<${cppNarrowedIntegerType}>(gea_value);`;
3636
+ const named = unitFunctionName('gea_narrowed_integer_from_dynamic', (name) => `${cppNarrowedIntegerType} ${name}(double gea_value)`, body);
3637
+ return named ?? `[](double gea_value) -> ${cppNarrowedIntegerType} { ${body} }`;
3638
+ };
2772
3639
  export const unboxedLoadText = (target, text) => {
3640
+ const formal = 'gea_unboxed';
3641
+ const load = unboxedLoadTextAt(target, formal);
3642
+ if (load === null)
3643
+ return null;
3644
+ if (load.length <= unitLoadInlineLimit)
3645
+ return unboxedLoadTextAt(target, text);
3646
+ const named = unitFunctionName('gea_unbox', (name) => `${cppTypeOf(target)} ${name}(const gea::Value& ${formal})`, `return ${load};`);
3647
+ return named === null ? unboxedLoadTextAt(target, text) : `${named}(${text})`;
3648
+ };
3649
+ /** A load no longer than this stays inline: naming a unit function costs about as much as it saves. */
3650
+ const unitLoadInlineLimit = 64;
3651
+ /**
3652
+ * The load of a record member that is a plain receiverless callable, bound to
3653
+ * the object it was read from -- or `null` when the member is anything else
3654
+ * (the ordinary `unboxedLoadText` answers it).
3655
+ */
3656
+ const boundMethodLoadText = (target, text, holder) => {
3657
+ if (target.kind !== 'function-value-dispatch')
3658
+ return null;
3659
+ const abi = callableObjectAbi(target);
3660
+ if (abi === null || abi.receiver !== null || abi.restFrom !== null)
3661
+ return null;
3662
+ return `gea::detail::DynamicCarrier<${cppTypeOf(target)}>::inBound(${text}, 0, ${holder})`;
3663
+ };
3664
+ const unboxedLoadTextAt = (target, text) => {
2773
3665
  // A `Function` arm remains a Value because its ABI is unknown. Loading it
2774
3666
  // out of a broader dynamic boundary is an identity-preserving copy guarded
2775
3667
  // by the Function tag, not an adaptation to an invented signature.
@@ -2882,6 +3774,13 @@ export const unboxedLoadText = (target, text) => {
2882
3774
  for (const left of sets[i])
2883
3775
  for (const right of sets[j])
2884
3776
  if (left.tag === right.tag && left.payload === right.payload && left.nominal === right.nominal) {
3777
+ const a = target.arms[i].runtimeDiscriminator;
3778
+ const b = target.arms[j].runtimeDiscriminator;
3779
+ if (a.kind === 'record-literal' &&
3780
+ b.kind === 'record-literal' &&
3781
+ a.key === b.key &&
3782
+ (a.primitive !== b.primitive || a.text !== b.text))
3783
+ continue;
2885
3784
  if (left.callableMembers === null || right.callableMembers === null)
2886
3785
  return null;
2887
3786
  if (left.callableMembers.some((member) => right.callableMembers.includes(member)))
@@ -2925,7 +3824,19 @@ export const unboxedLoadText = (target, text) => {
2925
3824
  `${text}.payloadType() == gea::detail::payloadTypeTagFor<${discriminant.payload}>())`
2926
3825
  : `${text}.tag() == gea::Value::Tag::${discriminant.tag}`;
2927
3826
  };
2928
- const condition = (index) => sets[index].map((entry) => test(entry)).join(' || ');
3827
+ const condition = (index) => {
3828
+ const discriminator = target.arms[index].runtimeDiscriminator;
3829
+ if (discriminator.kind !== 'record-literal')
3830
+ return sets[index].map((entry) => test(entry)).join(' || ');
3831
+ const tag = discriminator.primitive === 'string' ? 'String' : discriminator.primitive === 'number' ? 'Number' : 'Boolean';
3832
+ const type = discriminator.primitive === 'string' ? 'std::string' : discriminator.primitive === 'number' ? 'double' : 'bool';
3833
+ const literal = discriminator.primitive === 'string' ? cppStringLiteral(discriminator.text) : discriminator.text;
3834
+ return (`([](const gea::Value& object, bool nativeRecord) { if (object.tag() != gea::Value::Tag::Object) return false; ` +
3835
+ `const auto value = gea::detail::dynamicRecordDiscriminator(object, ${cppStringLiteral(discriminator.key)}, nativeRecord); ` +
3836
+ `return value.tag() == gea::Value::Tag::${tag} && ` +
3837
+ `gea::detail::unboxValue<${type}>(value, gea::Value::Tag::${tag}, "a union discriminator") == ${literal}; ` +
3838
+ `}(${text}, ${sets[index].map((entry) => test(entry)).join(' || ')}))`);
3839
+ };
2929
3840
  // The final arm must not be an implicit fallback. An exact load used to
2930
3841
  // refuse a nonmatching tag by itself, but a coercive Number/String arm
2931
3842
  // would otherwise turn (for example) Boolean into whichever arm happens
@@ -2973,8 +3884,44 @@ export const unboxedLoadText = (target, text) => {
2973
3884
  // result is a native `ArrayObject<Element>` and a bad element refuses rather
2974
3885
  // than being reinterpreted or leaving the whole Array boxed.
2975
3886
  if (target.kind === 'array-object') {
3887
+ // A record element is not a carrier `DynamicCarrier` can rebuild: which
3888
+ // struct is a record rather than a class is a compiler fact, and the
3889
+ // runtime's `Ref<T>` rule reads a box back by identity alone -- so a JSON
3890
+ // or BSON document element aborted. The element takes this function's own
3891
+ // record conversion instead, the one every other `any -> record` read takes.
3892
+ if (adoptsDynamicRecord(target.element)) {
3893
+ const element = 'gea_dynamic_element';
3894
+ const load = unboxedLoadText(target.element, element);
3895
+ if (load === null)
3896
+ return null;
3897
+ return (`gea::detail::unboxDynamicArrayWith<${cppTypeOf(target.element)}>(${text}, ${cppStringLiteral(assertionSite(target))}, ` +
3898
+ `[](const gea::Value& ${element}) -> ${cppTypeOf(target.element)} { return ${load}; })`);
3899
+ }
2976
3900
  return `gea::detail::unboxDynamicArray<${cppTypeOf(target.element)}>(${text}, ${cppStringLiteral(assertionSite(target))})`;
2977
3901
  }
3902
+ // `conversions.ts`'s `dynamicPromiseAdoptionMaterializer`, spelled: the
3903
+ // boxed promise adopted, each fulfilment value through the payload's own
3904
+ // checked load -- the same `promiseFromDynamic` an async `return` runs.
3905
+ if (target.kind === 'promise') {
3906
+ if (target.value.kind === 'void')
3907
+ return `gea::detail::promiseFromDynamic<void>(${text})`;
3908
+ const settledType = cppTypeOf(target.value);
3909
+ const settled = target.value.kind === 'dynamic' ? 'gea_settled' : unboxedLoadText(target.value, 'gea_settled');
3910
+ if (settled === null)
3911
+ return null;
3912
+ return `gea::detail::promiseFromDynamic<${settledType}>(${text}, [](const gea::Value& gea_settled) { return ${settledType}(${settled}); })`;
3913
+ }
3914
+ // `conversions.ts`'s `dynamicMapViewMaterializer`, spelled: any boxed Map,
3915
+ // read through a view of the same object.
3916
+ if (target.kind === 'keyed-collection' &&
3917
+ target.family === 'map' &&
3918
+ target.ownership === 'shared-refcount' &&
3919
+ target.recursive === undefined &&
3920
+ target.readOnlyView !== true &&
3921
+ target.key.kind === 'dynamic' &&
3922
+ target.value?.kind === 'dynamic') {
3923
+ return `gea::detail::unboxDynamicMap(${text}, ${cppStringLiteral(assertionSite(target))})`;
3924
+ }
2978
3925
  if (target.kind === 'dictionary' && target.key === 'string' && target.ownership === 'shared-refcount') {
2979
3926
  return `gea::detail::unboxDynamicDictionary<${cppTypeOf(target.value)}>(${text}, ${cppStringLiteral(assertionSite(target))})`;
2980
3927
  }
@@ -2983,43 +3930,108 @@ export const unboxedLoadText = (target, text) => {
2983
3930
  // that payload to already be the target record's C++ struct rejects valid
2984
3931
  // BSON/JSON document assertions. Rebuild the declared record from checked
2985
3932
  // dynamic field reads instead. The exact-payload branch preserves identity
2986
- // when the box already carries this record; the fallback evaluates the
2987
- // source once and leaves extra dictionary keys outside the statically
2988
- // declared result, matching the assertion's structural view.
2989
- if (target.kind === 'record' && target.accessors.length === 0) {
3933
+ // when the box already carries this record.
3934
+ //
3935
+ // A Document is then ADOPTED into the product (`gea::dictionary::
3936
+ // adoptProduct`): it views the record, so a write through the typed name is
3937
+ // a read through the `any` one, and the keys the record does not declare
3938
+ // move with it -- into the index sidecar of a `record-with-index`, whose
3939
+ // open half a field-by-field copy would otherwise drop. A value that is not
3940
+ // this record is the program's contract violated, not the compiler's, so it
3941
+ // is a TypeError the program may catch, as `exactArm` is.
3942
+ if ((target.kind === 'record' && target.accessors.length === 0) || target.kind === 'record-with-index') {
2990
3943
  if (target.ownership === 'borrowed')
2991
3944
  return null;
3945
+ const indexed = target.kind === 'record-with-index';
3946
+ if (indexed && (target.ownership !== 'shared-refcount' || target.fields.some((field) => cppRecordFieldKeyIsSymbol(field.key))))
3947
+ return null;
2992
3948
  const targetType = cppTypeOf(target);
3949
+ const structName = cppRecordStructName(target.shapeId);
2993
3950
  const holder = 'gea_dynamic_record';
2994
3951
  const fields = target.fields.map((field, index) => {
2995
3952
  const present = `gea_dynamic_record_present_${index}`;
2996
3953
  const value = `gea_dynamic_record_value_${index}`;
2997
- const load = field.value.kind === 'dynamic' ? value : unboxedLoadText(field.value, value);
2998
- return { field, present, value, load };
3954
+ // A method read off the dynamic object is called as `object.method(...)`,
3955
+ // so its adapter binds the object as `this` (`DynamicCarrier::inBound`).
3956
+ const boundMember = boundMethodLoadText(field.value, value, holder);
3957
+ const unboxed = field.value.kind === 'dynamic' ? value : (boundMember ?? unboxedLoadText(field.value, value));
3958
+ // A member the integer census narrowed is a `long long`, and a braced
3959
+ // initializer refuses the `double` a box unboxes to. The census admitted
3960
+ // this rebuild because the box carries exactly this struct, which the
3961
+ // exact-payload branch above answers by identity; a foreign object
3962
+ // reaching this field-by-field path has already broken the program's
3963
+ // contract, so a value the storage cannot hold is the same TypeError.
3964
+ const load = unboxed !== null && storageSlotIsNarrowed(integerStorageSlot(structName, field.key))
3965
+ ? `${narrowedIntegerFromDynamicName()}(${unboxed})`
3966
+ : unboxed;
3967
+ return { field, present, value, load, admission: dynamicFieldAdmissionText(field.value, value) };
2999
3968
  });
3000
3969
  if (fields.some((field) => field.load === null))
3001
3970
  return null;
3971
+ const refused = (message) => `gea::host::throwRuntimeError("TypeError", ${cppStringLiteral(message)});`;
3002
3972
  const checks = fields
3003
3973
  .filter(({ field }) => field.required)
3004
- .map(({ field, present }) => `if (!${present}) gea::detail::refusePayloadMismatch("a dynamic record lacks required field ${field.key}");`);
3974
+ .map(({ field, present }) => `if (!${present}) ${refused(`a dynamic record lacks required field ${field.key}`)}`);
3005
3975
  const values = fields.map(({ field, present, value }) => `const gea::Value ${value} = ${present} ? gea::detail::dynamicRecordField(${holder}, ${cppStringLiteral(field.key)}) : gea::Value();`);
3976
+ const admissions = fields
3977
+ .filter(({ admission }) => admission !== null)
3978
+ .map(({ field, present, admission }) => `if (${present} && !(${admission})) ${refused(`a dynamic record's field ${field.key} is not of the declared type`)}`);
3006
3979
  const reads = fields.map(({ field, present, load }) => {
3007
3980
  const materialized = load;
3008
3981
  return field.required ? materialized : `(${present} ? ${materialized} : ${cppTypeOf(field.value)}{})`;
3009
3982
  });
3010
- const presences = fields.filter(({ field }) => !field.required).map(({ present }) => present);
3011
- const structure = `${cppRecordStructName(target.shapeId)}{${[...reads, ...presences].join(', ')}}`;
3012
- const built = target.ownership === 'shared-refcount' ? `gea::makeRef<${cppRecordStructName(target.shapeId)}>(${structure})` : structure;
3983
+ // A layout that moved fields behind its `RecordTail` no longer declares
3984
+ // them positionally, and storing an absent one would allocate the tail
3985
+ // for nothing, so it is filled by name, present fields only.
3986
+ const tailed = !indexed && tailFieldsOf({ fields: target.fields }).size > 0;
3987
+ const product = () => {
3988
+ if (tailed) {
3989
+ const access = target.ownership === 'shared-refcount' ? '->' : '.';
3990
+ const assignments = fields.map(({ field, present, load }) => {
3991
+ const store = `gea_built${access}${tailAwareFieldWriteText(target.fields, field.key)} = ${load};`;
3992
+ return field.required ? store : `if (${present}) { ${store} gea_built${access}${cppRecordFieldPresenceName(field.key)} = true; }`;
3993
+ });
3994
+ const built = target.ownership === 'shared-refcount' ? `auto gea_built = gea::makeRef<${structName}>();` : `${structName} gea_built{};`;
3995
+ return `[&]() { ${built} ${assignments.join(' ')} return gea_built; }()`;
3996
+ }
3997
+ if (!indexed) {
3998
+ const presences = fields.filter(({ field }) => !field.required).map(({ present }) => present);
3999
+ const structure = `${structName}{${[...reads, ...presences].join(', ')}}`;
4000
+ return target.ownership === 'shared-refcount' ? `gea::makeRef<${structName}>(${structure})` : structure;
4001
+ }
4002
+ // The index sidecar sits between the fields and their presence bits, so
4003
+ // this layout is filled by name rather than by position.
4004
+ const assignments = fields.map(({ field, present }, index) => {
4005
+ const store = `gea_built->${cppRecordFieldName(field.key)} = ${reads[index]};`;
4006
+ return field.required ? store : `${store} gea_built->${cppRecordFieldPresenceName(field.key)} = ${present};`;
4007
+ });
4008
+ return `[&]() { auto gea_built = gea::makeRef<${structName}>(); ${assignments.join(' ')} return gea_built; }()`;
4009
+ };
4010
+ const adopted = target.ownership === 'shared-refcount'
4011
+ ? `gea::dictionary::adoptProduct<${structName}>(${holder}, [&]() -> ${targetType} { return ${product()}; })`
4012
+ : product();
3013
4013
  const exactPayload = target.ownership === 'shared-refcount'
3014
4014
  ? `if (${holder}.tag() == gea::Value::Tag::Object && ${holder}.payloadType() == gea::detail::payloadTypeTagFor<${targetType}>()) ` +
3015
4015
  `return gea::detail::unboxValue<${targetType}>(${holder}, gea::Value::Tag::Object, ${cppStringLiteral(assertionSite(target))}); `
3016
4016
  : '';
3017
- return (`[](const gea::Value& ${holder}) -> ${targetType} { ` +
3018
- exactPayload +
4017
+ // An indexed record's open half has no source but a Document's entries:
4018
+ // any other object would lose them, which a snapshot cast may not.
4019
+ const documentOnly = indexed
4020
+ ? `if (${holder}.payloadType() != gea::detail::payloadTypeTagFor<gea::Ref<gea::Dictionary<gea::Value>>>()) ` +
4021
+ `gea::detail::refusePayloadMismatch(${cppStringLiteral(assertionSite(target))}); `
4022
+ : '';
4023
+ const body = exactPayload +
3019
4024
  `if (${holder}.tag() != gea::Value::Tag::Object && ${holder}.tag() != gea::Value::Tag::Function) ` +
3020
- `gea::detail::refusePayloadMismatch("an assertion to a record requires an object"); ` +
4025
+ `${refused('an assertion to a record requires an object')} ` +
4026
+ documentOnly +
3021
4027
  `${fields.map(({ field, present }) => `const bool ${present} = gea::detail::dynamicRecordHasField(${holder}, ${cppStringLiteral(field.key)});`).join(' ')} ` +
3022
- `${checks.join(' ')} ${values.join(' ')} return ${built}; }(${text})`);
4028
+ `${checks.join(' ')} ${values.join(' ')} ${admissions.join(' ')} return ${adopted};`;
4029
+ // The text depends on the target alone, so a unit defines it once and
4030
+ // every site calls it -- see `unitFunctionName`.
4031
+ const named = unitFunctionName(`gea_from_dynamic_${structName}`, (name) => `${targetType} ${name}(const gea::Value& ${holder})`, body);
4032
+ if (named !== null)
4033
+ return `${named}(${text})`;
4034
+ return `[](const gea::Value& ${holder}) -> ${targetType} { ${body} }(${text})`;
3023
4035
  }
3024
4036
  // The exact inverse of the boxing table, asked of the same function, so a
3025
4037
  // carrier can never be boxed under one tag and read back under another.
@@ -3044,6 +4056,10 @@ export const unboxedLoadText = (target, text) => {
3044
4056
  // `gea::BigInt` type and `unboxValue` checks it like every other scalar.
3045
4057
  if (tag === 'Null')
3046
4058
  return `gea::detail::unboxNullValue(${text}, ${cppStringLiteral(assertionSite(target))})`;
4059
+ // The intrinsic `Error` carrier is the one object a box may hold under
4060
+ // ANOTHER payload type and still be: a compiled subclass's handle.
4061
+ if (isNativeError(target))
4062
+ return `gea::detail::unboxNativeError(${text}, ${cppStringLiteral(assertionSite(target))})`;
3047
4063
  // `gea::detail::unboxValue` checks BOTH the tag and the payload's recorded
3048
4064
  // C++ type (`payloadTypeTagFor`), so a box holding a different struct than
3049
4065
  // the narrowing claimed refuses by name instead of reinterpreting bytes.
@@ -3168,6 +4184,62 @@ const claimed = (text) => (text === null ? undefined : text);
3168
4184
  * rendering it, so the conversion census (`conversion/nodes.ts`) can state
3169
4185
  * the same answer this printer gives, from the same table.
3170
4186
  */
4187
+ /**
4188
+ * A promise adopting another's state with its fulfilment payload converted:
4189
+ * the chain's `promise-payload` step renders it with the chain's own payload
4190
+ * conversion, and `recipeText` with a structural record view when that is
4191
+ * what carries the payload (`IteratorResult<T>`'s arms are named interfaces a
4192
+ * `{ value, done: false }` literal reaches only by a view).
4193
+ *
4194
+ * A source still PENDING links through `observe`: hono's `#cachedBody` is one
4195
+ * callable returning `Promise<string | ArrayBuffer | Blob | ...>` that every
4196
+ * reader (`text()`, `json()`, `formData()`) adapts to its own `Promise<T>` at
4197
+ * the call, and the promise it hands back is the body read that has not
4198
+ * arrived yet. Snapshotting it (`if (!settled()) return Target()`) minted a
4199
+ * target nothing ever settled -- every `await c.req.json()` hung and the POST
4200
+ * never answered. The conversion runs when the value exists; a conversion that
4201
+ * throws (a dynamic arm not of the declared type) becomes the target's
4202
+ * rejection, which is what the same failure inside a `then` handler is.
4203
+ */
4204
+ const promiseAdoptionText = (source, target, text, payload) => {
4205
+ const settledPayload = payload(`${promiseSourceName}.value()`);
4206
+ if (settledPayload === null)
4207
+ return null;
4208
+ const pendingPayload = payload(promiseValueName);
4209
+ if (pendingPayload === null)
4210
+ return null;
4211
+ return (`([&]() -> ${cppTypeOf(target)} { const auto& ${promiseSourceName} = ${text}; ` +
4212
+ `if (${promiseSourceName}.rejected()) return ${cppTypeOf(target)}::rejected_with(${promiseSourceName}.rejection()); ` +
4213
+ `if (${promiseSourceName}.settled()) return ${cppTypeOf(target)}(${settledPayload}); ` +
4214
+ `${cppTypeOf(target)} ${promiseTargetName}; ` +
4215
+ `${promiseSourceName}.observe([${promiseTargetName}](const ${cppTypeOf(source.value)}& ${promiseValueName}) mutable ` +
4216
+ `{ try { ${promiseTargetName}.resolveInline(${pendingPayload}); } catch (...) { ${promiseTargetName}.rejectInline(std::current_exception()); } }, ` +
4217
+ `[${promiseTargetName}](const std::exception_ptr& ${promiseRejectionName}) mutable ` +
4218
+ `{ ${promiseTargetName}.rejectInline(${promiseRejectionName}); }); ` +
4219
+ `return ${promiseTargetName}; }())`);
4220
+ };
4221
+ /**
4222
+ * The `rebuild: 'unshared-array'` conversion (`ir/model.ts`'s `ConvertOperation`):
4223
+ * a call result lowering proved no other reference holds, rebuilt once at the
4224
+ * published element carrier. The rebuild allocates, which is exactly what makes
4225
+ * this unsound for any array another alias can reach -- so it is rendered only
4226
+ * for the instruction that carries the proof, never from the pair alone, and a
4227
+ * pending promise rebuilds when its array arrives (`promiseAdoptionText`).
4228
+ */
4229
+ export const unsharedArrayRebuildText = (ctx, source, target, text) => {
4230
+ if (source.kind === 'promise' && target.kind === 'promise') {
4231
+ return promiseAdoptionText(source, target, text, (value) => unsharedArrayRebuildText(ctx, source.value, target.value, value));
4232
+ }
4233
+ if (source.kind !== 'array-object' || target.kind !== 'array-object')
4234
+ return null;
4235
+ const element = alignedValueText(ctx, 'emit-narrowing.ts:unshared-array', source.element, target.element, 'gea_element');
4236
+ if (element === null)
4237
+ return null;
4238
+ return (`([&]() -> ${cppTypeOf(target)} { const auto& gea_fresh = ${text}; ` +
4239
+ `auto gea_rebuilt = gea::makeRef<${cppTypeOf(target, 'owned')}>(); ` +
4240
+ `gea_rebuilt->appendRangeConverted(*gea_fresh, 0, [&](const ${cppTypeOf(source.element)}& gea_element) { return ${element}; }); ` +
4241
+ `return gea_rebuilt; }())`);
4242
+ };
3171
4243
  export const conversionChain = [
3172
4244
  { id: 'native-sum-widening', apply: (source, target, text) => claimed(widenedNativeSumText(source, target, text)) },
3173
4245
  // A choice among generic functions widening into a superset: the index is
@@ -3193,6 +4265,16 @@ export const conversionChain = [
3193
4265
  return member === null ? undefined : `gea::upcastConstructor<${cppTypeOf(target)}, &${cppConstructThunkName(member)}>(${text})`;
3194
4266
  }
3195
4267
  },
4268
+ {
4269
+ id: 'constructor-family-upcast',
4270
+ apply: (source, target, text) => {
4271
+ const members = constructorFamilyUpcastMembers(source, target);
4272
+ if (members === null)
4273
+ return undefined;
4274
+ const thunks = members.map((member) => `&${cppConstructThunkName(member)}`).join(', ');
4275
+ return `gea::upcastConstructorFamily<${cppTypeOf(target)}, ${cppTypeOf(source)}, ${thunks}>(${text})`;
4276
+ }
4277
+ },
3196
4278
  {
3197
4279
  // The same store when the two conventions also disagree on a parameter
3198
4280
  // (`global.Request = LightweightRequest`, whose `input` names its own class
@@ -3233,6 +4315,10 @@ export const conversionChain = [
3233
4315
  `gea_to.environment = gea_from.environment; gea_to.environmentOwner = gea_from.environmentOwner; return gea_to; }(${text})`);
3234
4316
  }
3235
4317
  },
4318
+ {
4319
+ id: 'constructor-dispatch-adapter',
4320
+ apply: (source, target, text) => claimed(constructorDispatchAdapterText(source, target, text))
4321
+ },
3236
4322
  { id: 'regexp-match-array-base', apply: (source, target, text) => claimed(regexpMatchArrayBaseText(source, target, text)) },
3237
4323
  // A derived class-ref stored where a base class-ref is declared, rendered as
3238
4324
  // an EXPLICIT construction of the target. Checks the same ancestry direction as
@@ -3251,6 +4337,46 @@ export const conversionChain = [
3251
4337
  ? `${cppTypeOf(target)}(${text})`
3252
4338
  : undefined
3253
4339
  },
4340
+ // An instance of a class extending a native collection stored where that
4341
+ // collection is declared: the struct derives from the runtime's collection
4342
+ // object (`records.ts`'s native collection link), so this is `class-upcast`
4343
+ // one base over. Refused for a family that redeclares a collection member
4344
+ // (`class-ref.nativeBaseOverridden`) -- held as the bare collection, the
4345
+ // member would answer natively and skip the override. A read of one member
4346
+ // the family does not redeclare takes the census's `nativeBaseViewFor` node
4347
+ // instead, which renders this same upcast.
4348
+ {
4349
+ id: 'native-collection-upcast',
4350
+ apply: (source, target, text) => isNativeCollectionUpcast(source, target) && source.kind === 'class-ref' && !source.nativeBaseOverridden
4351
+ ? `${cppTypeOf(target)}(${text})`
4352
+ : undefined
4353
+ },
4354
+ // The same one base over for a class extending the intrinsic `Error`: its
4355
+ // struct derives from `gea::runtime::Error` in place (`records.ts`'s native
4356
+ // link), so `MongoError` stored where `Error` is declared is `Ref`'s own
4357
+ // converting constructor. `nativeRecordBaseTransportKind` states when a
4358
+ // family's overrides refuse it.
4359
+ // An instance of a class extending the intrinsic `Promise` stored where a
4360
+ // promise is declared: the struct derives from `gea::Promise<V>` in place,
4361
+ // so the store copies the base handle, which shares the instance's state.
4362
+ // A promise of another payload goes on through the ordinary promise chain
4363
+ // (`Promise<never>` into `Promise<T>`).
4364
+ {
4365
+ id: 'native-promise-upcast',
4366
+ apply: (source, target, text) => {
4367
+ const base = nativePromiseBaseOf(source);
4368
+ if (base === null || target.kind !== 'promise')
4369
+ return undefined;
4370
+ const viewed = `${cppTypeOf(base)}(static_cast<const ${cppTypeOf(base)}&>(*(${text})))`;
4371
+ if (representationKey(base) === representationKey(target))
4372
+ return viewed;
4373
+ return claimed(tryCandidateText(() => convertedValueText(base, target, viewed)));
4374
+ }
4375
+ },
4376
+ {
4377
+ id: 'native-record-upcast',
4378
+ apply: (source, target, text) => nativeRecordBaseTransportKind(source, target) === 'upcast' ? `${cppTypeOf(target)}(${text})` : undefined
4379
+ },
3254
4380
  // A host handle stored where one of its own base types is declared, the same
3255
4381
  // rule as `class-upcast` above for a hierarchy this compiler did not lay out.
3256
4382
  // An `NSStackView` IS an `NSView`: the host stated the inheritance
@@ -3272,6 +4398,15 @@ export const conversionChain = [
3272
4398
  ? `${cppTypeOf(target)}(${text})`
3273
4399
  : undefined
3274
4400
  },
4401
+ {
4402
+ id: 'native-handle-view',
4403
+ apply: (source, target, text) => {
4404
+ if (source.kind !== 'native-handle' || target.kind !== 'native-handle' || source.native === null)
4405
+ return undefined;
4406
+ const template = target.viewsFrom?.get(source.native);
4407
+ return template?.replace('{value}', `(${text})`);
4408
+ }
4409
+ },
3275
4410
  { id: 'callable-part', apply: (source, target, text) => claimed(callablePartText(source, target, text)) },
3276
4411
  // An EMPTY array literal flowing into a native array-like carrier. `[]` with
3277
4412
  // no contextual array type checks as the empty tuple, which derives a record
@@ -3282,9 +4417,12 @@ export const conversionChain = [
3282
4417
  // a record with even one field would be dropping data.
3283
4418
  {
3284
4419
  id: 'empty-record-into-native',
3285
- apply: (source, target) => source.kind === 'record' && source.fields.length === 0 && source.accessors.length === 0 && target.kind === 'native-record-ref'
4420
+ apply: (source, target) => source.kind === 'record' &&
4421
+ source.fields.length === 0 &&
4422
+ source.accessors.length === 0 &&
4423
+ (target.kind === 'native-record-ref' || (target.kind === 'record-with-index' && target.fields.every((field) => !field.required)))
3286
4424
  ? target.ownership === 'shared-refcount'
3287
- ? `gea::makeRef<${target.native ?? cppTypeOf(target, 'owned')}>()`
4425
+ ? `gea::makeRef<${(target.kind === 'native-record-ref' ? target.native : null) ?? cppTypeOf(target, 'owned')}>()`
3288
4426
  : `${cppTypeOf(target, 'owned')}{}`
3289
4427
  : undefined
3290
4428
  },
@@ -3445,10 +4583,22 @@ export const conversionChain = [
3445
4583
  // `recordCastableToDictionary` for why only this direction is sound.
3446
4584
  // `record-to-array` is the same distance: an unannotated rest parameter's two
3447
4585
  // views (`recordCastableToArray`).
4586
+ // A class instance or shared record into an open `any` document: the
4587
+ // object itself, viewed (`classDocumentViewText`), never a table of its fields.
4588
+ {
4589
+ id: 'class-document-view',
4590
+ apply: (source, target, text) => claimed(classDocumentViewText(source, target, text))
4591
+ },
3448
4592
  {
3449
4593
  id: 'record-to-dictionary',
3450
4594
  apply: (source, target, text) => source.kind === 'record' && target.kind === 'dictionary' ? claimed(recastedRecordToDictionaryText(source, target, text)) : undefined
3451
4595
  },
4596
+ {
4597
+ id: 'indexed-record-to-dictionary',
4598
+ apply: (source, target, text) => source.kind === 'record-with-index' && target.kind === 'dictionary'
4599
+ ? claimed(recastedIndexedRecordToDictionaryText(source, target, text))
4600
+ : undefined
4601
+ },
3452
4602
  // One shape wider: an open dictionary's values widened into another's
3453
4603
  // (`dictionaryCastableToDictionary`).
3454
4604
  {
@@ -3467,6 +4617,11 @@ export const conversionChain = [
3467
4617
  id: 'dictionary-to-record',
3468
4618
  apply: (source, target, text) => claimed(dictionaryToRecordText(source, target, text))
3469
4619
  },
4620
+ // Its inverse: the object a Document views, recovered at its own class.
4621
+ {
4622
+ id: 'document-viewed-object',
4623
+ apply: (source, target, text) => claimed(documentViewedObjectText(source, target, text))
4624
+ },
3470
4625
  // An Array of one element carrier copied into an Array of another, each
3471
4626
  // element through its own conversion. A copy, so only for an array that is
3472
4627
  // not written through both names afterwards: a matcher table built once
@@ -3546,14 +4701,15 @@ export const conversionChain = [
3546
4701
  // All three `[[PromiseState]]` values are carried: a rejection moves the
3547
4702
  // `exception_ptr` (the thrown carrier is the same on both sides), an unsettled
3548
4703
  // promise stays unsettled, and a `Promise<void>` on either side has no
3549
- // `value()`, which is why a void payload against a richer one refuses.
4704
+ // `value()`. A void source supplies undefined to unit or unknown payloads;
4705
+ // other richer payloads still refuse.
3550
4706
  //
3551
4707
  // `Promise<void>` against `Promise<undefined>` is the exception, and not a
3552
4708
  // hole being papered over: the two are one run-time promise wearing two
3553
4709
  // TypeScript types (ECMA-262 27.2.1.4 fulfils a promise resolved with
3554
4710
  // nothing with `undefined`, which `cppResultTypeOf` elides for `void`), so
3555
4711
  // the state crosses and the unit value is supplied or dropped. That recipe
3556
- // links through `observe` rather than snapshotting a settled state, because
4712
+ // awaits the source rather than snapshotting a settled state, because
3557
4713
  // its source is routinely still PENDING -- `@hono/node-server`'s
3558
4714
  // `responseViaCache` awaits inside -- and a snapshot of a pending promise is
3559
4715
  // a target nothing ever settles.
@@ -3573,16 +4729,15 @@ export const conversionChain = [
3573
4729
  return undefined;
3574
4730
  const bottomSource = source.value.kind === 'void' && source.value.bottom === true;
3575
4731
  if (!bottomSource && (source.value.kind === 'void' || target.value.kind === 'void')) {
3576
- if (!isUnitPromisePayload(source.value) || !isUnitPromisePayload(target.value))
4732
+ if (!isUnitPromisePayload(source.value) || !acceptsVoidPromisePayload(target.value))
3577
4733
  return undefined;
3578
- return (`([&]() -> ${cppTypeOf(target)} { const auto& ${promiseSourceName} = ${text}; ` +
3579
- `if (${promiseSourceName}.rejected()) return ${cppTypeOf(target)}::rejected_with(${promiseSourceName}.rejection()); ` +
3580
- `${cppTypeOf(target)} ${promiseTargetName}; ` +
3581
- `${promiseSourceName}.observe([${promiseTargetName}](auto&&...) mutable ` +
3582
- `{ ${promiseTargetName}.resolve(${target.value.kind === 'void' ? '' : cppUndefinedValue}); }, ` +
3583
- `[${promiseTargetName}](const std::exception_ptr& ${promiseRejectionName}) mutable ` +
3584
- `{ ${promiseTargetName}.reject(${promiseRejectionName}); }); ` +
3585
- `return ${promiseTargetName}; }())`);
4734
+ const fulfillment = target.value.kind === 'void' ? '' : target.value.kind === 'dynamic' ? 'gea::Value()' : cppUndefinedValue;
4735
+ // The coroutine parameter owns a pending source until settlement.
4736
+ // Registering an observer alone would discard the sole strong handle
4737
+ // to an async call's result; its frame deliberately only watches it.
4738
+ // A noncapturing lambda keeps ownership in the frame, not its closure.
4739
+ return (`([](${cppTypeOf(source)} ${promiseSourceName}) -> ${cppTypeOf(target)} ` +
4740
+ `{ co_await ${promiseSourceName}; co_return${fulfillment === '' ? '' : ` ${fulfillment}`}; }(${text}))`);
3586
4741
  }
3587
4742
  if (source.value.kind === 'void') {
3588
4743
  if (source.value.bottom !== true)
@@ -3591,41 +4746,21 @@ export const conversionChain = [
3591
4746
  `if (${promiseSourceName}.rejected()) return ${cppTypeOf(target)}::rejected_with(${promiseSourceName}.rejection()); ` +
3592
4747
  `${cppTypeOf(target)} ${promiseTargetName}; ` +
3593
4748
  `${promiseSourceName}.observe([]() {}, [${promiseTargetName}](const std::exception_ptr& ${promiseRejectionName}) mutable ` +
3594
- `{ ${promiseTargetName}.reject(${promiseRejectionName}); }); ` +
4749
+ `{ ${promiseTargetName}.rejectInline(${promiseRejectionName}); }); ` +
3595
4750
  `return ${promiseTargetName}; }())`);
3596
4751
  }
3597
- const settledPayload = convertedValueText(source.value, target.value, `${promiseSourceName}.value()`);
3598
- if (settledPayload === null)
3599
- return undefined;
3600
- const pendingPayload = convertedValueText(source.value, target.value, promiseValueName);
3601
- if (pendingPayload === null)
3602
- return undefined;
3603
- // A source still PENDING links through `observe`, exactly as the unit
3604
- // recipe above does and for the same reason: hono's `#cachedBody` is one
3605
- // callable returning `Promise<string | ArrayBuffer | Blob | ...>` that
3606
- // every reader (`text()`, `json()`, `formData()`) adapts to its own
3607
- // `Promise<T>` at the call, and the promise it hands back is the body
3608
- // read that has not arrived yet. Snapshotting it (`if (!settled()) return
3609
- // Target()`) minted a target nothing ever settled -- every `await
3610
- // c.req.json()` hung and the POST never answered. The conversion runs
3611
- // when the value exists; a conversion that throws (a dynamic arm not of
3612
- // the declared type) becomes the target's rejection, which is what the
3613
- // same failure inside a `then` handler is.
3614
- return (`([&]() -> ${cppTypeOf(target)} { const auto& ${promiseSourceName} = ${text}; ` +
3615
- `if (${promiseSourceName}.rejected()) return ${cppTypeOf(target)}::rejected_with(${promiseSourceName}.rejection()); ` +
3616
- `if (${promiseSourceName}.settled()) return ${cppTypeOf(target)}(${settledPayload}); ` +
3617
- `${cppTypeOf(target)} ${promiseTargetName}; ` +
3618
- `${promiseSourceName}.observe([${promiseTargetName}](const ${cppTypeOf(source.value)}& ${promiseValueName}) mutable ` +
3619
- `{ try { ${promiseTargetName}.resolve(${pendingPayload}); } catch (...) { ${promiseTargetName}.reject(std::current_exception()); } }, ` +
3620
- `[${promiseTargetName}](const std::exception_ptr& ${promiseRejectionName}) mutable ` +
3621
- `{ ${promiseTargetName}.reject(${promiseRejectionName}); }); ` +
3622
- `return ${promiseTargetName}; }())`);
4752
+ return claimed(promiseAdoptionText(source, target, text, (value) => convertedValueText(source.value, target.value, value)));
3623
4753
  }
3624
4754
  },
3625
4755
  // A TypeScript boundary does not call an ECMAScript abstract operation. A
3626
4756
  // dynamic source enters every typed carrier through its exact checked load;
3627
4757
  // String/Number, arithmetic, templates and property keys render their own
3628
4758
  // coercions at their semantic sites.
4759
+ // Before `widened-store`, which reaches the same arm through the same
4760
+ // helper: this step exists so the census names the pair by its own
4761
+ // (allocating) recipe rather than as a plain arm store.
4762
+ { id: 'readonly-map-view', apply: (source, target, text) => claimed(readOnlyMapViewStoreText(target, source, text)) },
4763
+ { id: 'dynamic-map-arm-view', apply: (source, target, text) => claimed(dynamicMapArmViewStoreText(target, source, text)) },
3629
4764
  { id: 'dynamic-unbox', apply: (source, target, text) => (source.kind === 'dynamic' ? unboxedLoadText(target, text) : undefined) },
3630
4765
  // A String OBJECT reconciled against the `string` primitive its alias widens
3631
4766
  // to (hono's `HtmlEscapedString`). Before the two general paths for the same
@@ -3654,8 +4789,13 @@ export const conversionChain = [
3654
4789
  {
3655
4790
  id: 'unreachable-value',
3656
4791
  apply: (source, target, text) => {
4792
+ // A sum holds an absence only through an arm that does: a
4793
+ // `tagged-union(array-buffer|typed-array|native-record-ref)` has no
4794
+ // arm for `undefined` to widen into, so an `undefined` reaching it is
4795
+ // `never`'s (bson's `ObjectId` normalizes a view it already narrowed to
4796
+ // `Uint8Array`, src/objectid.ts:226).
3657
4797
  const holdsAbsence = (carrier) => carrier.kind === 'optional' ||
3658
- carrier.kind === 'tagged-union' ||
4798
+ (carrier.kind === 'tagged-union' && carrier.arms.some((arm) => holdsAbsence(arm.value))) ||
3659
4799
  carrier.kind === 'dynamic' ||
3660
4800
  carrier.kind === 'undefined' ||
3661
4801
  carrier.kind === 'null' ||
@@ -3715,7 +4855,139 @@ export const alignedValueText = (ctx, site, source, target, text) => {
3715
4855
  * (`convertedValueText`) is deliberately ctx-free -- see `algebra.ts`'s doc
3716
4856
  * on the kind for why an `atom` cannot carry this recipe.
3717
4857
  */
3718
- export const recipeText = (ctx, node, text) => {
4858
+ /**
4859
+ * A named interface -- `native-record-ref`, which names its layout rather than
4860
+ * carrying it -- read out of a dynamic value, at the top or as the element of
4861
+ * an Array: the layout is resolved here, where the layouts are in hand, and
4862
+ * the read is `unboxedLoadText`'s own record conversion (checked product,
4863
+ * Document adoption, TypeError). The ctx-free chain would otherwise read the
4864
+ * name back by identity alone, which aborts on every JSON or BSON document.
4865
+ */
4866
+ const dynamicNamedRecordText = (layouts, source, target, text) => {
4867
+ if (source.kind !== 'dynamic' || source.reason === 'untyped-callable')
4868
+ return null;
4869
+ const expanded = expandedNamedRecords(layouts, target, new Set());
4870
+ return expanded === null ? null : unboxedLoadText(expanded, text);
4871
+ };
4872
+ /**
4873
+ * A declared `any` read into `target` where no conversion node was minted --
4874
+ * a boxed struct's field dispatcher writing a member (`records.ts`). The same
4875
+ * two recipes a census `dynamic -> target` node renders, in the same order: a
4876
+ * named interface expands to its layout first, so a box that is not already
4877
+ * the target's struct is rebuilt by the checked record product rather than
4878
+ * refused by identity; everything else is the generic load.
4879
+ */
4880
+ export const dynamicValueLoadText = (layouts, target, text) => dynamicNamedRecordText(layouts, { kind: 'dynamic', reason: 'declared-any-never-narrowed' }, target, text) ?? unboxedLoadText(target, text);
4881
+ /**
4882
+ * An `any` entering a union one arm of which is a native Proxy: mongodb's
4883
+ * deps.ts `kerberos = require('kerberos')` into `Module | { kModuleError }`,
4884
+ * a slot `makeErrorModule(...)`'s Proxy also fills. No box holds a native
4885
+ * Proxy (`dynamicTagFor` refuses one, and `conversion/derive.ts` skips the
4886
+ * arm), so the proxy arm is never the destination. Every other arm must be a
4887
+ * record the checked dynamic record conversion builds: a box holding that
4888
+ * record's own struct lands in it by identity first; then an object holding
4889
+ * every key a record arm requires is adopted as that arm (Document adoption,
4890
+ * field checks and all, `unboxedLoadText`); anything else is the TypeError a
4891
+ * program may catch. The union is never boxed.
4892
+ */
4893
+ const dynamicIntoProxyArmUnionText = (layouts, source, target, text) => {
4894
+ if (source.kind !== 'dynamic' || source.reason === 'untyped-callable')
4895
+ return null;
4896
+ if (target.kind !== 'tagged-union')
4897
+ return null;
4898
+ // A union of records alone is the same read: a box holding another
4899
+ // instantiation's layout of the same interface (`AnyBulkWriteOperation<T>`
4900
+ // at two `T`s) carries a different struct, so identity picks no arm and the
4901
+ // exact-payload chain aborts on a value the type admits. The arm whose
4902
+ // required keys the object holds is rebuilt, nested named records included.
4903
+ const recordArms = target.arms.every((arm) => arm.value.kind === 'proxy-object' || arm.value.kind === 'record' || arm.value.kind === 'native-record-ref');
4904
+ if (!recordArms || target.arms.length < 2)
4905
+ return null;
4906
+ const holder = 'gea_dynamic_module';
4907
+ const targetType = cppTypeOf(target);
4908
+ const arms = [];
4909
+ for (const [index, arm] of target.arms.entries()) {
4910
+ if (arm.value.kind === 'proxy-object')
4911
+ continue;
4912
+ const named = arm.value.kind === 'native-record-ref' ? expandedNamedRecords(layouts, arm.value, new Set()) : arm.value;
4913
+ // A record arm's own named-record fields expand too: a box of another
4914
+ // layout is rebuilt field by field, so a nested interface must be rebuilt
4915
+ // rather than demanded by identity (`dynamicFieldAdmissionText`).
4916
+ const record = named !== null && (named.kind === 'record' || named.kind === 'record-with-index')
4917
+ ? {
4918
+ ...named,
4919
+ fields: named.fields.map((field) => {
4920
+ const value = expandedNamedRecords(layouts, field.value, new Set([named.shapeId]));
4921
+ return value === null ? field : { ...field, value };
4922
+ })
4923
+ }
4924
+ : named;
4925
+ if (record === null || !adoptsDynamicRecord(record) || (record.kind !== 'record' && record.kind !== 'record-with-index'))
4926
+ return null;
4927
+ if (record.fields.some((field) => field.required && cppRecordFieldKeyIsSymbol(field.key)))
4928
+ return null;
4929
+ const load = unboxedLoadText(record, holder);
4930
+ if (load === null)
4931
+ return null;
4932
+ arms.push({
4933
+ index,
4934
+ exact: `gea::detail::payloadTypeTagFor<${cppTypeOf(arm.value)}>()`,
4935
+ required: record.fields.filter((field) => field.required).map((field) => field.key),
4936
+ load
4937
+ });
4938
+ }
4939
+ if (arms.length === 0)
4940
+ return null;
4941
+ const object = `(${holder}.tag() == gea::Value::Tag::Object || ${holder}.tag() == gea::Value::Tag::Function)`;
4942
+ const exact = arms.map(({ index, exact: payload, load }) => `if (${holder}.tag() == gea::Value::Tag::Object && ${holder}.payloadType() == ${payload}) return ${targetType}::ofArm<${index}>(${load});`);
4943
+ const structural = arms.map(({ index, required, load }) => {
4944
+ const keys = required.map((key) => `gea::detail::dynamicRecordHasField(${holder}, ${cppStringLiteral(key)})`);
4945
+ return `if (${[object, ...keys].join(' && ')}) return ${targetType}::ofArm<${index}>(${load});`;
4946
+ });
4947
+ return (`[](const gea::Value& ${holder}) -> ${targetType} { ${[...exact, ...structural].join(' ')} ` +
4948
+ `gea::host::throwRuntimeError("TypeError", ${cppStringLiteral("a dynamic value is none of the union's object arms")}); }(${text})`);
4949
+ };
4950
+ /**
4951
+ * `target` with every compiler-owned named record it reads by value expanded
4952
+ * to its layout (fields expanded the same way), or `null` when it names none.
4953
+ * A shape already being expanded stays a name: a recursive layout reads its
4954
+ * inner occurrence by identity, as before.
4955
+ */
4956
+ const expandedNamedRecords = (layouts, target, open) => {
4957
+ if (target.kind === 'optional') {
4958
+ const payload = expandedNamedRecords(layouts, target.payload, open);
4959
+ return payload === null ? null : { ...target, payload };
4960
+ }
4961
+ if (target.kind === 'array-object') {
4962
+ if (target.extension !== null)
4963
+ return null;
4964
+ const element = expandedNamedRecords(layouts, target.element, open);
4965
+ return element === null ? null : { ...target, element };
4966
+ }
4967
+ if (target.kind !== 'native-record-ref' || target.native !== null || target.recursive || target.ownership !== 'shared-refcount')
4968
+ return null;
4969
+ if (open.has(target.shapeId))
4970
+ return null;
4971
+ const fields = layouts.forShape(target.shapeId);
4972
+ if (fields === null || (layouts.accessorsForShape?.(target.shapeId)?.length ?? 0) !== 0)
4973
+ return null;
4974
+ open.add(target.shapeId);
4975
+ const expandedFields = fields.map((field) => {
4976
+ const value = expandedNamedRecords(layouts, field.value, open);
4977
+ return value === null ? field : { ...field, value };
4978
+ });
4979
+ open.delete(target.shapeId);
4980
+ const indexes = layouts.indexesForShape?.(target.shapeId) ?? [];
4981
+ return indexes.length === 0
4982
+ ? { kind: 'record', shapeId: target.shapeId, fields: expandedFields, accessors: [], ownership: target.ownership }
4983
+ : { kind: 'record-with-index', shapeId: target.shapeId, fields: expandedFields, indexes, ownership: target.ownership };
4984
+ };
4985
+ /**
4986
+ * The recipe's text with its source evaluated once, however many times the
4987
+ * recipe names it -- see `evaluated-once.ts`.
4988
+ */
4989
+ export const recipeText = (ctx, node, text) => evaluatedOnceText(text, (operand) => renderedRecipeText(ctx, node, operand));
4990
+ const renderedRecipeText = (ctx, node, text) => {
3719
4991
  if (node.capability.kind === 'identity')
3720
4992
  return text;
3721
4993
  if (node.capability.kind === 'never')
@@ -3724,6 +4996,16 @@ export const recipeText = (ctx, node, text) => {
3724
4996
  return coercionText(node.capability.operation, text, node.source, ctx.layouts);
3725
4997
  if (node.capability.kind === 'class-family')
3726
4998
  return classFamilyLoadText(ctx, node.source, node.target, text);
4999
+ // A callable the emitter saw allocated, adapted to another result convention.
5000
+ if ((node.capability.kind === 'atom' || node.capability.kind === 'static') &&
5001
+ node.capability.materializer.id === 'gea::CallableObject::result-adapter') {
5002
+ const known = ctx.knownCallableEntry?.(text) ?? null;
5003
+ if (known !== null) {
5004
+ const adapted = resultAdaptedCallableText(node.source, node.target, text, undefined, known);
5005
+ if (adapted !== null)
5006
+ return adapted;
5007
+ }
5008
+ }
3727
5009
  // `conversions.ts`'s read of a structural value as a class nothing instantiates.
3728
5010
  if (node.capability.kind === 'atom' && node.capability.materializer.id === 'gea::host::unreachableValue')
3729
5011
  return `((void)(${text}), gea::host::unreachableValue<${cppTypeOf(node.target)}>())`;
@@ -3732,6 +5014,46 @@ export const recipeText = (ctx, node, text) => {
3732
5014
  // carried on the node.
3733
5015
  if (node.capability.kind === 'static' && node.capability.materializer.id === EXACT_ARM_MATERIALIZER)
3734
5016
  return `gea::host::exactArm<${exactArmIndexOf(node.source, node.target)}>(${text})`;
5017
+ // The census's native-base view (`nodes.ts`'s `nativeBaseViewFor`).
5018
+ if (node.capability.kind === 'static' && node.capability.materializer.id === NATIVE_BASE_VIEW_MATERIALIZER)
5019
+ return node.target.kind === 'promise'
5020
+ ? // The runtime promise is a handle over shared state, not a `Ref`: the
5021
+ // view copies the base subobject, which settles as the instance does.
5022
+ `${cppTypeOf(node.target)}(static_cast<const ${cppTypeOf(node.target)}&>(*(${text})))`
5023
+ : `${cppTypeOf(node.target)}(${text})`;
5024
+ // The census's asserted-union dispatch (`nodes.ts`'s `assertedUnionFor`).
5025
+ if (node.capability.kind === 'static' && node.capability.materializer.id === ASSERTED_UNION_MATERIALIZER)
5026
+ return assertedUnionText(node.source, node.target, text, false);
5027
+ if (node.capability.kind === 'static' && node.capability.materializer.id === ASSERTED_UNION_COPY_MATERIALIZER)
5028
+ return assertedUnionText(node.source, node.target, text, true);
5029
+ // The census's per-arm view (`nodes.ts`'s `armViewFor`).
5030
+ if (node.capability.kind === 'static' && node.capability.materializer.id === ARM_VIEW_MATERIALIZER)
5031
+ return armViewText(node.source, node.target, text);
5032
+ // The census's nullish `any` into an optional parameter (`nodes.ts`'s `nullishOptionalFor`).
5033
+ if (node.capability.kind === 'static' &&
5034
+ node.capability.materializer.id === NULLISH_OPTIONAL_MATERIALIZER &&
5035
+ node.target.kind === 'optional') {
5036
+ const optionalType = cppTypeOf(node.target);
5037
+ const payload = dynamicValueLoadText(ctx.layouts, node.target.payload, 'gea_nullish');
5038
+ if (payload === null)
5039
+ return null;
5040
+ return (`[](const gea::Value& gea_nullish) -> ${optionalType} { return gea_nullish.tag() == gea::Value::Tag::Null || ` +
5041
+ `gea_nullish.tag() == gea::Value::Tag::Undefined ? ${optionalType}() : ${optionalType}(${payload}); }(${text})`);
5042
+ }
5043
+ // The census's caught-value handoff (`nodes.ts`'s `caughtHandoffFor`).
5044
+ if (node.capability.kind === 'static' &&
5045
+ node.capability.materializer.id === CAUGHT_HANDOFF_MATERIALIZER &&
5046
+ node.target.kind === 'class-ref')
5047
+ return `gea::detail::unboxCaughtClassRef<${cppClassName(node.target.declaration)}>(${text})`;
5048
+ // `conversions.ts`'s last resort for a union some arms of which have no home.
5049
+ if (node.capability.kind === 'static' && node.capability.materializer.id === CHECKED_ARM_NARROWING)
5050
+ return checkedArmNarrowingText(node.source, node.target, text);
5051
+ // `conversions.ts`'s callable adapter whose parameters need the layouts.
5052
+ if (node.capability.kind === 'static' && node.capability.materializer.id === VIEW_ADAPTED_CALLABLE)
5053
+ return resultAdaptedCallableText(node.source, node.target, text, (source, target, value) => structuralRecordViewText(ctx, source, target, value));
5054
+ // The census's family-member view (`nodes.ts`'s `familyMemberViewFor`).
5055
+ if (node.capability.kind === 'static' && node.capability.materializer.id === FAMILY_MEMBER_VIEW_MATERIALIZER)
5056
+ return node.familyMembers === undefined ? null : familyMemberViewText(ctx, node.source, node.target, node.familyMembers, text);
3735
5057
  // `conversions.ts`'s read of a class instance's structural view as the class: the boxed origin, narrowed.
3736
5058
  if (node.capability.kind === 'atom' && node.capability.materializer.id === 'gea::record::viewOrigin')
3737
5059
  return narrowedLoadText({ kind: 'dynamic', reason: 'declared-any-never-narrowed' }, node.target, node.source.kind === 'optional'
@@ -3743,6 +5065,64 @@ export const recipeText = (ctx, node, text) => {
3743
5065
  ? `${helper.name}(${text})`
3744
5066
  : nativeSelectionText(node.capability.materializer.nativeSelection, node.source, node.target, text);
3745
5067
  }
5068
+ // A named interface poured into a dictionary: the chain is ctx-free and a
5069
+ // `native-record-ref` only names its layout, so the field list is resolved
5070
+ // here, the same way `conversions.ts` admitted the pair.
5071
+ if ((node.capability.kind === 'static' || node.capability.kind === 'atom') &&
5072
+ node.capability.materializer.id === 'gea::record::recastToDictionary' &&
5073
+ node.source.kind === 'native-record-ref' &&
5074
+ node.target.kind === 'dictionary') {
5075
+ const fields = ctx.layouts.forShape(node.source.shapeId);
5076
+ if (fields === null)
5077
+ return null;
5078
+ return recastedRecordToDictionaryText({ kind: 'record', shapeId: node.source.shapeId, ownership: node.source.ownership, fields, accessors: [] }, node.target, text, cppTypeOf(node.source));
5079
+ }
5080
+ if ((node.capability.kind === 'static' || node.capability.kind === 'atom') &&
5081
+ (node.capability.materializer.id === INDEXED_RECORD_TO_DICTIONARY ||
5082
+ node.capability.materializer.id === INDEXED_RECORD_INTO_DICTIONARY_ARM)) {
5083
+ const view = indexedRecordViewOf(node.source, ctx.layouts);
5084
+ if (view === null)
5085
+ return null;
5086
+ if (node.target.kind === 'dictionary')
5087
+ return recastedIndexedRecordToDictionaryText(view, node.target, text, cppTypeOf(node.source));
5088
+ const arm = indexedRecordDictionaryArmOf(view, node.target);
5089
+ if (arm === null || node.target.kind !== 'tagged-union')
5090
+ return null;
5091
+ const armTarget = node.target.arms[arm].value;
5092
+ if (armTarget.kind !== 'dictionary')
5093
+ return null;
5094
+ const poured = recastedIndexedRecordToDictionaryText(view, armTarget, text, cppTypeOf(node.source));
5095
+ return poured === null ? null : `${cppTypeOf(node.target)}::ofArm<${arm}>(${poured})`;
5096
+ }
5097
+ if ((node.capability.kind === 'static' || node.capability.kind === 'atom') &&
5098
+ node.capability.materializer.id === CONSTRUCTOR_STATIC_VIEW) {
5099
+ return constructorStaticViewText(node.source, node.target, text);
5100
+ }
5101
+ if ((node.capability.kind === 'static' || node.capability.kind === 'atom') &&
5102
+ node.capability.materializer.id === DYNAMIC_DICTIONARY_TO_NAMED_RECORD) {
5103
+ const named = node.target.kind === 'optional' ? node.target.payload : node.target;
5104
+ if (named.kind !== 'native-record-ref')
5105
+ return null;
5106
+ const fields = ctx.layouts.forShape(named.shapeId);
5107
+ if (fields === null)
5108
+ return null;
5109
+ // The census lifts the pair through an optional of the same absence
5110
+ // (`conversions.ts`): the absent state stays absent, the present one adopts.
5111
+ if (node.source.kind === 'optional') {
5112
+ if (node.target.kind !== 'optional' || node.source.absence !== node.target.absence)
5113
+ return null;
5114
+ const present = documentAdoptionText(node.source.payload, named, fields, '(*gea_document)');
5115
+ if (present === null)
5116
+ return null;
5117
+ const targetType = cppTypeOf(node.target);
5118
+ return (`[](const ${cppTypeOf(node.source)}& gea_document) -> ${targetType} { ` +
5119
+ `return gea_document.has_value() ? ${targetType}(${present}) : ${targetType}(); }(${text})`);
5120
+ }
5121
+ const adopted = documentAdoptionText(node.source, named, fields, text);
5122
+ if (adopted === null || named === node.target)
5123
+ return adopted;
5124
+ return `${cppTypeOf(node.target)}(${adopted})`;
5125
+ }
3746
5126
  // A view that DISPATCHES on a sum's live arm is rendered ahead of the
3747
5127
  // chain: the chain would select the exact arm and trust a narrowing that,
3748
5128
  // at a store, never happened (`narrowedLoadText`'s arm search says why).
@@ -3751,7 +5131,65 @@ export const recipeText = (ctx, node, text) => {
3751
5131
  const view = viewPlanFor(ctx.layouts, node.source, node.target);
3752
5132
  if (view !== null && recordViewDispatchesArms(view))
3753
5133
  return structuralRecordViewText(ctx, node.source, node.target, text);
5134
+ // A whole-sum recast the census chose over the chain: the chain declined
5135
+ // the pair (some source arm only WIDENS into the target, so its
5136
+ // arm-selecting load would drop that arm -- `taggedUnionArmText`'s
5137
+ // `partialWidening`), and the view homes every arm. Rendering the chain
5138
+ // here would contradict the node.
5139
+ if (unionRecastPlanOf(ctx.layouts, node.source, node.target) !== null)
5140
+ return structuralRecordViewText(ctx, node.source, node.target, text);
5141
+ }
5142
+ // A boxed fulfilment read as a NAMED interface: the layout is resolved here,
5143
+ // where the layouts are, exactly as a plain `any -> T` read is
5144
+ // (`dynamicNamedRecordText`). mongodb's `findOne` settles
5145
+ // `Promise<WithId<TSchema> | null>` with a deserialized BSON Document, and
5146
+ // the ctx-free chain read the interface back by identity alone, aborting on
5147
+ // every document ("an assertion out of a dynamic value").
5148
+ if (node.source.kind === 'promise' && node.target.kind === 'promise') {
5149
+ const promiseSource = node.source;
5150
+ const promiseTarget = node.target;
5151
+ if (dynamicNamedRecordText(ctx.layouts, promiseSource.value, promiseTarget.value, promiseValueName) !== null)
5152
+ return promiseAdoptionText(promiseSource, promiseTarget, text, (value) => dynamicNamedRecordText(ctx.layouts, promiseSource.value, promiseTarget.value, value));
5153
+ }
5154
+ // State adoption whose payload only a record view carries: the chain's own
5155
+ // `promise-payload` step asks the ctx-free chain for the payload and cannot
5156
+ // see the view, which needs the layouts (`conversions.ts`'s `recasting`
5157
+ // admits the pair on the same plan).
5158
+ if (node.capability.kind === 'atom' &&
5159
+ node.capability.materializer.id === 'gea::Promise::adopt-converted' &&
5160
+ node.source.kind === 'promise' &&
5161
+ node.target.kind === 'promise') {
5162
+ const promiseSource = node.source;
5163
+ const promiseTarget = node.target;
5164
+ const source = promiseSource.value;
5165
+ const target = promiseTarget.value;
5166
+ // A view that dispatches -- `IteratorResult`'s arm read off `done` -- wins
5167
+ // over the chain, which would pick one arm statically.
5168
+ const view = viewPlanFor(ctx.layouts, source, target);
5169
+ const viewed = () => promiseAdoptionText(promiseSource, promiseTarget, text, (value) => structuralRecordViewText(ctx, source, target, value));
5170
+ if (view !== null && recordViewDispatchesArms(view))
5171
+ return viewed();
5172
+ const chained = convertedValueText(node.source, node.target, text);
5173
+ if (chained !== null)
5174
+ return chained;
5175
+ return view === null ? null : viewed();
3754
5176
  }
5177
+ const adopted = dynamicNamedRecordText(ctx.layouts, node.source, node.target, text);
5178
+ if (adopted !== null)
5179
+ return adopted;
5180
+ const module = dynamicIntoProxyArmUnionText(ctx.layouts, node.source, node.target, text);
5181
+ if (module !== null)
5182
+ return module;
5183
+ if (node.capability.kind === 'atom' && node.capability.materializer.id === PROTOCOL_ITERATOR)
5184
+ return protocolIteratorText(ctx, node.source, node.target, text);
5185
+ if (node.capability.kind === 'atom' && node.capability.materializer.id === ITERATOR_OBJECT_VIEW)
5186
+ return iteratorObjectViewText(ctx, node.source, node.target, text);
5187
+ if (node.capability.kind === 'atom' && node.capability.materializer.id === ITERABLE_OBJECT_VIEW)
5188
+ return iterableObjectViewText(ctx, node.source, node.target, text);
5189
+ if (node.capability.kind === 'atom' && node.capability.materializer.id === CONSTRUCTOR_IDENTITY_FAMILY)
5190
+ return constructorIdentityFamilyText(ctx, node.source, node.target, text);
5191
+ if (node.capability.kind === 'atom' && node.capability.materializer.id === CONSTRUCTOR_DISPATCH_FAMILY)
5192
+ return constructorDispatchFamilyText(ctx, node.source, node.target, text);
3755
5193
  return convertedValueText(node.source, node.target, text) ?? structuralRecordViewText(ctx, node.source, node.target, text);
3756
5194
  };
3757
5195
  /**
@@ -3778,6 +5216,8 @@ export const namedConversionText = (ctx, site, node, text) => {
3778
5216
  export const convertedValueText = (source, target, text) => {
3779
5217
  if (representationKey(source) === representationKey(target))
3780
5218
  return text;
5219
+ if (standInRefuses(source, target))
5220
+ return null;
3781
5221
  // A void TARGET is the language's explicit discard conversion. The source
3782
5222
  // operation has already evaluated its effects; this expression preserves a
3783
5223
  // valid C++ void value for callers that return or forward the conversion,
@@ -3794,7 +5234,7 @@ export const convertedValueText = (source, target, text) => {
3794
5234
  const bottom = [...walkRepresentation(source), ...walkRepresentation(target)].find((f) => f.kind === 'unresolved');
3795
5235
  throw createCppEmitBlockedError(`conversion:${representationKey(source)}->${representationKey(target)}`, `reconciles against ${bottom?.reason ?? 'an unresolved representation'}`);
3796
5236
  }
3797
- return runConversionChain(source, target, text).text;
5237
+ return evaluatedOnceText(text, (operand) => runConversionChain(source, target, operand).text);
3798
5238
  };
3799
5239
  /**
3800
5240
  * Which chain step answers a pair, decided by running the chain on a
@@ -3841,10 +5281,10 @@ export const conversionRecipeOf = (source, target) => {
3841
5281
  return { id: 'discard-into-void', renders: true };
3842
5282
  if (source.kind === 'void' || containsUnresolved(source) || containsUnresolved(target))
3843
5283
  return null;
3844
- const probed = tryCandidateText(() => {
5284
+ const probed = withoutUnitFunctions(() => tryCandidateText(() => {
3845
5285
  const outcome = runConversionChain(source, target, 'gea_conversion_probe');
3846
5286
  return outcome.step === null ? null : `${outcome.step.id}\u0000${outcome.text === null ? '' : 'renders'}`;
3847
- });
5287
+ }));
3848
5288
  if (probed === null)
3849
5289
  return null;
3850
5290
  const [id, renders] = probed.split('\u0000');
@@ -3870,8 +5310,13 @@ export const conversionRecipeOf = (source, target) => {
3870
5310
  const ownsItsStorage = (carrier) => {
3871
5311
  if (carrier.kind === 'string')
3872
5312
  return true;
3873
- if (carrier.kind === 'class-ref')
3874
- return carrier.ownership === 'shared-refcount';
5313
+ // A box is three counted handles (`gea::Value`'s function, class and held
5314
+ // payload references) plus a tag: copying one is three retain/release
5315
+ // pairs, moving one is a 48-byte copy and three nulled sources. The bson
5316
+ // serializer's per-key loop read each document value into a cell it never
5317
+ // read again, and paid the three pairs per key.
5318
+ if (carrier.kind === 'dynamic')
5319
+ return true;
3875
5320
  if (carrier.kind === 'optional')
3876
5321
  return ownsItsStorage(carrier.payload);
3877
5322
  // A sum owns whatever its live arm owns. `gea::TaggedUnion` has a real move
@@ -3881,7 +5326,25 @@ const ownsItsStorage = (carrier) => {
3881
5326
  // `writeHead`, where this was three heap copies of one content-type string.
3882
5327
  if (carrier.kind === 'tagged-union')
3883
5328
  return carrier.arms.some((arm) => ownsItsStorage(arm.value));
3884
- return false;
5329
+ // Every counted handle, not only a class instance: a record, an Array, a
5330
+ // typed array or a dictionary is the same `gea::Ref` with the same
5331
+ // retain/release pair, and a promise or callable object owns one inside.
5332
+ if ('ownership' in carrier)
5333
+ return carrier.ownership === 'shared-refcount';
5334
+ // Every callable and constructor carrier is a `CallableObject`,
5335
+ // `ConstructorObject` or `CallableConstructorObject`: an environment and an
5336
+ // identity handle each. Only `function` was listed, so a function
5337
+ // declaration that needs its identity (`function-value-dispatch`, what
5338
+ // `emitter.off(handler)` makes of a hoisted handler) was copied into its
5339
+ // own cell -- two retain/release pairs per closure, per mongodb operation
5340
+ // for every listener `onData` installs.
5341
+ if (isNativeCallableCarrier(carrier.kind))
5342
+ return true;
5343
+ return (carrier.kind === 'promise' ||
5344
+ carrier.kind === 'callable-identity' ||
5345
+ carrier.kind === 'constructor-family' ||
5346
+ carrier.kind === 'constructor-value-dispatch' ||
5347
+ carrier.kind === 'constructor-identity');
3885
5348
  };
3886
5349
  /**
3887
5350
  * A DYING refcounted value moves into the slot that takes it rather than being
@@ -3897,7 +5360,7 @@ const ownsItsStorage = (carrier) => {
3897
5360
  * make cheaper.
3898
5361
  */
3899
5362
  export const movedValueText = (ctx, value, held, text) => {
3900
- if (transferOf(ctx.dyingArguments, ctx.ownedValues, ctx.ownedDyingValues, value.value) !== 'move')
5363
+ if (transferOf(ctx.dyingArguments, ctx.ownedValues, ctx.transferDyingValues, value.value, ctx.receiverRenames) !== 'move')
3901
5364
  return text;
3902
5365
  // A value the emitter withheld renders as its own expression, not as a cell:
3903
5366
  // `f(std::move((a->elementAtIndex(i))))` moves a prvalue, which gcc rejects
@@ -3912,7 +5375,19 @@ export const movedValueText = (ctx, value, held, text) => {
3912
5375
  // serializer had just built into the cell that names it, once per call.
3913
5376
  if (!ownsItsStorage(carrier))
3914
5377
  return text;
3915
- if (held !== null && representationKey(held) !== representationKey(carrier))
5378
+ // Two representations can spell one C++ type -- an identified callable and
5379
+ // the plain function slot it is stored into are both the same
5380
+ // `gea::CallableObject<...>` -- and moving between them is a move of one
5381
+ // type into itself. Only the value's own name moves that way; a text some
5382
+ // conversion produced is already a temporary.
5383
+ if (held !== null &&
5384
+ representationKey(held) !== representationKey(carrier) &&
5385
+ !(text === operandText(ctx, value) && cppTypeOf(held) === cppTypeOf(carrier)))
5386
+ return text;
5387
+ // Two renderers on one argument's path each ask this (a sum-widenable
5388
+ // argument is moved into its widening and then into the slot): the second
5389
+ // wrap would spell `std::move(std::move(x))`, which is the same move.
5390
+ if (text.startsWith('std::move(') && text.endsWith(')'))
3916
5391
  return text;
3917
5392
  return `std::move(${text})`;
3918
5393
  };