@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,17 +1,25 @@
1
- import { receivableArguments } from '../../ir/call-entry.js';
1
+ import { proxyArmWithoutHome } from '../../representation/proxy-carriers.js';
2
+ import { hostConstructFrameOf, receivableArguments } from '../../ir/call-entry.js';
2
3
  import { stableBorrowEntryAccepts } from './borrowed-call-entry.js';
3
- import { callableMemberSlot } from '../../ir/callable-member-candidates.js';
4
+ import { callableMemberAlternateSlot, callableMemberSlot } from '../../ir/callable-member-candidates.js';
4
5
  import { transferOf } from '../../ir/transfer.js';
5
6
  import { boxedValueText } from './emit-dynamic-properties.js';
6
7
  import { functionConstructorArgumentKindOf } from '../../representation/function-constructor.js';
7
8
  import { nativeSumWidenable } from './emit-sum-widening.js';
9
+ import { classLayoutsConstructedBy } from '../../projection/classes.js';
10
+ import { classFamilyOverridesOf, virtualDispatchKey } from '../../projection/dispatch.js';
11
+ import { cppVirtualMemberName } from './virtual-methods.js';
8
12
  import { abiKey, representationKey } from '../../representation/model.js';
9
- import { alignedValueText, bindsReceiver, callableObjectAbi, movedValueText, unboxedLoadText } from './emit-narrowing.js';
13
+ import { alignedValueText, bindsReceiver, callableObjectAbi, movedValueText, recipeText, unboxedLoadText } from './emit-narrowing.js';
10
14
  import { memberAccessOperator, reactiveRevisionText } from './emit-carrier-members.js';
11
15
  import { structuralRecordViewText } from './emit-record-view.js';
16
+ import { frameHandleText, sharedGroupMemberText } from './emit-binding-reference.js';
17
+ import { restPacks } from '../../conversion/record-view.js';
18
+ import { abiOfCallee } from '../../projection/callee.js';
12
19
  import { emitDateConstruct, isDateCarrier } from './prototype/emit-prototype-date.js';
13
- import { unwrapPresentValue, bindingReference, cppConstructedThunkName, cppConstructThunkName, cppEnvironmentStructName, cppReceiverName, cppThunkEntryText, cppThunkName, createCppEmitBlockedError, declareCell, defineValue, defineValueAlias, isCppEmitBlockedError, isIntegerStorageValue, operandText, paddedArguments, captureFieldText } from './emit-context.js';
20
+ import { unwrapPresentValue, bindingReference, cppConstructedThunkName, cppConstructThunkName, cppEnvironmentStructName, cppFrameLocalName, cppFrameStructName, cppReceiverName, cppSharedIdentityFieldName, cppThunkEntryText, cppThunkName, createCppEmitBlockedError, declareCell, defineValue, defineValueAlias, isCppEmitBlockedError, isIntegerStorageValue, operandText, paddedArguments, captureFieldText } from './emit-context.js';
14
21
  import { classMemberOf, classStaticMemberOf, cppFieldInitializerStatements, lazyArrowFieldPlanOf } from './class-layout.js';
22
+ import { cellValueText } from './emit-bindings.js';
15
23
  import { declaredRecordFieldOf } from './records.js';
16
24
  import { hostArityCallLines, hostResultText } from './host/emit-host-arity.js';
17
25
  import { hostMemberOf } from './host/host-members.js';
@@ -19,25 +27,34 @@ import { hostCallText, nativeHandleInvocationText } from './host/emit-host-invok
19
27
  import { nativeReflectCallText } from './host/emit-host-reflect.js';
20
28
  import { jsonStringifyFillLines } from './emit-json.js';
21
29
  import { withheldCellOf } from './deferral-safety.js';
22
- import { prototypeMethodCallText } from './prototype/emit-prototype-invoke.js';
30
+ import { nativeBaseMethodCallText, prototypeMethodCallText } from './prototype/emit-prototype-invoke.js';
23
31
  import { mutatingArrayMembers } from './prototype/emit-prototype-array.js';
24
32
  import { regexpRoleOf, regExpConstructionFromObject } from './prototype/emit-prototype-regexp.js';
25
33
  import { cppConstructPatternEntry, cppRegExpNativeTypes } from './regexp-types.js';
26
34
  import { cppErrorNativeType } from './error-types.js';
27
35
  import { isNativeErrorBaseRefusal, nativeErrorBaseInitializeStatements } from './native-error-base.js';
36
+ import { nativeCollectionBaseInitializeStatements } from './native-collection-base.js';
37
+ import { nativePromiseBaseInitializeStatements } from './native-promise-base.js';
28
38
  import { emitArrayBufferConstruct, emitSharedArrayBufferConstruct, emitTextCodecConstruct, emitDataViewConstruct, emitTypedArrayBufferConstruct, typedArrayTargetSpelling } from './emit-buffers.js';
29
39
  import { armAt, armIs } from './emit-union-properties.js';
30
- import { cppAbiType, cppBodyName, cppBoxedType, cppCallableDeclarationTagName, cppClassName, cppConstructName, cppInitializeName, cppRecordFieldName, cppRefcountedReceiver, cppTypeOf, cppUndefinedValue } from './types.js';
40
+ import { cppAbiType, cppBodyName, cppBoxedType, cppCallableDeclarationTagName, cppClassName, cppConstructName, cppInitializeName, cppRecordFieldName, cppRefcountedReceiver, cppStringLiteral, cppTypeOf, cppUndefinedValue } from './types.js';
31
41
  /** `Function.prototype.bind` preserves the native call ABI and captures only evaluated prefix values. */
32
42
  export const emitBindCallable = (ctx, lines, operation) => {
33
43
  if (operation.result.representation.kind !== 'function-value-dispatch') {
34
44
  throw createCppEmitBlockedError('call-abi:bind-callable', 'a bound Function result is not carried as an evaluated function-value dispatch');
35
45
  }
46
+ const guarded = operation.unboxedMethod !== undefined && operation.unboxedMethodConfirmed !== true;
47
+ if (guarded && operation.detached !== false) {
48
+ throw createCppEmitBlockedError('call-abi:bind-shadowable', `"${operation.unboxedMethod.key}" was bound as the builtin Function.prototype.bind on the assumption that no boxed ` +
49
+ `value holds its Function object, and the reflection census did not confirm it: an instance, prototype or ` +
50
+ `constructor of ${String(operation.unboxedMethod.owner)} or a related class reaches dynamic code, where a ` +
51
+ `computed write can shadow "bind"`);
52
+ }
36
53
  if (operation.detached) {
37
54
  // See `BindCallableOperation.detached`: the language calls a detached
38
55
  // method with no receiver, so a body that reads `this` would be answered
39
56
  // where the program would have thrown.
40
- if (operation.sourceFunctionId !== null && ctx.captures.readsReceiver(operation.sourceFunctionId)) {
57
+ if (operation.detached !== 'holder' && operation.sourceFunctionId !== null && ctx.captures.readsReceiver(operation.sourceFunctionId)) {
41
58
  throw createCppEmitBlockedError('call-abi:bind-callable', `passes method ${operation.sourceFunctionId} on as a value, and its body reads \`this\`: the language calls a detached method ` +
42
59
  'with no receiver, so binding the object it was read from would answer where the program would have thrown');
43
60
  }
@@ -45,7 +62,21 @@ export const emitBindCallable = (ctx, lines, operation) => {
45
62
  throw createCppEmitBlockedError('call-abi:bind-callable', 'a detached method bind names no receiver to bind');
46
63
  const bound = alignedText(ctx, operation.sourceAbi.receiver ?? undefined, operation.receiver, 'detached method receiver');
47
64
  const type = cppTypeOf(operation.result.representation);
48
- lines.push(`${defineValue(ctx, operation.result)} = ${type}::bindReceiver(${operandText(ctx, operation.source)}, ${bound});`);
65
+ // A holder's own member is bound to the holder WEAKLY: the bound value is
66
+ // stored into that very object, and a strong binding makes every such
67
+ // object a cycle only the collector can free (`CallableObject::bindHolder`).
68
+ // A source that is one capture-free function needs no block to hold it: the
69
+ // holder itself is the bound callable's environment (`bindHolderInPlace`).
70
+ const sourceRepresentation = operation.source.representation;
71
+ const sourceText = operandText(ctx, operation.source);
72
+ const knownSource = sourceRepresentation.kind === 'function' ? sourceRepresentation.functionId : ctx.knownCallableEntry(sourceText);
73
+ const inPlace = operation.detached === 'holder' && knownSource !== null && ctx.captures.of(knownSource).kind === 'none';
74
+ const binder = inPlace
75
+ ? `bindHolderInPlace<&${cppThunkName(knownSource)}>`
76
+ : operation.detached === 'holder'
77
+ ? 'bindHolder'
78
+ : 'bindReceiver';
79
+ lines.push(`${defineValue(ctx, operation.result)} = ${type}::${binder}(${sourceText}, ${bound});`);
49
80
  return;
50
81
  }
51
82
  const receiver = operation.receiver
@@ -72,10 +103,56 @@ export const emitBindCallable = (ctx, lines, operation) => {
72
103
  throw createCppEmitBlockedError('call-abi:bind-callable', 'a dynamic Function source has no authenticated native ABI adapter');
73
104
  }
74
105
  const prefix = [...receiver, ...bound];
75
- lines.push(`${defineValue(ctx, operation.result)} = gea::bindCallable<${cppAbiType(operation.result.representation.abi)}, ${operation.bound.length}>(${[
76
- source,
77
- ...prefix
78
- ].join(', ')});`);
106
+ const native = `gea::bindCallable<${cppAbiType(operation.result.representation.abi)}, ${operation.bound.length}>(${[source, ...prefix].join(', ')})`;
107
+ if (!guarded) {
108
+ lines.push(`${defineValue(ctx, operation.result)} = ${native};`);
109
+ return;
110
+ }
111
+ lines.push(...guardedBindLines(ctx, operation, source, native));
112
+ };
113
+ /**
114
+ * A `bind` the reflection census could not confirm unshadowable
115
+ * (`ir/boxed-bind-assumptions.ts`): a boxed instance, prototype or
116
+ * constructor of the method's class reaches dynamic code, where a computed
117
+ * write could give the method's Function object an own `bind`.
118
+ *
119
+ * Whether one did is a run-time fact about ONE object, so it is checked there,
120
+ * the way a checked conversion checks its tag: `callableBindIsIntrinsic` reads
121
+ * the Function object's own-property table -- where every dynamic write to it
122
+ * lands -- and the native bound callable is built exactly as the confirmed
123
+ * case builds it when nothing is there. Otherwise the program's own `bind` is
124
+ * read off the boxed Function and called with the boxed `thisArg` and
125
+ * arguments, and its answer is loaded back through the checked callable
126
+ * adapter.
127
+ *
128
+ * `Function.prototype.bind` itself needs no run-time half: the bind was lowered
129
+ * as the builtin only because the program writes no `bind` onto
130
+ * `Function.prototype` (`callableBindResolution`), and this runtime's
131
+ * `Function.prototype` is not a table dynamic code can write
132
+ * (`dynamicFunctionPrototypeGet`).
133
+ */
134
+ const guardedBindLines = (ctx, operation, source, native) => {
135
+ const described = `"${operation.unboxedMethod?.key ?? 'method'}".bind`;
136
+ const thisArgument = operation.thisArgument ?? operation.receiver;
137
+ const boxedArguments = [
138
+ thisArgument === null ? 'gea::Value()' : boxedValueText(ctx, thisArgument, `${described} thisArg`),
139
+ ...operation.bound.map((value) => boxedValueText(ctx, value, `${described} argument`))
140
+ ];
141
+ const boxedSource = boxedValueText(ctx, operation.source, `${described} Function object`);
142
+ const dynamic = `[&]() -> gea::Value { const gea::Value gea_bind_target = ${boxedSource}; return gea_bind_target.getProperty(gea::PropertyKey::string("bind")).callWithReceiver(gea_bind_target, {${boxedArguments.join(', ')}}); }()`;
143
+ const loaded = unboxedLoadText(operation.result.representation, dynamic);
144
+ if (loaded === null) {
145
+ throw createCppEmitBlockedError('call-abi:bind-shadowable', `${described} can be shadowed through a boxed value, and its dynamic answer cannot be loaded back as ` +
146
+ representationKey(operation.result.representation));
147
+ }
148
+ const name = defineValue(ctx, operation.result);
149
+ // The program's own `bind` is the case no run has taken yet; out of line and
150
+ // cold, its boxing and property call stop sitting inline in every body
151
+ // that binds a method (mongodb binds one per socket listener).
152
+ return [
153
+ `if (gea::callableBindIsIntrinsic(${source})) ${name} = ${native};`,
154
+ `else ${name} = [&]() __attribute__((noinline, cold)) { return ${loaded}; }();`
155
+ ];
79
156
  };
80
157
  /**
81
158
  * Rendering the callable family: calling, constructing, super-initializing, and
@@ -184,6 +261,19 @@ const derivesFrom = (ctx, source, target) => {
184
261
  * that absence is a value it accepts.
185
262
  */
186
263
  /** The lambda's own names, kept out of every body-local namespace a view can be spliced into. */
264
+ /** The generic class a physical copy belongs to: `decl|f1|2@1` and `decl|f1|2@0` share the root `decl|f1|2`. */
265
+ const copyRootOf = (declaration) => {
266
+ const text = String(declaration);
267
+ const at = text.lastIndexOf('@');
268
+ return at < 0 ? text : text.slice(0, at);
269
+ };
270
+ /** Whether `argument` is an instance of one copy of the class (or of a subclass of it) whose parameter slot names a different copy of it. */
271
+ const isSiblingClassCopy = (argument, slot) => {
272
+ if (argument.kind !== 'class-ref' || slot.kind !== 'class-ref' || argument.declaration === slot.declaration)
273
+ return false;
274
+ const root = copyRootOf(slot.declaration);
275
+ return [argument.declaration, ...argument.ancestors].some((declaration) => declaration !== slot.declaration && copyRootOf(declaration) === root);
276
+ };
187
277
  /**
188
278
  * One argument in the carrier the frame it is being written into declares.
189
279
  *
@@ -244,6 +334,16 @@ export const alignedText = (ctx, slot, argument, what = 'call') => {
244
334
  const bound = receiverBoundCallableText(ctx, argument, slot, text);
245
335
  if (bound !== null)
246
336
  return bound;
337
+ // An exact instance of one physical copy of a generic class handed to a
338
+ // parameter of ANOTHER copy of the same class. A `this` is exactly one copy,
339
+ // so the pairing can never hold at run time -- it exists only because a
340
+ // receiver spelled at `any` is the union of every copy (`anyCopyFamilyOf`),
341
+ // and dispatch over that union types each arm's call for all the others.
342
+ // The dead arm is the TypeError a mismatched copy would have been, not a
343
+ // refusal of the live arms beside it.
344
+ if (isSiblingClassCopy(argument.representation, slot)) {
345
+ return `[&]() -> ${cppTypeOf(slot)} { gea::host::throwRuntimeError("TypeError", "a value of another instantiation of this generic class was passed"); }()`;
346
+ }
247
347
  throw createCppEmitBlockedError(`conversion:${representationKey(argument.representation)}->${representationKey(slot)}`, `passes a ${representationKey(argument.representation)} argument into a parameter slot carrying ` +
248
348
  `${representationKey(slot)}, and no installed load performs that conversion`);
249
349
  };
@@ -340,6 +440,39 @@ const argumentText = (ctx, abi, position, argument, what = 'call') => {
340
440
  * same copy passing by value would have made, in the one shape where the
341
441
  * reference has nothing behind it.
342
442
  */
443
+ /**
444
+ * A method called on a union one arm of which is a native Proxy, into a frame
445
+ * whose receiver slot is the OTHER arm.
446
+ *
447
+ * When that other arm is live, it is the receiver. When the proxy is, the
448
+ * callee is whatever its `get` trap answered (`ir/lower-proxy.ts`), and the
449
+ * language calls it with the proxy itself as `this` -- which no native
450
+ * receiver slot can hold and which this runtime cannot box. That aborts at the
451
+ * call, by name (`gea::host::refuseProxyReceiver`), rather than loading the
452
+ * other arm's payload as the plain narrowing would -- and rather than a
453
+ * TypeError the program does not have and a `catch` could swallow. mongodb's
454
+ * `zstd.compress(...)` off its error module is the shape; there the trap
455
+ * throws before the call is reached.
456
+ */
457
+ const proxyUnionReceiverText = (ctx, abi, receiver) => {
458
+ // The same union behind an absence (a module `let` read before any write
459
+ // can be proven, `representation/unassigned-binding-cells.ts`): calling a
460
+ // method off `undefined` is a TypeError, raised by the checked presence load.
461
+ const absent = receiver.representation.kind === 'optional';
462
+ const held = receiver.representation.kind === 'optional' ? receiver.representation.payload : receiver.representation;
463
+ const slot = abi.receiver;
464
+ if (slot === null || held.kind !== 'tagged-union' || !proxyArmWithoutHome(held, slot))
465
+ return null;
466
+ const others = held.arms.flatMap((arm, index) => (arm.value.kind === 'proxy-object' ? [] : [{ arm, index }]));
467
+ const [only] = others;
468
+ if (others.length !== 1 || !only)
469
+ return null;
470
+ const union = absent ? `(*gea::host::presentOrThrow(${operandText(ctx, receiver)}))` : operandText(ctx, receiver);
471
+ const load = alignedValueText(ctx, 'emit-callable.ts:proxy-union-receiver', only.arm.value, slot, `${union}.get<${only.index}>()`);
472
+ if (load === null)
473
+ return null;
474
+ return `(${union}.is<${only.index}>() ? ${load} : gea::host::refuseProxyReceiver<${cppTypeOf(slot)}>())`;
475
+ };
343
476
  export const receiverArgumentText = (ctx, abi, receiver) => {
344
477
  const slot = abi.receiver ?? receiver.representation;
345
478
  // A receiver the callee never names, whose construction was therefore deleted
@@ -350,6 +483,9 @@ export const receiverArgumentText = (ctx, abi, receiver) => {
350
483
  // never declared.
351
484
  if (ctx.deadValues.has(receiver.value))
352
485
  return `${cppTypeOf(slot)}{}`;
486
+ const proxyChecked = proxyUnionReceiverText(ctx, abi, receiver);
487
+ if (proxyChecked !== null)
488
+ return proxyChecked;
353
489
  const text = alignedText(ctx, abi.receiver ?? undefined, receiver, 'receiver');
354
490
  // `withheldCellOf` rather than a private pair of lookups: this is one of the
355
491
  // three sites where an emitter observes a withheld read somewhere the
@@ -382,6 +518,48 @@ const emitNullishInvocation = (ctx, lines, operation) => {
382
518
  defineValueAlias(ctx, result, '(void)0');
383
519
  return true;
384
520
  };
521
+ const refusedPrimitiveValueOf = (primitive, result) => {
522
+ throw createCppEmitBlockedError(`conversion:${representationKey(primitive)}->${representationKey(result)}`, `a "${representationKey(primitive)}" arm's valueOf answers the primitive itself, which this call's "${representationKey(result)}" result cannot hold`);
523
+ };
524
+ /**
525
+ * One union arm's call of the member its native base answers
526
+ * (`UnionMethodArm.nativeBase`): the arm read as that base through the
527
+ * census's native-base view node -- the node a lone receiver of the class is
528
+ * read through -- then the base's own prototype renderer, which converts its
529
+ * answer into this call's published result or refuses by name.
530
+ */
531
+ const nativeBaseArmCallBody = (ctx, operation, arm, native, armText) => {
532
+ const node = ctx.conversions.nativeBaseViewFor(arm, native.carrier);
533
+ const viewed = node === null ? null : recipeText(ctx, node, armText);
534
+ const call = viewed === null ? null : nativeBaseMethodCallText(ctx, native.carrier, native.member, viewed, operation.arguments, operation.result);
535
+ if (call === null) {
536
+ throw createCppEmitBlockedError('call-abi:tagged-union-method', `a tagged-union arm "${representationKey(arm)}" calls "${native.member}" on its native base "${representationKey(native.carrier)}", ` +
537
+ 'and no renderer answers that member on the viewed base');
538
+ }
539
+ return operation.result === null || operation.result.representation.kind === 'void' ? `${call}; return;` : `return ${call};`;
540
+ };
541
+ /**
542
+ * A body that gathers a REST where the call's own convention states fixed
543
+ * parameters -- an interface member `emit(event, a, b)` bound to the class
544
+ * that implements it as `emit(event, ...args)` -- receives the surplus as its
545
+ * one Array (ECMA-262 10.2.11), each argument entered into the rest element.
546
+ * Lowering packed against the held convention, which has no rest to pack
547
+ * into; `emit-record-view.ts`'s view member packs the identical shape
548
+ * (`restPacks`). Null when the body's frame is the call's own.
549
+ */
550
+ const restPackedArguments = (ctx, held, body, operation) => {
551
+ if (operation.argumentsAreSpread || !restPacks(held, body))
552
+ return null;
553
+ const restFrom = body.restFrom;
554
+ const rest = body.parameters[restFrom]?.value;
555
+ if (rest === undefined || rest.kind !== 'array-object')
556
+ return null;
557
+ const elements = operation.arguments.slice(restFrom).map((argument) => alignedText(ctx, rest.element, argument, 'rest element'));
558
+ return [
559
+ ...operation.arguments.slice(0, restFrom).map((argument, position) => argumentText(ctx, body, position, argument)),
560
+ `gea::arrayOf<${cppTypeOf(rest.element)}>({${elements.join(', ')}})`
561
+ ];
562
+ };
385
563
  const emitUnionMethodCall = (ctx, lines, operation) => {
386
564
  const read = ctx.unionMethodReads.get(operation.callee.value);
387
565
  if (read === undefined)
@@ -402,16 +580,37 @@ const emitUnionMethodCall = (ctx, lines, operation) => {
402
580
  armText = armAt(armText, step);
403
581
  }
404
582
  const armTest = tests.length === 0 ? 'true' : tests.join(' && ');
583
+ if (arm.nullish !== undefined) {
584
+ const resultType = operation.result === null || operation.result.representation.kind === 'void' ? 'void' : cppTypeOf(operation.result.representation);
585
+ const thrown = `gea::host::throwGetPropertyOfNullish<${resultType}>("${arm.nullish}")`;
586
+ const body = resultType === 'void' ? `${thrown}; return;` : `return ${thrown};`;
587
+ return index === arms.length - 1 ? body : `if (${armTest}) { ${body} }`;
588
+ }
589
+ if (arm.nativeBase !== undefined) {
590
+ const body = nativeBaseArmCallBody(ctx, operation, arm.receiverRepresentation, arm.nativeBase, armText);
591
+ return index === arms.length - 1 ? body : `if (${armTest}) { ${body} }`;
592
+ }
593
+ if (arm.callable === null) {
594
+ const answer = operation.result === null || operation.result.representation.kind === 'void'
595
+ ? `(void)(${armText}); return;`
596
+ : `return ${alignedValueText(ctx, 'emit-callable.ts:union-primitive-value-of', arm.receiverRepresentation, operation.result.representation, armText) ?? refusedPrimitiveValueOf(arm.receiverRepresentation, operation.result.representation)};`;
597
+ return index === arms.length - 1 ? answer : `if (${armTest}) { ${answer} }`;
598
+ }
405
599
  const abi = ctx.abiOfCallable(arm.callable);
406
- if (abi === null || abi.receiver === null) {
600
+ // A static method's `this` is its class constructor, and its convention
601
+ // declares that receiver only when the body reads it.
602
+ const staticArm = arm.receiverRepresentation.kind === 'constructor-family';
603
+ if (abi === null || (abi.receiver === null && !staticArm)) {
407
604
  throw createCppEmitBlockedError('call-abi:tagged-union-method', 'a deferred tagged-union method body has no receiver-bearing convention');
408
605
  }
409
- const receiver = alignedValueText(ctx, 'emit-callable.ts:705', arm.receiverRepresentation, abi.receiver, armText);
410
- if (receiver === null) {
606
+ const receiver = abi.receiver === null ? null : alignedValueText(ctx, 'emit-callable.ts:705', arm.receiverRepresentation, abi.receiver, armText);
607
+ if (abi.receiver !== null && receiver === null) {
411
608
  throw createCppEmitBlockedError(`conversion:${representationKey(arm.receiverRepresentation)}->${representationKey(abi.receiver)}`, `a deferred tagged-union method receiver cannot convert from ${representationKey(arm.receiverRepresentation)} to ${representationKey(abi.receiver)}`);
412
609
  }
413
- const supplied = receivableArguments(abi, operation.arguments).map((argument, position) => argumentText(ctx, abi, position, argument));
414
- const invocation = `${cppBodyName(arm.callable)}(${paddedArguments(abi, [receiver, ...supplied], 'union method call').join(', ')})`;
610
+ const heldAbi = abiOfCallee(operation.callee.representation);
611
+ const supplied = (heldAbi === null ? null : restPackedArguments(ctx, heldAbi, abi, operation)) ??
612
+ receivableArguments(abi, operation.arguments).map((argument, position) => argumentText(ctx, abi, position, argument));
613
+ const invocation = `${cppBodyName(arm.callable)}(${paddedArguments(abi, [...(receiver === null ? [] : [receiver]), ...supplied], 'union method call').join(', ')})`;
415
614
  let body;
416
615
  if (operation.result === null || operation.result.representation.kind === 'void') {
417
616
  body = `${invocation}; return;`;
@@ -700,6 +899,24 @@ const functionConstructorArgumentTexts = (ctx, arguments_, internalMethod) => ar
700
899
  }
701
900
  return `gea::Eval::functionArgument(${operandText(ctx, argument)})`;
702
901
  });
902
+ /**
903
+ * A `push` onto a char-code buffer (`char-code-buffers.ts`): the cell is the string being built, so each
904
+ * pushed code unit is appended to it, in order, exactly as `fromCharCode` would spell it.
905
+ */
906
+ const emitCharCodeBufferPush = (ctx, lines, operation) => {
907
+ const cell = ctx.charCodeBuffers.pushCallees.get(operation.callee.value);
908
+ const packed = operation.arguments[0];
909
+ if (cell === undefined || packed === undefined)
910
+ return false;
911
+ const buffer = cellValueText(bindingReference(ctx, cell, 'a char-code buffer push'));
912
+ const withheld = ctx.pendingPacks.get(packed.value);
913
+ if (withheld)
914
+ for (const element of withheld.elements)
915
+ lines.push(`gea::host::StringConstructor::appendCharCodeTo(${buffer}, ${element});`);
916
+ else
917
+ lines.push(`gea::host::StringConstructor::appendCharCodesTo(${buffer}, ${operandText(ctx, packed)});`);
918
+ return true;
919
+ };
703
920
  export const emitCall = (ctx, lines, operation) => {
704
921
  if (ctx.numericCalls.get(operation) === 'imul') {
705
922
  const args = operation.arguments.map((argument) => {
@@ -722,6 +939,8 @@ export const emitCall = (ctx, lines, operation) => {
722
939
  emitCall(ctx, lines, { ...operation, result: null });
723
940
  return;
724
941
  }
942
+ if (emitCharCodeBufferPush(ctx, lines, operation))
943
+ return;
725
944
  if (emitNullishInvocation(ctx, lines, operation))
726
945
  return;
727
946
  if (operation.callee.representation.kind === 'native-handle' && operation.callee.representation.protocol === 'FunctionConstructor') {
@@ -1135,7 +1354,8 @@ export const emitCall = (ctx, lines, operation) => {
1135
1354
  }
1136
1355
  const args = [
1137
1356
  ...(declaredReceiverOperand ? [receiverArgumentText(ctx, physicalFrame, declaredReceiverOperand)] : []),
1138
- ...receivableArguments(physicalFrame, operation.arguments).map((argument, position) => argumentText(ctx, directAbi, position, argument))
1357
+ ...((direct === undefined || directAbi === abi ? null : restPackedArguments(ctx, abi, directAbi, operation)) ??
1358
+ receivableArguments(physicalFrame, operation.arguments).map((argument, position) => argumentText(ctx, directAbi, position, argument)))
1139
1359
  ];
1140
1360
  // A callee whose environment is `nullptr` is called by name. The carrier is
1141
1361
  // still built wherever the program stores one -- this only decides how THIS
@@ -1164,38 +1384,93 @@ export const emitCall = (ctx, lines, operation) => {
1164
1384
  // is declared with the family root's reconciled ABI. Convert the receiver
1165
1385
  // and arguments into that ABI before invoking the member; using `args`
1166
1386
  // directly is only valid when every override repeats the root signature.
1167
- const virtualArgs = dispatched === undefined
1387
+ // `this.execute(a, b)` reaches a virtual member with no receiver operand on
1388
+ // the call: the read recorded it (`directCallReceivers`), exactly as it does
1389
+ // for a direct bind. Leaving it out handed the FIRST ARGUMENT the receiver's
1390
+ // place (`a->execute(b)`), and the arity check below then read the call as
1391
+ // omitting its last argument.
1392
+ const virtualReceiver = operation.receiver ?? boundReceiverOperand;
1393
+ if (dispatched !== undefined && !virtualReceiver) {
1394
+ throw createCppEmitBlockedError('call-abi:receiver-mismatch', 'a virtual member call has no receiver to dispatch on');
1395
+ }
1396
+ const virtualArgs = dispatched === undefined || !virtualReceiver
1168
1397
  ? []
1169
1398
  : [
1170
- ...(operation.receiver ? [receiverArgumentText(ctx, dispatched.abi, operation.receiver)] : []),
1399
+ receiverArgumentText(ctx, dispatched.abi, virtualReceiver),
1171
1400
  ...receivableArguments(dispatched.abi, operation.arguments).map((argument, position) => argumentText(ctx, dispatched.abi, position, argument))
1172
1401
  ];
1173
1402
  const virtualPadded = dispatched === undefined ? [] : paddedArguments(dispatched.abi, virtualArgs, 'virtual call');
1174
1403
  const memberRead = ctx.propertyReadOrigins.get(operation.callee.value);
1175
1404
  const memberKey = memberRead === undefined ? undefined : ctx.staticKeyTexts.get(memberRead.key.value);
1176
- const candidate = memberRead === undefined || memberKey === undefined || calleeOperand.value !== operation.callee.value
1405
+ const memberSlot = memberRead === undefined || memberKey === undefined || calleeOperand.value !== operation.callee.value
1177
1406
  ? undefined
1178
- : ctx.callableMemberCandidates.get(callableMemberSlot(memberRead.receiver.representation, memberKey));
1407
+ : callableMemberSlot(memberRead.receiver.representation, memberKey);
1408
+ const candidate = memberSlot === undefined ? undefined : ctx.callableMemberCandidates.get(memberSlot);
1409
+ const alternate = memberSlot === undefined ? undefined : ctx.callableMemberCandidates.get(callableMemberAlternateSlot(memberSlot));
1179
1410
  const stableCandidate = ctx.stableBorrowEntries.get(direct ?? (candidate === undefined ? '' : cppBodyName(candidate)));
1180
1411
  const potentiallyMovingArguments = new Set(operation.arguments
1181
- .filter((argument) => transferOf(ctx.dyingArguments, ctx.ownedValues, ctx.ownedDyingValues, argument.value) === 'move')
1412
+ .filter((argument) => transferOf(ctx.dyingArguments, ctx.ownedValues, ctx.transferDyingValues, argument.value, ctx.receiverRenames) === 'move')
1182
1413
  .map((argument) => argument.value));
1183
1414
  const stableEntry = stableCandidate !== undefined &&
1184
1415
  stableBorrowEntryAccepts(stableCandidate, operation.arguments, ctx.stableBorrowActuals, potentiallyMovingArguments)
1185
1416
  ? stableCandidate
1186
1417
  : undefined;
1418
+ // A candidate's borrowed entry for this call, when it has one: the stable
1419
+ // entry its arguments are accepted by, or its borrowable body.
1420
+ const borrowedEntryOf = (target) => {
1421
+ const stable = ctx.stableBorrowEntries.get(cppBodyName(target));
1422
+ if (stable !== undefined && stableBorrowEntryAccepts(stable, operation.arguments, ctx.stableBorrowActuals, potentiallyMovingArguments))
1423
+ return stable.name;
1424
+ return ctx.borrowableMemberBodies.has(target) ? cppBodyName(target) : undefined;
1425
+ };
1426
+ const twoCandidates = candidate !== undefined && alternate !== undefined && direct === undefined;
1427
+ const firstEntry = twoCandidates ? borrowedEntryOf(candidate) : undefined;
1428
+ const alternateEntry = twoCandidates ? borrowedEntryOf(alternate) : undefined;
1429
+ // Only the alternate can be entered borrowed (bson's web `encodeUTF8Into` owns its `source`, the node one reads it): guarding the
1430
+ // first-stored one alone missed on every call under Node and sent each key string through the owning thunk.
1431
+ const alternateOnly = twoCandidates && firstEntry === undefined && alternateEntry !== undefined;
1432
+ // A callee that is the caller's own parameter, constant or private cell sits in a slot no callee can
1433
+ // write (`stableBorrowActualsOf`); so does a callee materialized into a frame local of its own (an
1434
+ // owned SSA temporary with a declaration, not a deferred expression naming a field or cell). The
1435
+ // environment retain `CallableObject::call` makes is there for a callback that overwrites the
1436
+ // field it was reached through, and guards against nothing in either case.
1437
+ const stableCallee = calleeOperand.value === operation.callee.value &&
1438
+ (ctx.stableBorrowActuals.has(operation.callee.value) ||
1439
+ (ctx.ownedValues.has(operation.callee.value) && !ctx.deferredTexts.has(operation.callee.value)));
1187
1440
  const callMember = candidate === undefined
1188
- ? 'call'
1189
- : stableEntry !== undefined
1190
- ? `callKnownBorrowed<&${cppThunkName(candidate)}, &${stableEntry.name}>`
1191
- : ctx.borrowableMemberBodies.has(candidate)
1192
- ? `callKnownBorrowed<&${cppThunkName(candidate)}, &${cppBodyName(candidate)}>`
1193
- : `callKnown<&${cppThunkName(candidate)}>`;
1441
+ ? stableCallee
1442
+ ? 'callStable'
1443
+ : 'call'
1444
+ : firstEntry !== undefined && alternate !== undefined && alternateEntry !== undefined
1445
+ ? `callKnownBorrowedEither<&${cppThunkName(candidate)}, &${firstEntry}, &${cppThunkName(alternate)}, &${alternateEntry}>`
1446
+ : alternateOnly
1447
+ ? `callKnownBorrowed<&${cppThunkName(alternate)}, &${alternateEntry}>`
1448
+ : stableEntry !== undefined
1449
+ ? `callKnownBorrowed<&${cppThunkName(candidate)}, &${stableEntry.name}>`
1450
+ : ctx.borrowableMemberBodies.has(candidate)
1451
+ ? `callKnownBorrowed<&${cppThunkName(candidate)}, &${cppBodyName(candidate)}>`
1452
+ : `callKnown<&${cppThunkName(candidate)}>`;
1453
+ // The run-time half of `CallOperation.builtinShadowGuard`: the rewrite
1454
+ // bypassed `[[Get]]` of `call`/`apply` on the strength of every possibly
1455
+ // shadowing write going through a boxed target, and whether one reached
1456
+ // THIS Function object is read off its own-property table here, the way
1457
+ // `guardedBindLines` does for `bind`. A shadowed builtin is refused by name
1458
+ // rather than forwarded: the program's own `call` would be the thing to
1459
+ // run, and this frame is the callee's, not `.call`'s.
1460
+ if (operation.builtinShadowGuard !== undefined) {
1461
+ lines.push(`if (!gea::callableBuiltinIsIntrinsic(${operandText(ctx, calleeOperand)}, gea::PropertyKey::string(${cppStringLiteral(operation.builtinShadowGuard)}))) ` +
1462
+ `gea::host::throwRuntimeError("TypeError", ${cppStringLiteral(`an own "${operation.builtinShadowGuard}" written onto a natively carried callable is not rendered by this backend`)});`);
1463
+ }
1194
1464
  const invocation = dispatched !== undefined
1195
1465
  ? `${virtualPadded[0]}->${dispatched.member}(${virtualPadded.slice(1).join(', ')})`
1196
1466
  : direct !== undefined
1197
1467
  ? `${stableEntry?.name ?? direct}(${padded.join(', ')})`
1198
1468
  : `${operandText(ctx, calleeOperand)}.${callMember}(${padded.join(', ')})`;
1469
+ // A result the integer census narrowed from the candidate body's returns is
1470
+ // checked where it lands, on every path the call can take: the guard above
1471
+ // may miss and run whatever callable the member holds.
1472
+ const checkedLimit = operation.result === null ? undefined : ctx.integerCallChecks.get(operation.result.id);
1473
+ const checked = (text) => checkedLimit === undefined ? text : `gea::requireIntegralCallResult(${text}, ${checkedLimit}LL)`;
1199
1474
  if (!operation.result) {
1200
1475
  lines.push(`${invocation};`);
1201
1476
  return;
@@ -1260,12 +1535,35 @@ export const emitCall = (ctx, lines, operation) => {
1260
1535
  // local and the conversion reads that -- an IIFE rather than two statements
1261
1536
  // because a declaration between two of this body's `goto` labels would let
1262
1537
  // a jump bypass its initialization.
1538
+ if (checkedLimit !== undefined)
1539
+ ctx.checkedIntegerCalls.add(operation.result.id);
1263
1540
  if (produced === callResultName) {
1264
- lines.push(`${name} = ${invocation};`);
1541
+ // `await f()` where the promise is read nowhere else: call `f`'s `_task`
1542
+ // twin (`taskTwinEligible`), which answers the frame itself instead of a
1543
+ // pooled promise state. The very next operation awaits it
1544
+ // (`fusedAwaitCallsOf`), so nothing else can name it.
1545
+ const resultType = cppTypeOf(operation.result.representation);
1546
+ if (direct !== undefined &&
1547
+ dispatched === undefined &&
1548
+ stableEntry === undefined &&
1549
+ checkedLimit === undefined &&
1550
+ ctx.asyncCoroutineBody &&
1551
+ ctx.taskBodies.has(direct) &&
1552
+ ctx.fusableAwaitCalls.has(operation.result.id) &&
1553
+ operation.result.representation.kind === 'promise') {
1554
+ const index = ctx.declarations.findIndex((entry) => entry.name === name);
1555
+ if (index >= 0) {
1556
+ ctx.declarations[index] = { name, type: `gea::Task<${resultType.slice('gea::Promise<'.length)}` };
1557
+ ctx.taskValues.add(operation.result.id);
1558
+ lines.push(`${name} = ${direct}_task(${padded.join(', ')});`);
1559
+ return;
1560
+ }
1561
+ }
1562
+ lines.push(`${name} = ${checked(invocation)};`);
1265
1563
  return;
1266
1564
  }
1267
1565
  const target = cppTypeOf(operation.result.representation);
1268
- lines.push(`${name} = ([&]() -> ${target} { auto ${callResultName} = ${invocation}; return ${produced}; }());`);
1566
+ lines.push(`${name} = ([&]() -> ${target} { auto ${callResultName} = ${invocation}; return ${checked(produced)}; }());`);
1269
1567
  };
1270
1568
  /** The local a call's own result is read into when its carrier has to be reconciled with the cell's. */
1271
1569
  const callResultName = 'gea_call_result';
@@ -1288,6 +1586,38 @@ const trailingOptionalCount = (args) => {
1288
1586
  }
1289
1587
  return count;
1290
1588
  };
1589
+ /**
1590
+ * A class extending `Error` that answers `name`/`message` with a getter
1591
+ * (`override get name() { return 'MongoError' }`) still has the intrinsic
1592
+ * layout's own field under that key, and every read through an `Error`
1593
+ * carrier -- an upcast store, `toString`, a boxed read -- sees the field. The
1594
+ * family may only travel as that carrier when each such getter is a constant
1595
+ * (`class-heritage.ts`'s `nativeErrorOverridesOf`), so the field is written
1596
+ * once, right after the base initializes it, with the most-derived getter's
1597
+ * answer: through the family's virtual dispatch member when a subclass
1598
+ * redeclares the getter, which the already-allocated receiver resolves to its
1599
+ * own class.
1600
+ */
1601
+ const nativeErrorGetterStoreStatements = (ctx, declaration) => {
1602
+ const statements = [];
1603
+ const stringCarrier = { kind: 'string' };
1604
+ for (const key of ['name', 'message']) {
1605
+ const site = classMemberOf(ctx.classes, declaration, key);
1606
+ if (site === null || site.kind !== 'accessor' || site.accessor.getter === null)
1607
+ continue;
1608
+ const dispatched = classFamilyOverridesOf(ctx.classes, declaration, key).length > 0;
1609
+ const dispatch = dispatched ? ctx.virtualDispatch.get(virtualDispatchKey(declaration, key, 'get')) : undefined;
1610
+ const result = dispatched ? dispatch?.result : ctx.abiOfCallable(site.accessor.getter)?.result;
1611
+ const call = dispatched
1612
+ ? `${cppReceiverName}->${cppVirtualMemberName(key, 'get')}()`
1613
+ : `${cppBodyName(site.accessor.getter)}(${cppReceiverName})`;
1614
+ const text = result === undefined ? null : alignedValueText(ctx, 'emit-callable.ts:nativeErrorGetterStore', result, stringCarrier, call);
1615
+ if (text === null)
1616
+ throw createCppEmitBlockedError('call-abi:super-initialize', `class ${declaration}'s \`${key}\` getter has no string result to store into the intrinsic Error layout`);
1617
+ statements.push(`static_cast<${cppErrorNativeType}&>(*${cppReceiverName}).${key} = ${text};`);
1618
+ }
1619
+ return statements;
1620
+ };
1291
1621
  /**
1292
1622
  * `super(...)`: the base's initialization against the object under
1293
1623
  * construction, then this class's own field initializers.
@@ -1310,7 +1640,7 @@ const trailingOptionalCount = (args) => {
1310
1640
  * refused here rather than silently initializing the enclosing class.
1311
1641
  */
1312
1642
  export const emitSuperInitialize = (ctx, lines, operation) => {
1313
- const owning = [...ctx.classes.values()].find((layout) => layout.constructor === ctx.owner);
1643
+ const owning = classLayoutsConstructedBy(ctx.classes, ctx.owner)[0];
1314
1644
  if (!owning) {
1315
1645
  throw createCppEmitBlockedError('call-abi:super-initialize', `runs in ${ctx.owner}, which no class publishes as its constructor body, so there is no base to initialize`);
1316
1646
  }
@@ -1320,9 +1650,36 @@ export const emitSuperInitialize = (ctx, lines, operation) => {
1320
1650
  if (ctx.abi?.receiver?.kind !== 'class-ref') {
1321
1651
  throw createCppEmitBlockedError('call-abi:super-initialize', `the constructor of class ${owning.declaration} declares no class receiver to initialize the base against`);
1322
1652
  }
1653
+ if (owning.nativeBase !== null && owning.nativeBase.instance.kind === 'keyed-collection') {
1654
+ const baseStatements = nativeCollectionBaseInitializeStatements(ctx, ctx.classes, owning.declaration, ctx.abiOfCallable, cppReceiverName, owning.nativeBase.instance, operation.arguments.map((argument) => ({ representation: argument.representation, text: operandText(ctx, argument) })));
1655
+ if (typeof baseStatements === 'string')
1656
+ throw createCppEmitBlockedError('call-abi:super-initialize', baseStatements);
1657
+ for (const statement of baseStatements)
1658
+ lines.push(statement);
1659
+ const fieldInitializers = cppFieldInitializerStatements(ctx, owning.declaration, owning.fields, cppReceiverName, (field) => owning.instance === null ? null : declaredRecordFieldOf(ctx.deriver, owning.instance, field.key, ctx.classes));
1660
+ if (typeof fieldInitializers === 'string')
1661
+ throw createCppEmitBlockedError('conversion:class-property-initializer', fieldInitializers);
1662
+ for (const statement of fieldInitializers)
1663
+ lines.push(statement);
1664
+ return;
1665
+ }
1666
+ if (owning.nativeBase !== null && owning.nativeBase.instance.kind === 'promise') {
1667
+ const baseStatements = nativePromiseBaseInitializeStatements(cppReceiverName, owning.nativeBase.instance, operation.arguments.map((argument) => ({ representation: argument.representation, text: operandText(ctx, argument) })));
1668
+ if (typeof baseStatements === 'string')
1669
+ throw createCppEmitBlockedError('call-abi:super-initialize', baseStatements);
1670
+ for (const statement of baseStatements)
1671
+ lines.push(statement);
1672
+ const fieldInitializers = cppFieldInitializerStatements(ctx, owning.declaration, owning.fields, cppReceiverName, (field) => owning.instance === null ? null : declaredRecordFieldOf(ctx.deriver, owning.instance, field.key, ctx.classes));
1673
+ if (typeof fieldInitializers === 'string')
1674
+ throw createCppEmitBlockedError('conversion:class-property-initializer', fieldInitializers);
1675
+ for (const statement of fieldInitializers)
1676
+ lines.push(statement);
1677
+ return;
1678
+ }
1323
1679
  if (owning.nativeBase !== null) {
1324
- if (owning.nativeBase.instance.native !== cppErrorNativeType) {
1325
- throw createCppEmitBlockedError('call-abi:super-initialize', `native base ${owning.nativeBase.protocol} uses "${owning.nativeBase.instance.native ?? 'no native layout'}"; only the intrinsic Error layout has an existing-receiver initializer`);
1680
+ const errorBase = owning.nativeBase.instance;
1681
+ if (errorBase.kind !== 'native-record-ref' || errorBase.native !== cppErrorNativeType) {
1682
+ throw createCppEmitBlockedError('call-abi:super-initialize', `native base ${owning.nativeBase.protocol} uses "${errorBase.kind === 'native-record-ref' ? (errorBase.native ?? 'no native layout') : errorBase.kind}"; only the intrinsic Error layout has an existing-receiver initializer`);
1326
1683
  }
1327
1684
  const baseStatements = nativeErrorBaseInitializeStatements(ctx.deriver, cppReceiverName, operation.arguments.slice(0, 2).map((argument) => ({ representation: argument.representation, text: operandText(ctx, argument) })));
1328
1685
  if (isNativeErrorBaseRefusal(baseStatements)) {
@@ -1332,6 +1689,8 @@ export const emitSuperInitialize = (ctx, lines, operation) => {
1332
1689
  }
1333
1690
  for (const statement of baseStatements)
1334
1691
  lines.push(statement);
1692
+ for (const statement of nativeErrorGetterStoreStatements(ctx, owning.declaration))
1693
+ lines.push(statement);
1335
1694
  const fieldInitializers = cppFieldInitializerStatements(ctx, owning.declaration, owning.fields, cppReceiverName, (field) => owning.instance === null ? null : declaredRecordFieldOf(ctx.deriver, owning.instance, field.key, ctx.classes));
1336
1695
  if (typeof fieldInitializers === 'string')
1337
1696
  throw createCppEmitBlockedError('conversion:class-property-initializer', fieldInitializers);
@@ -1385,34 +1744,47 @@ export const emitSuperInitialize = (ctx, lines, operation) => {
1385
1744
  * The packed environment one capturing body is entered with, built in the
1386
1745
  * frame that supplies its captures.
1387
1746
  *
1388
- * `gea::packEnvironment` (gea_runtime.h) decides where the captured state
1389
- * physically goes, and the body's own `unpackEnvironment` reads that same
1390
- * decision from the same predicate, so the two cannot disagree. Where it
1391
- * fits, the state IS the pointer the carrier holds and nothing is allocated;
1392
- * where it does not, the struct is a `gea::Ref` block every holder counts on
1393
- * -- which is why there is no "who deletes it" question here: the last holder
1394
- * does.
1747
+ * `gea::packEnvironment`/`gea::packTransientEnvironment` (gea_runtime.h)
1748
+ * decide where the captured state physically goes, and the body's own
1749
+ * `unpackEnvironment`/`unpackTransientEnvironment` reads that same decision
1750
+ * from the same predicate, so the two cannot disagree. Where it fits, the
1751
+ * state IS the pointer the carrier holds and nothing is allocated; where it
1752
+ * is exactly one ref-owned capture and `transient` says this body is read
1753
+ * back only through a thunk, the pointer is that capture's own address and
1754
+ * nothing is allocated either; otherwise the struct is a `gea::Ref` block
1755
+ * every holder counts on -- which is why there is no "who deletes it"
1756
+ * question here: the last holder does.
1395
1757
  *
1396
1758
  * Two callers, and they are the two ways a body can be reached with state it
1397
- * did not declare: a `CallableObject` carries it for an allocated closure,
1398
- * and a record member carries it for a capturing ACCESSOR
1399
- * (`emit-allocation.ts`), which has no carrier of its own.
1759
+ * did not declare: a `CallableObject` carries it for an allocated closure
1760
+ * (`transient: true` -- entered only through a thunk, which unpacks with the
1761
+ * matching `gea::unpackTransientEnvironment`), and a record member carries it
1762
+ * for a capturing ACCESSOR (`emit-allocation.ts`, `transient: false`), which
1763
+ * has no carrier of its own and is read back in place with
1764
+ * `gea::storedEnvironment` -- a call with no scratch slot to reconstruct a
1765
+ * transiently-packed environment into, so an accessor's pack call must stay
1766
+ * the untransient one.
1400
1767
  */
1401
- export const packedEnvironmentText = (ctx, lines, functionId, admission) => {
1768
+ export const packedEnvironmentText = (ctx, lines, functionId, admission, transient = false) => `gea::${transient ? 'packTransientEnvironment' : 'packEnvironment'}(${environmentValueText(ctx, lines, functionId, admission, cppEnvironmentStructName(functionId))})`;
1769
+ /** The environment struct's value, one field per captured slot (then the receiver), read in this frame. */
1770
+ const environmentValueText = (ctx, lines, functionId, admission, struct) => {
1402
1771
  if (admission.kind !== 'ok')
1403
- throw new Error(`packedEnvironmentText called for ${functionId} with no admitted environment`);
1772
+ throw new Error(`environmentValueText called for ${functionId} with no admitted environment`);
1404
1773
  for (const slot of admission.layout.slots)
1405
1774
  ensureBoxedSlotDeclared(ctx, lines, slot);
1406
1775
  const fields = [
1407
- ...admission.layout.slots.map((slot) => slot.boxed
1776
+ ...admission.layout.slots
1777
+ .filter((slot) => slot.frame === undefined)
1778
+ .map((slot) => slot.boxed
1408
1779
  ? bindingReference(ctx, slot.declaration, `a capture of ${functionId}`).name
1409
1780
  : captureFieldText(ctx, slot.declaration, slot.representation, bindingReference(ctx, slot.declaration, `a capture of ${functionId}`).name)),
1781
+ ...admission.layout.frames.map((frame) => frameHandleText(ctx, frame)),
1410
1782
  ...(admission.layout.receiver !== null ? [cppReceiverName] : [])
1411
1783
  ];
1412
- return `gea::packEnvironment(${cppEnvironmentStructName(functionId)}{${fields.join(', ')}})`;
1784
+ return `${struct}{${fields.join(', ')}}`;
1413
1785
  };
1414
1786
  const ensureBoxedSlotDeclared = (ctx, lines, slot) => {
1415
- if (!slot.boxed)
1787
+ if (!slot.boxed || slot.frame !== undefined)
1416
1788
  return;
1417
1789
  const placement = ctx.placements.get(slot.declaration);
1418
1790
  if (placement?.storage.kind !== 'local' || placement.storage.owner !== ctx.owner)
@@ -1478,6 +1850,13 @@ export const emitAllocateCallable = (ctx, lines, operation) => {
1478
1850
  // no `optional` to begin with.
1479
1851
  const payloadCarrier = carrier.kind === 'optional' ? carrier.payload : carrier;
1480
1852
  const wrap = (payloadText) => (carrier.kind === 'optional' ? `${cppTypeOf(carrier)}{${payloadText}}` : payloadText);
1853
+ // A plain callable carrier's entry IS this function's thunk, whatever the
1854
+ // environment: a conversion that adapts the value can call that entry directly.
1855
+ if (carrier.kind === 'function' ||
1856
+ carrier.kind === 'function-family' ||
1857
+ carrier.kind === 'function-value-family' ||
1858
+ carrier.kind === 'function-value-dispatch')
1859
+ ctx.callableEntryTexts.set(name, operation.functionId);
1481
1860
  // Which body this callable runs, kept so a consumer that must RE-RUN it --
1482
1861
  // a reactive JSX slot -- can ask what that body reads. See `thunkValues`.
1483
1862
  //
@@ -1519,7 +1898,7 @@ export const emitAllocateCallable = (ctx, lines, operation) => {
1519
1898
  // regardless: its `prototype` lives on that owner and `new F()` reads it.
1520
1899
  const identified = (payloadText) => payloadCarrier.kind === 'function-and-constructor' ||
1521
1900
  payloadCarrier.kind === 'dynamic' ||
1522
- ctx.callableIdentityDemand.observes(payloadCarrier)
1901
+ ctx.callableIdentityDemand.observesAllocation(operation.result.id, payloadCarrier)
1523
1902
  ? `gea::identifyCallable<&${cppCallableDeclarationTagName(operation.functionId)}>(${payloadText})`
1524
1903
  : payloadText;
1525
1904
  // A function whose OWN structural type the `--dynamic-fallback` prototype
@@ -1554,7 +1933,7 @@ export const emitAllocateCallable = (ctx, lines, operation) => {
1554
1933
  lines.push(`${name} = gea::host::installOrdinaryConstructorPrototype(${boxText(`${callableType}{${cppThunkEntryText(ctx, operation.functionId)}, nullptr}`)});`);
1555
1934
  return;
1556
1935
  }
1557
- const dynamicEnvironment = packedEnvironmentText(ctx, lines, operation.functionId, admission);
1936
+ const dynamicEnvironment = packedEnvironmentText(ctx, lines, operation.functionId, admission, true);
1558
1937
  lines.push(`${name} = gea::host::installOrdinaryConstructorPrototype(${boxText(`${callableType}{${cppThunkEntryText(ctx, operation.functionId)}, ${dynamicEnvironment}}`)});`);
1559
1938
  return;
1560
1939
  }
@@ -1566,7 +1945,59 @@ export const emitAllocateCallable = (ctx, lines, operation) => {
1566
1945
  lines.push(`${name} = ${wrap(identified(`${cppTypeOf(payloadCarrier)}{${pointers}, nullptr}`))};`);
1567
1946
  return;
1568
1947
  }
1569
- const environment = packedEnvironmentText(ctx, lines, operation.functionId, admission);
1948
+ const group = ctx.captures.groupOf(operation.functionId);
1949
+ if (group !== null) {
1950
+ // A recursion group member (`IrCaptureGroup`): the group's one environment
1951
+ // is built at its first member's allocation -- where `ir/captures.ts`
1952
+ // proved every capture already written -- and each member is that block
1953
+ // with its own entry and identity slot. The IR admits only a plain
1954
+ // callable carrier, so anything else here is a disagreement between the
1955
+ // two, refused rather than rendered as an environment of its own (the
1956
+ // capture facts already stopped boxing the members).
1957
+ if (carrier.kind === 'optional' || payloadCarrier.kind === 'function-and-constructor') {
1958
+ throw createCppEmitBlockedError('capture:recursion-group', `allocates ${operation.functionId} as a "${carrier.kind}" carrier, but its recursion group shares one plain callable environment`);
1959
+ }
1960
+ const struct = cppEnvironmentStructName(group.id);
1961
+ let shared = ctx.sharedEnvironments.get(group.id);
1962
+ if (shared === undefined) {
1963
+ shared = `gea_group_${ctx.sharedEnvironments.size}`;
1964
+ ctx.sharedEnvironments.set(group.id, shared);
1965
+ ctx.declarations.push({ name: shared, type: `gea::SharedEnvironment<${struct}>` });
1966
+ lines.push(`${shared} = gea::shareEnvironment(${environmentValueText(ctx, lines, operation.functionId, admission, struct)});`);
1967
+ }
1968
+ lines.push(`${name} = ${sharedGroupMemberText(ctx, group, operation.functionId, payloadCarrier, shared)};`);
1969
+ return;
1970
+ }
1971
+ // The allocation's value is used exactly once, synchronously, and retained
1972
+ // by nothing past that one call (`ir/borrowed-callable-uses.ts`'s whole-
1973
+ // program proof, today: the executor argument of `new Promise(...)`) -- so
1974
+ // its environment is a named C++ local declared right here, never a
1975
+ // `gea::HeapEnvironmentBlock`. The callable-identity gate is asked again,
1976
+ // independently, because that census answers a different question (does
1977
+ // ANY copy of this CONVENTION ever need identity) that the capture fact
1978
+ // above does not: an identity slot would need somewhere to live once this
1979
+ // local's block ends, which a borrow does not have.
1980
+ if (ctx.captures.borrowedExecutorEnvironment(operation.result.id) &&
1981
+ !ctx.callableIdentityDemand.observesAllocation(operation.result.id, payloadCarrier)) {
1982
+ const struct = cppEnvironmentStructName(operation.functionId);
1983
+ const stackName = `${name}_env`;
1984
+ lines.push(`${struct} ${stackName} = ${environmentValueText(ctx, lines, operation.functionId, admission, struct)};`);
1985
+ lines.push(`${name} = ${wrap(identified(`${cppTypeOf(payloadCarrier)}{${pointers}, gea::packBorrowedEnvironment(${stackName})}`))};`);
1986
+ return;
1987
+ }
1988
+ // A closure whose whole environment is its owner's frame handle anchors its
1989
+ // identity in a slot of that frame (`CaptureIndex.frameIdentitiesOf`), so
1990
+ // identifying it costs no cell. Only when the program observes the identity:
1991
+ // otherwise the bare handle is the whole closure.
1992
+ const identitySlot = ctx.captures.frameIdentityOf(operation.functionId);
1993
+ if (identitySlot !== null &&
1994
+ identitySlot.frame.owner === ctx.owner &&
1995
+ ctx.callableIdentityDemand.observesAllocation(operation.result.id, payloadCarrier)) {
1996
+ const anchored = `gea::packFrameEnvironment<${cppEnvironmentStructName(operation.functionId)}>(${cppFrameLocalName}, &${cppFrameStructName(String(ctx.owner))}::${cppSharedIdentityFieldName(identitySlot.index)})`;
1997
+ lines.push(`${name} = ${wrap(identified(`${cppTypeOf(payloadCarrier)}{${pointers}, ${anchored}}`))};`);
1998
+ return;
1999
+ }
2000
+ const environment = packedEnvironmentText(ctx, lines, operation.functionId, admission, true);
1570
2001
  lines.push(`${name} = ${wrap(identified(`${cppTypeOf(payloadCarrier)}{${pointers}, ${environment}}`))};`);
1571
2002
  };
1572
2003
  /**
@@ -1591,6 +2022,17 @@ export const emitAllocateCallable = (ctx, lines, operation) => {
1591
2022
  * views and numeric array copies use their own branches below; unsupported
1592
2023
  * carrier families are refused rather than treated as a numeric length.
1593
2024
  */
2025
+ /**
2026
+ * A buffer block, or a native sum of the two: `view.buffer` is typed
2027
+ * `ArrayBufferLike`, so `view.buffer.slice(...)` (bson's
2028
+ * `webByteUtils.toLocalBufferType`) hands `new Uint8Array(...)` an
2029
+ * `ArrayBuffer | SharedArrayBuffer`, and either arm is the buffer overload.
2030
+ */
2031
+ const isBufferBlockCarrier = (carrier) => carrier.kind === 'array-buffer' ||
2032
+ carrier.kind === 'shared-array-buffer' ||
2033
+ (carrier.kind === 'tagged-union' &&
2034
+ carrier.arms.length > 0 &&
2035
+ carrier.arms.every((arm) => arm.value.kind === 'array-buffer' || arm.value.kind === 'shared-array-buffer'));
1594
2036
  const emitTypedArrayConstruct = (ctx, lines, operation, result) => {
1595
2037
  if (result.ownership !== 'shared-refcount') {
1596
2038
  throw createCppEmitBlockedError(`physical-cpp-type:${representationKey(result)}`, `a typed array allocation carries ownership "${result.ownership}", but this emitter only spells std::make_shared for "shared-refcount"`);
@@ -1603,7 +2045,7 @@ const emitTypedArrayConstruct = (ctx, lines, operation, result) => {
1603
2045
  // family. Checked before the arity guard below because it is the one
1604
2046
  // overload that takes more than one argument.
1605
2047
  const first = operation.arguments[0];
1606
- if (first?.representation.kind === 'array-buffer' || first?.representation.kind === 'shared-array-buffer') {
2048
+ if (first !== undefined && isBufferBlockCarrier(first.representation)) {
1607
2049
  emitTypedArrayBufferConstruct(ctx, lines, operation, target);
1608
2050
  return;
1609
2051
  }
@@ -1757,15 +2199,13 @@ const emitArrayConstruct = (ctx, lines, operation, result) => {
1757
2199
  * the construction's own already-resolved result carrier and argument
1758
2200
  * representation instead.
1759
2201
  *
1760
- * Only the zero-argument form, plus `new Set(T[])`, is rendered. Every other
1761
- * seeding form refuses by name:
2202
+ * Rendered: the zero-argument form, `new Set(T[])`/`new Set(Set<T>)` and the
2203
+ * widening Set seeds, and `new Map(pairs)` over an Array of `[K, V]` tuples
2204
+ * (`mapSeedText`: a tuple is a positional record of "0"/"1" fields). Every
2205
+ * other seeding form refuses by name:
1762
2206
  *
1763
- * - a Map/WeakMap seeded from entries needs each element to be a `[K, V]`
1764
- * PAIR, and this compiler carries a tuple as an ordinary record of "0"/"1"
1765
- * fields (`derive.ts`'s `deriveTuple`). Reading two struct members back out
1766
- * as a key and a value is a real lowering, not a spelling, and guessing at
1767
- * it would be the kind of improvisation `emitArrayConstruct` already
1768
- * declines for `new Array(...items)`;
2207
+ * - a WeakMap seeded from entries, and a Map seeded from anything but an
2208
+ * Array of required pairs;
1769
2209
  * - a Set seeded from any iterable that is not an Array needs the dynamic
1770
2210
  * `@@iterator` protocol this backend does not lower at all
1771
2211
  * (`emit-iterator.ts`);
@@ -1812,6 +2252,26 @@ const emitKeyedCollectionConstruct = (ctx, lines, operation, result) => {
1812
2252
  if (result.family === 'set' && carrier.kind === 'array-object' && representationKey(carrier.element) === representationKey(result.key)) {
1813
2253
  return void lines.push(`${name} = gea::setFromArray<${cppTypeOf(result.key)}>(${operandText(ctx, argument)});`);
1814
2254
  }
2255
+ // A Set of the Set's own element carrier: its iterator is the built-in
2256
+ // insertion-order walk, as native as the Array one -- mongodb's
2257
+ // `setDifference` copies `new Set<T>(setA)` from a `Set<string>`.
2258
+ if (result.family === 'set' &&
2259
+ carrier.kind === 'keyed-collection' &&
2260
+ carrier.family === 'set' &&
2261
+ representationKey(carrier.key) === representationKey(result.key)) {
2262
+ return void lines.push(`${name} = gea::setFromSet<${cppTypeOf(result.key)}>(${operandText(ctx, argument)});`);
2263
+ }
2264
+ // An Array or Set whose element WIDENS into the Set's own (a `string[]`
2265
+ // into a `Set<any>`), or a sum of those -- mongodb's `isSuperset` rebinds
2266
+ // `set = Array.isArray(set) ? new Set(set) : set` over `string[] |
2267
+ // Set<any>`. The walk is the source's own iteration (23.1.5.1 / 24.2.5.1),
2268
+ // each element through the one conversion authority.
2269
+ if (result.family === 'set') {
2270
+ const seeded = setSeedText(ctx, result, carrier, 'gea_seed_source');
2271
+ if (seeded !== null) {
2272
+ return void lines.push(`${name} = ([&](const ${cppTypeOf(carrier)}& gea_seed_source) -> ${cppTypeOf(result)} { ${seeded} })(${operandText(ctx, argument)});`);
2273
+ }
2274
+ }
1815
2275
  // A STRING is the second iterable this backend proves statically, and it is
1816
2276
  // not a special case of the Array one: ECMA-262 22.1.5.1 iterates a string
1817
2277
  // by CODE POINT, so `new Set('ab')` holds two one-character strings and
@@ -1824,11 +2284,107 @@ const emitKeyedCollectionConstruct = (ctx, lines, operation, result) => {
1824
2284
  if (result.family === 'set' && carrier.kind === 'string' && result.key.kind === 'string') {
1825
2285
  return void lines.push(`${name} = gea::setFromString(${operandText(ctx, argument)});`);
1826
2286
  }
2287
+ if (result.family === 'map' && result.value !== null) {
2288
+ const seeded = mapSeedText(ctx, result, result.value, carrier, 'gea_seed_source');
2289
+ if (seeded !== null) {
2290
+ return void lines.push(`${name} = ([&](const ${cppTypeOf(carrier)}& gea_seed_source) -> ${cppTypeOf(result)} { ${seeded} })(${operandText(ctx, argument)});`);
2291
+ }
2292
+ }
1827
2293
  throw createCppEmitBlockedError('call-abi:construct:keyed-collection', `constructs a ${result.family}<${representationKey(result.key)}> from a "${representationKey(carrier)}" argument; only the zero-argument form is implemented for every ` +
1828
- "family, plus `new Set(T[])` where the array's element carrier is exactly the set's own -- a Map seeded from " +
2294
+ "family, plus `new Set(T[])`/`new Set(Set<T>)` where the source's element carrier is exactly the set's own -- a Map seeded from " +
1829
2295
  'entries needs a [K, V] pair lowering (a tuple is carried here as a record of "0"/"1" fields), and any other ' +
1830
2296
  'iterable needs the dynamic @@iterator protocol this backend does not lower');
1831
2297
  };
2298
+ /**
2299
+ * The statements of a lambda body returning a `Set<K>` seeded from `source`
2300
+ * (named `text`): an Array or Set walked in its own iteration order with each
2301
+ * element converted into `K`, or a sum of those dispatched on its live arm.
2302
+ * `null` when some element has no conversion or the source is anything else.
2303
+ */
2304
+ /**
2305
+ * `new Map(entries)` over an Array of `[K, V]` pairs (ECMA-262 24.1.1.1 ->
2306
+ * AddEntriesFromIterable): each element is read as `entry[0]`/`entry[1]` in
2307
+ * order and `set` on the new map, a later duplicate key overwriting an
2308
+ * earlier one. A tuple is carried as a positional record, so the pair's two
2309
+ * slots are its "0"/"1" fields; each goes through the one conversion
2310
+ * authority into the map's own key/value carriers. A hole is `undefined`,
2311
+ * which is not an entry object: a TypeError, as in the language.
2312
+ */
2313
+ const mapSeedText = (ctx, result, value, source, text) => {
2314
+ // A Map seeded from another Map: 24.1.1.1 walks the source's own
2315
+ // `@@iterator`, which for a Map is its entries in insertion order
2316
+ // (24.1.3.12) -- `new Map(this.servers)`, mongodb's copy-on-write of a
2317
+ // topology. Walked by insertion serial (`Map::entryAfter`), the cursor the
2318
+ // Map Iterator itself uses, each half through the one conversion authority.
2319
+ if (source.kind === 'keyed-collection' && source.family === 'map' && source.value !== null && source.ownership === 'shared-refcount') {
2320
+ const site = 'emit-callable.ts:mapSeedText:map';
2321
+ const keyText = alignedValueText(ctx, site, source.key, result.key, 'gea_entry->first');
2322
+ const valueText = alignedValueText(ctx, site, source.value, value, 'gea_entry->second');
2323
+ if (keyText === null || valueText === null)
2324
+ return null;
2325
+ const mapType = cppTypeOf({ ...result, ownership: 'owned' });
2326
+ return (`auto gea_seeded = gea::makeRef<${mapType}>(); if (${text}) { std::uint64_t gea_serial = 0; ` +
2327
+ `while (const auto* gea_entry = ${text}->entryAfter(gea_serial)) gea_seeded->set(${keyText}, ${valueText}); } return gea_seeded;`);
2328
+ }
2329
+ if (source.kind !== 'array-object' || source.ownership !== 'shared-refcount')
2330
+ return null;
2331
+ const pair = source.element;
2332
+ if (pair.kind !== 'record' || pair.fields.length !== 2)
2333
+ return null;
2334
+ const [first, second] = pair.fields;
2335
+ if (first?.key !== '0' || second?.key !== '1' || !first.required || !second.required)
2336
+ return null;
2337
+ const site = 'emit-callable.ts:mapSeedText';
2338
+ const access = pair.ownership === 'shared-refcount' ? '->' : '.';
2339
+ const keyText = alignedValueText(ctx, site, first.value, result.key, `gea_pair${access}${cppRecordFieldName('0')}`);
2340
+ const valueText = alignedValueText(ctx, site, second.value, value, `gea_pair${access}${cppRecordFieldName('1')}`);
2341
+ if (keyText === null || valueText === null)
2342
+ return null;
2343
+ const mapType = cppTypeOf({ ...result, ownership: 'owned' });
2344
+ return (`auto gea_seeded = gea::makeRef<${mapType}>(); if (${text}) for (const auto& gea_slot : ${text}->slots()) { ` +
2345
+ `if (!gea_slot.present) gea::host::throwRuntimeError("TypeError", "Iterator value undefined is not an entry object"); ` +
2346
+ `const auto& gea_pair = gea_slot.value; gea_seeded->set(${keyText}, ${valueText}); } return gea_seeded;`);
2347
+ };
2348
+ const setSeedText = (ctx, result, source, text) => {
2349
+ const setType = cppTypeOf({ ...result, ownership: 'owned' });
2350
+ const site = 'emit-callable.ts:setSeedText';
2351
+ if (source.kind === 'array-object' && source.ownership === 'shared-refcount') {
2352
+ const element = `(gea_slot.present ? gea_slot.value : ${cppTypeOf(source.element)}{})`;
2353
+ const converted = alignedValueText(ctx, site, source.element, result.key, element);
2354
+ if (converted === null)
2355
+ return null;
2356
+ return (`auto gea_seeded = gea::makeRef<${setType}>(); if (${text}) for (const auto& gea_slot : ${text}->slots()) gea_seeded->add(${converted}); ` +
2357
+ 'return gea_seeded;');
2358
+ }
2359
+ if (source.kind === 'keyed-collection' && source.family === 'set' && source.ownership === 'shared-refcount') {
2360
+ const converted = alignedValueText(ctx, site, source.key, result.key, '(*gea_item)');
2361
+ if (converted === null)
2362
+ return null;
2363
+ return (`auto gea_seeded = gea::makeRef<${setType}>(); if (${text}) { std::uint64_t gea_serial = 0; ` +
2364
+ `while (const auto* gea_item = ${text}->itemAfter(gea_serial)) gea_seeded->add(${converted}); } return gea_seeded;`);
2365
+ }
2366
+ // A native cursor (`map.keys()`, a generator): 24.2.1.1 drains the
2367
+ // iterator it is handed, each value `add`ed as it is produced.
2368
+ if (source.kind === 'iterator') {
2369
+ const converted = alignedValueText(ctx, site, source.element, result.key, 'gea_value');
2370
+ if (converted === null)
2371
+ return null;
2372
+ return (`auto gea_seeded = gea::makeRef<${setType}>(); auto gea_cursor = ${text}; while (true) { ` +
2373
+ `auto gea_value = gea_cursor.arrayNext(); if (gea_cursor.done()) break; gea_seeded->add(${converted}); } return gea_seeded;`);
2374
+ }
2375
+ if (source.kind === 'tagged-union' && source.arms.length > 0) {
2376
+ const arms = source.arms.map((arm, index) => {
2377
+ const body = setSeedText(ctx, result, arm.value, `gea_seed_arm_${index}`);
2378
+ return body === null
2379
+ ? null
2380
+ : `if (${text}.template is<${index}>()) { const auto& gea_seed_arm_${index} = ${text}.template get<${index}>(); ${body} }`;
2381
+ });
2382
+ if (arms.some((arm) => arm === null))
2383
+ return null;
2384
+ return `${arms.join(' ')} gea::detail::refusePayloadMismatch("a Set seed whose live arm is none of its own"); return {};`;
2385
+ }
2386
+ return null;
2387
+ };
1832
2388
  /**
1833
2389
  * `new RegExp(pattern)`, `new RegExp(pattern, flags)` and the two
1834
2390
  * pattern-copying forms (ECMA-262 22.2.4.1).
@@ -1849,14 +2405,26 @@ const emitKeyedCollectionConstruct = (ctx, lines, operation, result) => {
1849
2405
  * unknown or repeated flag throws where the language says it throws.
1850
2406
  */
1851
2407
  const emitRegExpConstruct = (ctx, lines, operation) => {
1852
- const args = operation.arguments;
2408
+ lines.push(`${defineValue(ctx, operation.result)} = ${regExpCreationText(ctx, operation.arguments, 'construct')};`);
2409
+ };
2410
+ /**
2411
+ * The value of `new RegExp(...)` or of `RegExp(...)` called as a function.
2412
+ *
2413
+ * The two differ in exactly one step (22.2.4.1 step 2.b): called without
2414
+ * `new`, a pattern that already IS a RegExp, with `flags` undefined, is
2415
+ * returned as itself (its `constructor` is `%RegExp%` unless the program
2416
+ * rewrote it, which a `Pattern` carrier has no slot to do). Every other call
2417
+ * builds a new pattern exactly as the construction does.
2418
+ */
2419
+ export const regExpCreationText = (ctx, args, role) => {
2420
+ const refusal = (message) => role === 'construct'
2421
+ ? createCppEmitBlockedError('call-abi:construct:regexp', message)
2422
+ : createCppEmitBlockedError('host-invocation:RegExpConstructor.call', message);
1853
2423
  if (args.length > 2) {
1854
- throw createCppEmitBlockedError('call-abi:construct:regexp', `constructs a RegExp from ${args.length} argument(s); ECMA-262 22.2.4.1 takes a pattern and an optional flags string`);
1855
- }
1856
- if (args.length === 0) {
1857
- lines.push(`${defineValue(ctx, operation.result)} = ${cppConstructPatternEntry}(std::string());`);
1858
- return;
2424
+ throw refusal(`creates a RegExp from ${args.length} argument(s); ECMA-262 22.2.4.1 takes a pattern and an optional flags string`);
1859
2425
  }
2426
+ if (args.length === 0)
2427
+ return `${cppConstructPatternEntry}(std::string())`;
1860
2428
  const spellingOf = (argument, position) => {
1861
2429
  const carrier = argument.representation;
1862
2430
  if (carrier.kind === 'dynamic')
@@ -1865,31 +2433,27 @@ const emitRegExpConstruct = (ctx, lines, operation) => {
1865
2433
  return operandText(ctx, argument);
1866
2434
  if (position === 0 && regexpRoleOf(carrier) === 'pattern')
1867
2435
  return operandText(ctx, argument);
1868
- throw createCppEmitBlockedError(`conversion:${representationKey(carrier)}->string`, `"new RegExp" argument ${position} carries "${representationKey(carrier)}"; this backend spells it for a string` +
2436
+ throw createCppEmitBlockedError(`conversion:${representationKey(carrier)}->string`, `"RegExp" argument ${position} carries "${representationKey(carrier)}"; this backend spells it for a string` +
1869
2437
  (position === 0 ? ` or an existing ${cppRegExpNativeTypes.pattern}` : '') +
1870
2438
  ', and ECMA-262 22.2.4.1 ToStrings anything else -- ToString of an arbitrary value is what this backend has no box for');
1871
2439
  };
1872
2440
  const patternArgument = args[0];
1873
2441
  if (!patternArgument)
1874
- throw createCppEmitBlockedError('call-abi:construct:regexp', 'a RegExp construction with an argument has no pattern operand');
2442
+ throw refusal('a RegExp creation with an argument has no pattern operand');
1875
2443
  const flag = args[1];
2444
+ if (role === 'call' && flag === undefined && regexpRoleOf(patternArgument.representation) === 'pattern') {
2445
+ return operandText(ctx, patternArgument);
2446
+ }
1876
2447
  // Steps 5-7 over an ordinary OBJECT pattern. Step 5 is already `false` here
1877
2448
  // -- a value carrying `[[RegExpMatcher]]` is the `Pattern` carrier
1878
2449
  // `spellingOf` hands straight through -- so what remains is `patternIsRegExp`
1879
2450
  // choosing between the object's own `source`/`flags` and a ToString of it.
1880
2451
  const fromObject = regExpConstructionFromObject(ctx, patternArgument, flag ?? null);
1881
- if (fromObject !== null) {
1882
- lines.push(`${defineValue(ctx, operation.result)} = ${fromObject};`);
1883
- return;
1884
- }
2452
+ if (fromObject !== null)
2453
+ return fromObject;
1885
2454
  const pattern = spellingOf(patternArgument, 0);
1886
2455
  const rendered = flag ? spellingOf(flag, 1) : null;
1887
- const name = defineValue(ctx, operation.result);
1888
- if (rendered === null) {
1889
- lines.push(`${name} = ${cppConstructPatternEntry}(${pattern});`);
1890
- return;
1891
- }
1892
- lines.push(`${name} = ${cppConstructPatternEntry}(${pattern}, ${rendered});`);
2456
+ return rendered === null ? `${cppConstructPatternEntry}(${pattern})` : `${cppConstructPatternEntry}(${pattern}, ${rendered})`;
1893
2457
  };
1894
2458
  /** Reconcile one [[Construct]] branch's declared result with the carrier selected for the `new` expression. */
1895
2459
  const constructResultText = (ctx, source, target, text) => {
@@ -2060,10 +2624,11 @@ export const emitConstruct = (ctx, lines, operation) => {
2060
2624
  emitRegExpConstruct(ctx, lines, operation);
2061
2625
  return;
2062
2626
  }
2063
- if (!callee.construct) {
2627
+ const constructFrame = hostConstructFrameOf(operation);
2628
+ if (!constructFrame) {
2064
2629
  throw createCppEmitBlockedError(`host-invocation:${callee.native ?? callee.protocol}`, `a "${callee.protocol}" host handle carries no [[Construct]] convention this program's checker derived for it`);
2065
2630
  }
2066
- const invocation = nativeHandleInvocationText(ctx, callee, callee.construct, operation.arguments, 'construct', result);
2631
+ const invocation = nativeHandleInvocationText(ctx, callee, constructFrame, operation.arguments, 'construct', result);
2067
2632
  const name = defineValue(ctx, operation.result);
2068
2633
  lines.push(`${name} = ${invocation};`);
2069
2634
  return;