@geastack/compiler 1.0.19 → 1.0.21

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 (535) 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 +118 -28
  9. package/dist/conversion/algebra.d.ts +16 -1
  10. package/dist/conversion/algebra.js +2 -0
  11. package/dist/conversion/build.js +16 -6
  12. package/dist/conversion/constructor-identity-family.d.ts +49 -0
  13. package/dist/conversion/constructor-identity-family.js +67 -0
  14. package/dist/conversion/derive.js +39 -6
  15. package/dist/conversion/iterable-object-view.d.ts +44 -0
  16. package/dist/conversion/iterable-object-view.js +55 -0
  17. package/dist/conversion/iterator-object-view.d.ts +77 -0
  18. package/dist/conversion/iterator-object-view.js +112 -0
  19. package/dist/conversion/nodes.d.ts +93 -0
  20. package/dist/conversion/nodes.js +262 -5
  21. package/dist/conversion/operand-view.js +41 -0
  22. package/dist/conversion/protocol-iterator.d.ts +84 -0
  23. package/dist/conversion/protocol-iterator.js +88 -0
  24. package/dist/conversion/record-view.d.ts +152 -8
  25. package/dist/conversion/record-view.js +518 -37
  26. package/dist/conversion/registry.d.ts +32 -0
  27. package/dist/ir/borrowed-call-arguments.d.ts +22 -1
  28. package/dist/ir/borrowed-call-arguments.js +102 -1
  29. package/dist/ir/borrowed-callable-uses.d.ts +62 -0
  30. package/dist/ir/borrowed-callable-uses.js +135 -0
  31. package/dist/ir/boxed-bind-assumptions.d.ts +24 -0
  32. package/dist/ir/boxed-bind-assumptions.js +93 -0
  33. package/dist/ir/build.d.ts +18 -7
  34. package/dist/ir/build.js +71 -13
  35. package/dist/ir/call-dispatch.js +474 -10
  36. package/dist/ir/call-entry.d.ts +24 -1
  37. package/dist/ir/call-entry.js +106 -1
  38. package/dist/ir/callable-class-flow.js +15 -5
  39. package/dist/ir/callable-identity-demand.d.ts +20 -1
  40. package/dist/ir/callable-identity-demand.js +157 -18
  41. package/dist/ir/callable-member-candidates.d.ts +11 -1
  42. package/dist/ir/callable-member-candidates.js +82 -3
  43. package/dist/ir/callable-records.js +2 -2
  44. package/dist/ir/callable-site-escape.d.ts +4 -0
  45. package/dist/ir/callable-site-escape.js +228 -0
  46. package/dist/ir/captures.d.ts +10 -1
  47. package/dist/ir/captures.js +219 -4
  48. package/dist/ir/certify/carrier-keys.d.ts +58 -1
  49. package/dist/ir/certify/carrier-keys.js +158 -6
  50. package/dist/ir/certify/property-access-keys.d.ts +17 -0
  51. package/dist/ir/certify/property-access-keys.js +36 -0
  52. package/dist/ir/certify/property-access.js +49 -4
  53. package/dist/ir/certify/runtime-helper.d.ts +4 -0
  54. package/dist/ir/certify/runtime-helper.js +17 -5
  55. package/dist/ir/certify.js +132 -79
  56. package/dist/ir/class-static-fields.d.ts +11 -0
  57. package/dist/ir/class-static-fields.js +28 -0
  58. package/dist/ir/construct-entry.d.ts +2 -1
  59. package/dist/ir/construct-entry.js +3 -2
  60. package/dist/ir/construction-only-fields.d.ts +73 -0
  61. package/dist/ir/construction-only-fields.js +211 -0
  62. package/dist/ir/dominance.d.ts +14 -0
  63. package/dist/ir/dominance.js +18 -4
  64. package/dist/ir/emission-representations.js +4 -1
  65. package/dist/ir/exception-edges.d.ts +17 -0
  66. package/dist/ir/exception-edges.js +75 -0
  67. package/dist/ir/facts.d.ts +54 -3
  68. package/dist/ir/facts.js +182 -5
  69. package/dist/ir/generator-split.js +2 -2
  70. package/dist/ir/instance-reparenting.d.ts +83 -0
  71. package/dist/ir/instance-reparenting.js +167 -0
  72. package/dist/ir/integer-storage.d.ts +29 -0
  73. package/dist/ir/integer-storage.js +188 -79
  74. package/dist/ir/integers.d.ts +16 -0
  75. package/dist/ir/integers.js +327 -8
  76. package/dist/ir/integrity-restrictions.d.ts +42 -9
  77. package/dist/ir/integrity-restrictions.js +335 -42
  78. package/dist/ir/key-order-observation.d.ts +38 -0
  79. package/dist/ir/key-order-observation.js +173 -0
  80. package/dist/ir/literal-set-membership.d.ts +30 -0
  81. package/dist/ir/literal-set-membership.js +277 -0
  82. package/dist/ir/lower-allocation.js +68 -8
  83. package/dist/ir/lower-completion.d.ts +0 -9
  84. package/dist/ir/lower-completion.js +14 -5
  85. package/dist/ir/lower-destructuring.js +24 -2
  86. package/dist/ir/lower-exceptions.js +4 -4
  87. package/dist/ir/lower-flow.d.ts +21 -0
  88. package/dist/ir/lower-flow.js +37 -3
  89. package/dist/ir/lower-graph.d.ts +19 -1
  90. package/dist/ir/lower-graph.js +91 -67
  91. package/dist/ir/lower-invocation.d.ts +16 -0
  92. package/dist/ir/lower-invocation.js +182 -28
  93. package/dist/ir/lower-narrow.d.ts +0 -46
  94. package/dist/ir/lower-narrow.js +63 -1
  95. package/dist/ir/lower-operands.d.ts +52 -2
  96. package/dist/ir/lower-operands.js +491 -8
  97. package/dist/ir/lower-property.d.ts +2 -1
  98. package/dist/ir/lower-property.js +140 -31
  99. package/dist/ir/lower-protocol.js +16 -4
  100. package/dist/ir/lower-proxy.d.ts +65 -0
  101. package/dist/ir/lower-proxy.js +181 -0
  102. package/dist/ir/lower.js +112 -17
  103. package/dist/ir/model.d.ts +228 -18
  104. package/dist/ir/native-class-accessor.d.ts +9 -2
  105. package/dist/ir/native-class-accessor.js +12 -3
  106. package/dist/ir/native-class-construction.d.ts +1 -1
  107. package/dist/ir/native-class-construction.js +2 -1
  108. package/dist/ir/native-class-initialization.js +2 -2
  109. package/dist/ir/object-value-conversions.js +20 -5
  110. package/dist/ir/operation-index.d.ts +16 -0
  111. package/dist/ir/operation-index.js +17 -0
  112. package/dist/ir/pcm-loops.d.ts +11 -0
  113. package/dist/ir/pcm-loops.js +284 -0
  114. package/dist/ir/presence-proof.js +5 -0
  115. package/dist/ir/program-facts.d.ts +10 -20
  116. package/dist/ir/program-facts.js +80 -6
  117. package/dist/ir/proven-branches.d.ts +2 -2
  118. package/dist/ir/proven-branches.js +196 -3
  119. package/dist/ir/queries.js +35 -1
  120. package/dist/ir/reflection-demand.d.ts +9 -4
  121. package/dist/ir/reflection-demand.js +400 -28
  122. package/dist/ir/refusal.d.ts +1 -0
  123. package/dist/ir/refusal.js +2 -1
  124. package/dist/ir/shake.d.ts +94 -1
  125. package/dist/ir/shake.js +209 -12
  126. package/dist/ir/shared-empty-records.d.ts +12 -0
  127. package/dist/ir/shared-empty-records.js +301 -0
  128. package/dist/ir/spread-copy-elision.d.ts +59 -0
  129. package/dist/ir/spread-copy-elision.js +431 -0
  130. package/dist/ir/stable-cell-reads.d.ts +40 -0
  131. package/dist/ir/stable-cell-reads.js +123 -0
  132. package/dist/ir/static-callables.js +50 -0
  133. package/dist/ir/string-layout-reuse.d.ts +16 -1
  134. package/dist/ir/string-layout-reuse.js +66 -0
  135. package/dist/ir/transfer.d.ts +72 -3
  136. package/dist/ir/transfer.js +511 -19
  137. package/dist/ir/typed-property-access.d.ts +18 -2
  138. package/dist/ir/typed-property-access.js +109 -12
  139. package/dist/ir/verify.js +2 -1
  140. package/dist/plugins/apple/plugin.js +3 -2
  141. package/dist/plugins/gea/host.d.ts +7 -0
  142. package/dist/plugins/gea/host.js +30 -1
  143. package/dist/plugins/gea/lower.js +6 -1
  144. package/dist/plugins/gea/plugin.js +7 -4
  145. package/dist/plugins/gea/prelude.js +5 -1
  146. package/dist/plugins/gea/render-bridge.d.ts +4 -2
  147. package/dist/plugins/gea/render-bridge.js +23 -7
  148. package/dist/plugins/model.d.ts +2 -0
  149. package/dist/project-preparation.d.ts +5 -1
  150. package/dist/project-preparation.js +164 -7
  151. package/dist/projection/bindings.d.ts +5 -2
  152. package/dist/projection/bindings.js +40 -1
  153. package/dist/projection/callee.d.ts +16 -0
  154. package/dist/projection/callee.js +35 -6
  155. package/dist/projection/class-prototype.js +5 -1
  156. package/dist/projection/classes.d.ts +65 -2
  157. package/dist/projection/classes.js +159 -2
  158. package/dist/projection/dispatch.d.ts +69 -18
  159. package/dist/projection/dispatch.js +391 -19
  160. package/dist/projection/fields.d.ts +4 -3
  161. package/dist/projection/fields.js +89 -21
  162. package/dist/projection/instance-test.d.ts +12 -0
  163. package/dist/projection/instance-test.js +40 -10
  164. package/dist/projection/method-value-escapes.d.ts +43 -0
  165. package/dist/projection/method-value-escapes.js +113 -0
  166. package/dist/projection/slots.d.ts +34 -1
  167. package/dist/projection/slots.js +82 -5
  168. package/dist/representation/any-null-record-members.d.ts +41 -0
  169. package/dist/representation/any-null-record-members.js +115 -0
  170. package/dist/representation/collections.d.ts +3 -1
  171. package/dist/representation/collections.js +5 -2
  172. package/dist/representation/derive.d.ts +9 -1
  173. package/dist/representation/derive.js +366 -25
  174. package/dist/representation/difference.js +14 -0
  175. package/dist/representation/embedded-carriers.js +1 -0
  176. package/dist/representation/host-abi.d.ts +15 -0
  177. package/dist/representation/host-abi.js +28 -0
  178. package/dist/representation/host-templates.d.ts +1 -1
  179. package/dist/representation/host-templates.js +7 -3
  180. package/dist/representation/intersection.js +22 -0
  181. package/dist/representation/json-nullable.d.ts +18 -0
  182. package/dist/representation/json-nullable.js +22 -0
  183. package/dist/representation/model.d.ts +141 -0
  184. package/dist/representation/model.js +47 -3
  185. package/dist/representation/object-shape.d.ts +5 -1
  186. package/dist/representation/object-shape.js +5 -2
  187. package/dist/representation/policies.d.ts +66 -1
  188. package/dist/representation/proxy-carriers.d.ts +71 -0
  189. package/dist/representation/proxy-carriers.js +330 -0
  190. package/dist/representation/publish.d.ts +9 -1
  191. package/dist/representation/publish.js +186 -18
  192. package/dist/representation/record-fields.d.ts +5 -0
  193. package/dist/representation/record-fields.js +7 -1
  194. package/dist/representation/static-field-cells.d.ts +61 -0
  195. package/dist/representation/static-field-cells.js +80 -0
  196. package/dist/representation/unassigned-binding-cells.d.ts +32 -0
  197. package/dist/representation/unassigned-binding-cells.js +44 -0
  198. package/dist/representation/union.js +17 -1
  199. package/dist/representation/unwritten-record-members.d.ts +54 -0
  200. package/dist/representation/unwritten-record-members.js +167 -0
  201. package/dist/representation/value-records.js +153 -11
  202. package/dist/semantics/ambient.d.ts +102 -0
  203. package/dist/semantics/ambient.js +183 -0
  204. package/dist/semantics/any-null-member-declarations.d.ts +32 -0
  205. package/dist/semantics/any-null-member-declarations.js +90 -0
  206. package/dist/semantics/borrowed-builtin-call-bind-source-transform.js +14 -0
  207. package/dist/semantics/borrowed-method-receiver-copy-source-transform.d.ts +51 -0
  208. package/dist/semantics/borrowed-method-receiver-copy-source-transform.js +367 -0
  209. package/dist/semantics/call-invalidated-narrowing.d.ts +3 -0
  210. package/dist/semantics/call-invalidated-narrowing.js +715 -0
  211. package/dist/semantics/callable-origins.d.ts +39 -0
  212. package/dist/semantics/callable-origins.js +73 -2
  213. package/dist/semantics/class-alias.d.ts +21 -0
  214. package/dist/semantics/class-alias.js +45 -14
  215. package/dist/semantics/class-heritage.d.ts +64 -0
  216. package/dist/semantics/class-heritage.js +278 -2
  217. package/dist/semantics/commonjs-wrapper.d.ts +1 -1
  218. package/dist/semantics/commonjs-wrapper.js +24 -7
  219. package/dist/semantics/constructor-function-class-source-transform.d.ts +4 -0
  220. package/dist/semantics/constructor-function-class-source-transform.js +327 -0
  221. package/dist/semantics/constructor-slot-subclasses.js +163 -4
  222. package/dist/semantics/declaration-overlay-transform.js +197 -3
  223. package/dist/semantics/frontend.d.ts +31 -0
  224. package/dist/semantics/frontend.js +177 -19
  225. package/dist/semantics/host-methods.d.ts +27 -2
  226. package/dist/semantics/host-methods.js +57 -4
  227. package/dist/semantics/host-protocols.d.ts +19 -8
  228. package/dist/semantics/host-protocols.js +145 -31
  229. package/dist/semantics/interface-families.d.ts +51 -2
  230. package/dist/semantics/interface-families.js +609 -23
  231. package/dist/semantics/interface-implementors.d.ts +20 -0
  232. package/dist/semantics/interface-implementors.js +130 -6
  233. package/dist/semantics/known-caller-predicate-parameters.d.ts +2 -0
  234. package/dist/semantics/known-caller-predicate-parameters.js +161 -0
  235. package/dist/semantics/model/intrinsic-accessor-getters.d.ts +10 -0
  236. package/dist/semantics/model/intrinsic-accessor-getters.js +4 -0
  237. package/dist/semantics/model/operands.d.ts +10 -0
  238. package/dist/semantics/model/operations.d.ts +107 -0
  239. package/dist/semantics/model/selected-signature.d.ts +33 -0
  240. package/dist/semantics/model/structural-type-table.d.ts +15 -0
  241. package/dist/semantics/model/structural-type-table.js +19 -1
  242. package/dist/semantics/model/structural-types.d.ts +99 -0
  243. package/dist/semantics/model/structural-types.js +31 -2
  244. package/dist/semantics/normalize/absent-globals.d.ts +1 -1
  245. package/dist/semantics/normalize/absent-globals.js +3 -3
  246. package/dist/semantics/normalize/bivariant-slot-parameter.d.ts +46 -0
  247. package/dist/semantics/normalize/bivariant-slot-parameter.js +357 -0
  248. package/dist/semantics/normalize/callback-parameter-contracts.d.ts +2 -0
  249. package/dist/semantics/normalize/callback-parameter-contracts.js +21 -0
  250. package/dist/semantics/normalize/census.d.ts +2 -1
  251. package/dist/semantics/normalize/census.js +25 -2
  252. package/dist/semantics/normalize/class-instance-record-statement.d.ts +37 -0
  253. package/dist/semantics/normalize/class-instance-record-statement.js +74 -0
  254. package/dist/semantics/normalize/collection-bindings.js +242 -5
  255. package/dist/semantics/normalize/commonjs-require.d.ts +26 -0
  256. package/dist/semantics/normalize/commonjs-require.js +355 -121
  257. package/dist/semantics/normalize/dead-event-emissions.d.ts +6 -0
  258. package/dist/semantics/normalize/dead-event-emissions.js +866 -0
  259. package/dist/semantics/normalize/dead-method-copies.d.ts +56 -0
  260. package/dist/semantics/normalize/dead-method-copies.js +239 -0
  261. package/dist/semantics/normalize/derived-expression-type.d.ts +149 -2
  262. package/dist/semantics/normalize/derived-expression-type.js +418 -14
  263. package/dist/semantics/normalize/field-bindings.js +139 -4
  264. package/dist/semantics/normalize/flow/callable-reach.js +162 -9
  265. package/dist/semantics/normalize/flow/member-call-forwarding.js +6 -0
  266. package/dist/semantics/normalize/flow/owned-class-receivers.js +40 -2
  267. package/dist/semantics/normalize/flow/source-class-data.d.ts +7 -1
  268. package/dist/semantics/normalize/flow/source-class-data.js +28 -9
  269. package/dist/semantics/normalize/flow/source-value-session.js +32 -13
  270. package/dist/semantics/normalize/flow/targets.d.ts +32 -0
  271. package/dist/semantics/normalize/flow/targets.js +65 -6
  272. package/dist/semantics/normalize/flow/value-flow.d.ts +7 -0
  273. package/dist/semantics/normalize/flow/value-flow.js +30 -2
  274. package/dist/semantics/normalize/fresh-array-result.d.ts +32 -0
  275. package/dist/semantics/normalize/fresh-array-result.js +125 -0
  276. package/dist/semantics/normalize/gating.js +2 -0
  277. package/dist/semantics/normalize/global-host-mutations.d.ts +11 -1
  278. package/dist/semantics/normalize/global-host-mutations.js +691 -27
  279. package/dist/semantics/normalize/host-effect-contracts.d.ts +43 -1
  280. package/dist/semantics/normalize/host-effect-contracts.js +60 -3
  281. package/dist/semantics/normalize/identities.js +49 -3
  282. package/dist/semantics/normalize/intrinsic-accessor-getter.d.ts +59 -0
  283. package/dist/semantics/normalize/intrinsic-accessor-getter.js +129 -0
  284. package/dist/semantics/normalize/local-bindings.js +117 -21
  285. package/dist/semantics/normalize/merged-declaration.d.ts +41 -0
  286. package/dist/semantics/normalize/merged-declaration.js +81 -0
  287. package/dist/semantics/normalize/never-override-result.d.ts +21 -0
  288. package/dist/semantics/normalize/never-override-result.js +64 -0
  289. package/dist/semantics/normalize/null-blind-parameter.d.ts +21 -0
  290. package/dist/semantics/normalize/null-blind-parameter.js +77 -0
  291. package/dist/semantics/normalize/object-bag-bindings.js +10 -0
  292. package/dist/semantics/normalize/override-field-arms.d.ts +33 -0
  293. package/dist/semantics/normalize/override-field-arms.js +362 -0
  294. package/dist/semantics/normalize/parameter-bindings.d.ts +64 -1
  295. package/dist/semantics/normalize/parameter-bindings.js +801 -81
  296. package/dist/semantics/normalize/parameter-slot.d.ts +1 -0
  297. package/dist/semantics/normalize/parameter-slot.js +69 -0
  298. package/dist/semantics/normalize/physical-overload-result.d.ts +45 -0
  299. package/dist/semantics/normalize/physical-overload-result.js +132 -0
  300. package/dist/semantics/normalize/producer-context.d.ts +23 -0
  301. package/dist/semantics/normalize/producers/allocations.d.ts +13 -0
  302. package/dist/semantics/normalize/producers/allocations.js +8 -15
  303. package/dist/semantics/normalize/producers/binding-kind.d.ts +11 -0
  304. package/dist/semantics/normalize/producers/binding-kind.js +31 -0
  305. package/dist/semantics/normalize/producers/bindings.js +16 -1
  306. package/dist/semantics/normalize/producers/boundary.js +21 -1
  307. package/dist/semantics/normalize/producers/class-lifecycle.js +23 -14
  308. package/dist/semantics/normalize/producers/computations.js +8 -67
  309. package/dist/semantics/normalize/producers/control-loops.d.ts +1 -1
  310. package/dist/semantics/normalize/producers/control-loops.js +25 -1
  311. package/dist/semantics/normalize/producers/control.js +87 -60
  312. package/dist/semantics/normalize/producers/declaration-lifecycle.js +5 -0
  313. package/dist/semantics/normalize/producers/enums.d.ts +10 -0
  314. package/dist/semantics/normalize/producers/enums.js +169 -0
  315. package/dist/semantics/normalize/producers/erasure.d.ts +10 -0
  316. package/dist/semantics/normalize/producers/erasure.js +23 -0
  317. package/dist/semantics/normalize/producers/intrinsic-accessor-getter.d.ts +15 -0
  318. package/dist/semantics/normalize/producers/intrinsic-accessor-getter.js +33 -0
  319. package/dist/semantics/normalize/producers/invocations.js +255 -18
  320. package/dist/semantics/normalize/producers/iteration-yield.js +6 -1
  321. package/dist/semantics/normalize/producers/logical-merge-type.d.ts +36 -0
  322. package/dist/semantics/normalize/producers/logical-merge-type.js +163 -0
  323. package/dist/semantics/normalize/producers/properties.js +207 -18
  324. package/dist/semantics/normalize/producers/protocol.d.ts +4 -0
  325. package/dist/semantics/normalize/producers/protocol.js +147 -12
  326. package/dist/semantics/normalize/producers/references.js +50 -9
  327. package/dist/semantics/normalize/producers/shared.d.ts +120 -0
  328. package/dist/semantics/normalize/producers/shared.js +359 -10
  329. package/dist/semantics/normalize/producers/spread-arguments.js +85 -4
  330. package/dist/semantics/normalize/producers/tuple-spread.d.ts +1 -0
  331. package/dist/semantics/normalize/producers/tuple-spread.js +1 -1
  332. package/dist/semantics/normalize/property-key-domain.js +6 -0
  333. package/dist/semantics/normalize/reachability.d.ts +7 -0
  334. package/dist/semantics/normalize/reachability.js +166 -9
  335. package/dist/semantics/normalize/record-home-arms.d.ts +25 -0
  336. package/dist/semantics/normalize/record-home-arms.js +87 -0
  337. package/dist/semantics/normalize/record-link-families.d.ts +74 -0
  338. package/dist/semantics/normalize/record-link-families.js +327 -0
  339. package/dist/semantics/normalize/record-stand-in-arms.d.ts +56 -0
  340. package/dist/semantics/normalize/record-stand-in-arms.js +484 -0
  341. package/dist/semantics/normalize/return-bindings.d.ts +6 -2
  342. package/dist/semantics/normalize/return-bindings.js +60 -7
  343. package/dist/semantics/normalize/script-global-redefinition.js +5 -0
  344. package/dist/semantics/normalize/shared-array-storage.d.ts +42 -0
  345. package/dist/semantics/normalize/shared-array-storage.js +373 -0
  346. package/dist/semantics/normalize/sloppy-absence.d.ts +41 -0
  347. package/dist/semantics/normalize/sloppy-absence.js +199 -0
  348. package/dist/semantics/normalize/specialization.d.ts +40 -0
  349. package/dist/semantics/normalize/specialization.js +770 -36
  350. package/dist/semantics/normalize/structural-array-element.js +196 -6
  351. package/dist/semantics/normalize/structural-array-read.js +12 -0
  352. package/dist/semantics/normalize/structural-creation-order.d.ts +15 -0
  353. package/dist/semantics/normalize/structural-creation-order.js +51 -48
  354. package/dist/semantics/normalize/structural-declarations.d.ts +16 -0
  355. package/dist/semantics/normalize/structural-declarations.js +43 -0
  356. package/dist/semantics/normalize/structural-generics.d.ts +13 -0
  357. package/dist/semantics/normalize/structural-generics.js +22 -0
  358. package/dist/semantics/normalize/structural-indexed-access.js +16 -0
  359. package/dist/semantics/normalize/structural-instantiated-member.js +68 -2
  360. package/dist/semantics/normalize/structural-joins.js +2 -0
  361. package/dist/semantics/normalize/structural-layout-relevance.d.ts +30 -0
  362. package/dist/semantics/normalize/structural-layout-relevance.js +164 -0
  363. package/dist/semantics/normalize/structural-layout-type.js +270 -14
  364. package/dist/semantics/normalize/structural-leaves.d.ts +1 -1
  365. package/dist/semantics/normalize/structural-leaves.js +17 -3
  366. package/dist/semantics/normalize/structural-mutable-method.js +5 -1
  367. package/dist/semantics/normalize/structural-parts.d.ts +18 -5
  368. package/dist/semantics/normalize/structural-parts.js +68 -19
  369. package/dist/semantics/normalize/structural-receiver.d.ts +1 -1
  370. package/dist/semantics/normalize/structural-receiver.js +23 -1
  371. package/dist/semantics/normalize/structural-self-reference.d.ts +1 -1
  372. package/dist/semantics/normalize/structural-self-reference.js +23 -2
  373. package/dist/semantics/normalize/structural.d.ts +12 -1
  374. package/dist/semantics/normalize/structural.js +1420 -53
  375. package/dist/semantics/normalize/suppressed-write-arms.d.ts +47 -0
  376. package/dist/semantics/normalize/suppressed-write-arms.js +393 -0
  377. package/dist/semantics/normalize/unresolvable-names.d.ts +15 -2
  378. package/dist/semantics/normalize/unresolvable-names.js +30 -6
  379. package/dist/semantics/normalize/unshared-array-result.d.ts +32 -0
  380. package/dist/semantics/normalize/unshared-array-result.js +125 -0
  381. package/dist/semantics/package-sources.d.ts +1 -1
  382. package/dist/semantics/package-sources.js +120 -8
  383. package/dist/semantics/program.d.ts +20 -0
  384. package/dist/semantics/program.js +145 -14
  385. package/dist/semantics/stable-checker.d.ts +1 -1
  386. package/dist/semantics/stable-checker.js +7 -2
  387. package/dist/semantics/unchecked-guard-argument-copies.d.ts +67 -0
  388. package/dist/semantics/unchecked-guard-argument-copies.js +163 -0
  389. package/dist/semantics/unchecked-write-member-declarations.d.ts +46 -0
  390. package/dist/semantics/unchecked-write-member-declarations.js +331 -0
  391. package/dist/targets/cpp/balanced-units.d.ts +31 -0
  392. package/dist/targets/cpp/balanced-units.js +57 -0
  393. package/dist/targets/cpp/borrowed-arm-projections.d.ts +31 -0
  394. package/dist/targets/cpp/borrowed-arm-projections.js +106 -0
  395. package/dist/targets/cpp/borrowed-call-entry.d.ts +1 -1
  396. package/dist/targets/cpp/borrowed-call-entry.js +24 -20
  397. package/dist/targets/cpp/captures.js +314 -8
  398. package/dist/targets/cpp/char-code-buffers.d.ts +36 -0
  399. package/dist/targets/cpp/char-code-buffers.js +214 -0
  400. package/dist/targets/cpp/class-layout.d.ts +7 -1
  401. package/dist/targets/cpp/class-layout.js +42 -17
  402. package/dist/targets/cpp/class-properties/computed-method-value.d.ts +17 -2
  403. package/dist/targets/cpp/class-properties/computed-method-value.js +50 -4
  404. package/dist/targets/cpp/class-properties/emit-class-properties.d.ts +31 -1
  405. package/dist/targets/cpp/class-properties/emit-class-properties.js +174 -17
  406. package/dist/targets/cpp/class-ref-transport.d.ts +32 -0
  407. package/dist/targets/cpp/class-ref-transport.js +56 -1
  408. package/dist/targets/cpp/conversions.js +1827 -1502
  409. package/dist/targets/cpp/coroutine-bodies.d.ts +97 -0
  410. package/dist/targets/cpp/coroutine-bodies.js +187 -0
  411. package/dist/targets/cpp/document.js +11 -1
  412. package/dist/targets/cpp/emit-allocation.js +535 -21
  413. package/dist/targets/cpp/emit-arrays.d.ts +10 -0
  414. package/dist/targets/cpp/emit-arrays.js +147 -16
  415. package/dist/targets/cpp/emit-binding-reference.d.ts +26 -2
  416. package/dist/targets/cpp/emit-binding-reference.js +97 -5
  417. package/dist/targets/cpp/emit-bindings.d.ts +9 -1
  418. package/dist/targets/cpp/emit-bindings.js +108 -8
  419. package/dist/targets/cpp/emit-buffers.d.ts +2 -16
  420. package/dist/targets/cpp/emit-buffers.js +124 -25
  421. package/dist/targets/cpp/emit-callable.d.ts +35 -72
  422. package/dist/targets/cpp/emit-callable.js +647 -82
  423. package/dist/targets/cpp/emit-carrier-members.d.ts +13 -2
  424. package/dist/targets/cpp/emit-carrier-members.js +50 -9
  425. package/dist/targets/cpp/emit-constructor-identity-family.d.ts +20 -0
  426. package/dist/targets/cpp/emit-constructor-identity-family.js +45 -0
  427. package/dist/targets/cpp/emit-context.d.ts +329 -15
  428. package/dist/targets/cpp/emit-context.js +104 -13
  429. package/dist/targets/cpp/emit-dynamic-properties.d.ts +44 -0
  430. package/dist/targets/cpp/emit-dynamic-properties.js +256 -37
  431. package/dist/targets/cpp/emit-equality.js +117 -2
  432. package/dist/targets/cpp/emit-error-constructor.d.ts +19 -0
  433. package/dist/targets/cpp/emit-error-constructor.js +73 -0
  434. package/dist/targets/cpp/emit-exceptions.d.ts +25 -3
  435. package/dist/targets/cpp/emit-exceptions.js +215 -26
  436. package/dist/targets/cpp/emit-in.js +52 -5
  437. package/dist/targets/cpp/emit-instanceof.js +59 -11
  438. package/dist/targets/cpp/emit-integers.d.ts +6 -0
  439. package/dist/targets/cpp/emit-integers.js +10 -0
  440. package/dist/targets/cpp/emit-iterable-object-view.d.ts +15 -0
  441. package/dist/targets/cpp/emit-iterable-object-view.js +51 -0
  442. package/dist/targets/cpp/emit-iterator-object-view.d.ts +15 -0
  443. package/dist/targets/cpp/emit-iterator-object-view.js +125 -0
  444. package/dist/targets/cpp/emit-iterator.d.ts +7 -10
  445. package/dist/targets/cpp/emit-iterator.js +361 -24
  446. package/dist/targets/cpp/emit-json.d.ts +7 -1
  447. package/dist/targets/cpp/emit-json.js +594 -54
  448. package/dist/targets/cpp/emit-jsx.d.ts +0 -37
  449. package/dist/targets/cpp/emit-jsx.js +70 -8
  450. package/dist/targets/cpp/emit-narrowing.d.ts +192 -28
  451. package/dist/targets/cpp/emit-narrowing.js +1595 -120
  452. package/dist/targets/cpp/emit-native-selection.js +8 -2
  453. package/dist/targets/cpp/emit-presence.js +13 -0
  454. package/dist/targets/cpp/emit-properties.d.ts +3 -1
  455. package/dist/targets/cpp/emit-properties.js +303 -54
  456. package/dist/targets/cpp/emit-protocol-iterator.d.ts +14 -0
  457. package/dist/targets/cpp/emit-protocol-iterator.js +203 -0
  458. package/dist/targets/cpp/emit-proxy.d.ts +17 -0
  459. package/dist/targets/cpp/emit-proxy.js +35 -0
  460. package/dist/targets/cpp/emit-record-view.d.ts +12 -1
  461. package/dist/targets/cpp/emit-record-view.js +429 -18
  462. package/dist/targets/cpp/emit-return.d.ts +38 -0
  463. package/dist/targets/cpp/emit-return.js +143 -21
  464. package/dist/targets/cpp/emit-scopes.d.ts +78 -0
  465. package/dist/targets/cpp/emit-scopes.js +196 -0
  466. package/dist/targets/cpp/emit-sum-widening.js +6 -3
  467. package/dist/targets/cpp/emit-tonumber.d.ts +40 -1
  468. package/dist/targets/cpp/emit-tonumber.js +75 -4
  469. package/dist/targets/cpp/emit-tostring.d.ts +28 -2
  470. package/dist/targets/cpp/emit-tostring.js +115 -12
  471. package/dist/targets/cpp/emit-typeof.js +2 -2
  472. package/dist/targets/cpp/emit-union-properties.d.ts +9 -0
  473. package/dist/targets/cpp/emit-union-properties.js +375 -46
  474. package/dist/targets/cpp/emit.d.ts +3 -1
  475. package/dist/targets/cpp/emit.js +725 -90
  476. package/dist/targets/cpp/evaluated-once.d.ts +51 -0
  477. package/dist/targets/cpp/evaluated-once.js +140 -0
  478. package/dist/targets/cpp/host/core-globals.d.ts +0 -21
  479. package/dist/targets/cpp/host/core-globals.js +10 -2
  480. package/dist/targets/cpp/host/emit-host-invoke.d.ts +0 -10
  481. package/dist/targets/cpp/host/emit-host-invoke.js +454 -36
  482. package/dist/targets/cpp/host/emit-host-object.js +733 -88
  483. package/dist/targets/cpp/host/emit-host-properties.js +26 -2
  484. package/dist/targets/cpp/host/emit-host-reflect.d.ts +1 -0
  485. package/dist/targets/cpp/host/emit-host-reflect.js +26 -7
  486. package/dist/targets/cpp/host/emit-host-value.d.ts +13 -0
  487. package/dist/targets/cpp/host/emit-host-value.js +48 -4
  488. package/dist/targets/cpp/host/host-members.d.ts +11 -0
  489. package/dist/targets/cpp/host/host-members.js +50 -4
  490. package/dist/targets/cpp/host/native-protocols.js +3 -0
  491. package/dist/targets/cpp/host/object-protocol.d.ts +8 -0
  492. package/dist/targets/cpp/host/object-protocol.js +55 -13
  493. package/dist/targets/cpp/key-order-tracking.d.ts +11 -0
  494. package/dist/targets/cpp/key-order-tracking.js +18 -0
  495. package/dist/targets/cpp/manifest/capabilities.js +107 -8
  496. package/dist/targets/cpp/manifest.js +14 -0
  497. package/dist/targets/cpp/native-collection-base.d.ts +27 -0
  498. package/dist/targets/cpp/native-collection-base.js +202 -0
  499. package/dist/targets/cpp/native-error-base.d.ts +14 -0
  500. package/dist/targets/cpp/native-error-base.js +19 -4
  501. package/dist/targets/cpp/native-promise-base.d.ts +23 -0
  502. package/dist/targets/cpp/native-promise-base.js +30 -0
  503. package/dist/targets/cpp/native-symbol-keys.js +1 -1
  504. package/dist/targets/cpp/prototype/emit-prototype-array.js +258 -20
  505. package/dist/targets/cpp/prototype/emit-prototype-date.js +5 -4
  506. package/dist/targets/cpp/prototype/emit-prototype-invoke.d.ts +9 -1
  507. package/dist/targets/cpp/prototype/emit-prototype-invoke.js +232 -26
  508. package/dist/targets/cpp/prototype/emit-prototype-iterator.d.ts +1 -1
  509. package/dist/targets/cpp/prototype/emit-prototype-iterator.js +111 -13
  510. package/dist/targets/cpp/prototype/emit-prototype-promise.d.ts +33 -4
  511. package/dist/targets/cpp/prototype/emit-prototype-promise.js +218 -10
  512. package/dist/targets/cpp/prototype/emit-prototype-regexp.js +8 -5
  513. package/dist/targets/cpp/prototype/emit-prototype-string.js +24 -7
  514. package/dist/targets/cpp/prototype/prototype-method-reads.js +18 -3
  515. package/dist/targets/cpp/reactive-dependencies.d.ts +2 -0
  516. package/dist/targets/cpp/reactive-dependencies.js +94 -3
  517. package/dist/targets/cpp/realm-storage.d.ts +5 -0
  518. package/dist/targets/cpp/realm-storage.js +12 -0
  519. package/dist/targets/cpp/records.d.ts +151 -1
  520. package/dist/targets/cpp/records.js +1321 -122
  521. package/dist/targets/cpp/recursive-containers.d.ts +4 -1
  522. package/dist/targets/cpp/recursive-containers.js +28 -9
  523. package/dist/targets/cpp/translation-unit.d.ts +10 -0
  524. package/dist/targets/cpp/translation-unit.js +686 -140
  525. package/dist/targets/cpp/types.d.ts +56 -6
  526. package/dist/targets/cpp/types.js +218 -12
  527. package/dist/targets/cpp/virtual-methods.d.ts +3 -3
  528. package/dist/targets/cpp/virtual-methods.js +174 -17
  529. package/package.json +6 -5
  530. package/src/targets/cpp/runtime/gea_dynamic_proxy.h +155 -25
  531. package/src/targets/cpp/runtime/gea_eval.h +3 -0
  532. package/src/targets/cpp/runtime/gea_pcm.h +116 -0
  533. package/src/targets/cpp/runtime/gea_runtime.h +18007 -4757
  534. package/src/targets/cpp/runtime/gea_runtime_builtins.cpp +7 -45
  535. package/src/targets/cpp/runtime/gea_runtime_rtc.h +247 -0
@@ -1,34 +1,46 @@
1
+ import { publishRealmStorage } from './realm-storage.js';
1
2
  import { nativeSelectionHelpers } from './native-selection-helpers.js';
3
+ import { asyncPromiseViewOf, isAsyncCoroutineBody, taskTwinEligible } from './coroutine-bodies.js';
4
+ import { createCppEmitBlockedError } from './emit-context.js';
5
+ import { instanceReparentTargetsOf } from '../../ir/instance-reparenting.js';
2
6
  import { cppErrorNativeType } from './error-types.js';
3
7
  import { isNativeErrorBaseRefusal, nativeErrorBaseInitializeStatements } from './native-error-base.js';
8
+ import { nativeCollectionBaseInitializeStatements } from './native-collection-base.js';
9
+ import { nativePromiseBaseInitializeStatements } from './native-promise-base.js';
4
10
  import { classFieldStorageOwnerOf, classMemberOf, classMethodOverrideOf } from '../../projection/fields.js';
5
- import { balanceCppUnits } from './balanced-units.js';
11
+ import { balanceCppUnits, chunkCppItems, cppChunkFileName, cppUnitByteBudget } from './balanced-units.js';
12
+ import { readonlyBorrowFormalsOf } from '../../ir/borrowed-call-arguments.js';
6
13
  import { stableBorrowEntryOf } from './borrowed-call-entry.js';
7
14
  import { programFactsOf } from '../../ir/program-facts.js';
15
+ import { integrityRestrictionsOf } from '../../ir/integrity-restrictions.js';
16
+ import { keyOrderObservationOf, nothingProvenUnobserved } from '../../ir/key-order-observation.js';
8
17
  import { nativeOrdinaryConstructInstanceMatches } from '../../ir/construct-entry.js';
9
18
  import { fileIdentityOf, isRegionId } from '../../identity/ids.js';
10
19
  import { constructedBaseOf, runtimeClassLayoutsOf } from '../../projection/classes.js';
11
20
  import { allOperationsOf } from '../../ir/model.js';
12
- import { representationKey } from '../../representation/model.js';
21
+ import { capturesNothing } from '../../ir/captures.js';
22
+ import { representationKey, walkRepresentation } from '../../representation/model.js';
13
23
  import { hostCallName } from './host/host-members.js';
14
24
  import { reactiveBoundRecordFields, reactiveDependenciesOfBodies } from './reactive-dependencies.js';
15
25
  import { buildDirectCallableIndex, buildCaptureIndex } from './captures.js';
16
26
  import { createCppDocumentBuilder, emptyCppFacts, render, spliceRendered } from './document.js';
17
- import { beginUnionAliasing, endUnionAliasing } from './types.js';
27
+ import { beginUnionAliasing, endUnionAliasing, cppNativeHandleTag } from './types.js';
18
28
  import { cppConstructedThunkName, cppConstructThunkName, cppFormalName, cppReceiverName, cppThunkName, emitBody, isCppEmitBlockedError } from './emit.js';
19
- import { cppCaptureFieldName, cppCaptureReceiverFieldName, cppEnvironmentLocalName, cppEnvironmentParamName, cppEnvironmentSlotName, cppEnvironmentStructName, effectiveAbiOf, symbolKeyDefinitions, templateObjectDefinitions } from './emit-context.js';
20
- import { censusClassStaticFieldStorage, censusConstantFieldInitializers, censusLazyArrowFields, classBoxable, cppFieldInitializerStatements, publishBoxableClasses, publishClassStaticFieldStorage, publishConstantFieldInitializers, publishLazyArrowFieldPlans } from './class-layout.js';
29
+ import { cppCaptureFieldName, cppCaptureFrameFieldName, cppCaptureReceiverFieldName, cppEnvironmentLocalName, cppEnvironmentParamName, cppEnvironmentSlotName, cppEnvironmentStructName, cppFrameMemberName, cppFrameStructName, cppEnvironmentStructOf, cppSharedAnchorFieldName, cppSharedIdentityFieldName, effectiveAbiOf, symbolKeyDefinitions, templateObjectDefinitions } from './emit-context.js';
30
+ import { censusClassStaticFieldStorage, censusConstantFieldInitializers, censusLazyArrowFields, classBoxable, cppFieldInitializerStatements, publishBoxableClasses, publishClassStaticFieldStorage, publishConstructorViewShapes, publishConstantFieldInitializers, publishLazyArrowFieldPlans } from './class-layout.js';
21
31
  import { classStaticFieldStorageRows, cppRecordDeclarations, cppStructNameOf, declaredFieldRepresentationOf, declaredRecordFieldOf, recordAccessorBodiesOf, representationNamesMintedStruct, withUnreadParametersUnnamed } from './records.js';
22
32
  import { prototypeReadHooks, virtualMethodEmission, virtualMethodFamiliesOf } from './virtual-methods.js';
23
33
  import { virtualDispatchVerdictOf } from '../../projection/dispatch.js';
24
34
  import { stringConstantsOf } from '../../ir/dead-values.js';
25
35
  import { integerParameterSlot, integerResultSlot, integerStorageCensusOf, integerStorageSlot } from '../../ir/integer-storage.js';
36
+ import { narrowableIntegersOf } from '../../ir/integers.js';
26
37
  import { classesConstructedUnobservably, functionsIgnoringTheirReceiver } from '../../ir/instantiation.js';
27
38
  import { renderJsonStructDeclarations } from './emit-json.js';
28
39
  import { alignedValueText } from './emit-narrowing.js';
29
40
  import { recordLayoutPolicyOf } from '../../projection/fields.js';
30
- import { cppAbiParameterType, cppAbiType, cppStringLiteral, cppBodyName, cppCallableDeclarationTagName, cppCommonJsModuleName, cppCommonJsRecordName, cppNarrowedIntegerType, cppRefcountedReceiver, cppBoxedType, cppClassName, cppConstructName, cppGlobalName, cppInitializeName, cppRecordFieldName, cppRecordStructName, cppResultTypeOf, cppTypeOf, sanitizeForCppIdentifier } from './types.js';
41
+ import { cppAbiParameterType, cppAbiType, cppStringLiteral, cppBodyName, cppCallableDeclarationTagName, cppCommonJsModuleName, cppCommonJsRecordName, cppNarrowedIntegerType, cppRefcountedReceiver, cppBoxedType, cppClassName, cppConstructName, cppGlobalName, cppInitializeName, cppRecordFieldName, cppRecordStructName, cppResultTypeOf, cppTypeOf, publishNarrowedStorageSlots, sanitizeForCppIdentifier } from './types.js';
31
42
  import { buildHostMethodAliasIndex } from './host/host-method-aliases.js';
43
+ import { constructionOnlyFieldsOf, reflectiveFieldWritesOf } from '../../ir/construction-only-fields.js';
32
44
  import { cppRecursiveContainerDeclarations, cppRecursiveContainerTraceEdges } from './recursive-containers.js';
33
45
  /**
34
46
  * One C++ translation unit, assembled from what earlier stages sealed.
@@ -167,10 +179,12 @@ const hostPreamblesOf = (representations, placements, hosts, bodies) => {
167
179
  }
168
180
  return [...lines];
169
181
  };
170
- const storageSpelling = (type, name) => ({
171
- declaration: `extern ${type} ${name};`,
172
- definition: `${type} ${name};`
173
- });
182
+ const storageSpelling = (type, name, realm = false) => realm
183
+ ? {
184
+ declaration: `${type}& ${name}();`,
185
+ definition: `${type}& ${name}() { struct RealmTag {}; return gea::detail::realmSlot<RealmTag, ${type}>(); }`
186
+ }
187
+ : { declaration: `extern ${type} ${name};`, definition: `${type} ${name};` };
174
188
  /**
175
189
  * File-scope variables for the cells a run-once region owns.
176
190
  *
@@ -178,23 +192,23 @@ const storageSpelling = (type, name) => ({
178
192
  * guessed type -- the body that reads it then refuses by name, which is the
179
193
  * answer, instead of this file inventing a layout to make the file compile.
180
194
  */
181
- const globalStorage = (placements, omit) => [...placements.entries()]
195
+ const globalStorage = (placements, omit, realm = false) => [...placements.entries()]
182
196
  .filter(([declaration, placement]) => placement.storage.kind === 'region' && placement.representation !== null && !omit.has(declaration))
183
197
  .sort(([left], [right]) => left.localeCompare(right))
184
198
  .flatMap(([declaration, placement]) => {
185
199
  const representation = placement.representation;
186
200
  if (!representation || representation.kind === 'unresolved' || representation.kind === 'void')
187
201
  return [];
188
- return [storageSpelling(cppTypeOf(representation), cppGlobalName(declaration))];
202
+ return [storageSpelling(cppTypeOf(representation), cppGlobalName(declaration), realm)];
189
203
  });
190
- const absentDefinitions = (placements) => [...placements.entries()]
204
+ const absentDefinitions = (placements, realm = false) => [...placements.entries()]
191
205
  .filter(([, placement]) => placement.storage.kind === 'absent' && placement.representation !== null)
192
206
  .sort(([left], [right]) => left.localeCompare(right))
193
207
  .flatMap(([declaration, placement]) => {
194
208
  const representation = placement.representation;
195
209
  if (!representation || representation.kind === 'unresolved' || representation.kind === 'void')
196
210
  return [];
197
- const spelling = storageSpelling(cppTypeOf(representation), cppGlobalName(declaration));
211
+ const spelling = storageSpelling(cppTypeOf(representation), cppGlobalName(declaration), realm);
198
212
  return [{ text: spelling.definition, declaration: spelling.declaration, representation }];
199
213
  });
200
214
  const externDeclarations = (placements) => [...placements.entries()]
@@ -246,8 +260,10 @@ const formalsOf = (abi, narrowed = new Set(), borrowReceiver = false, borrowed =
246
260
  * formal correctly either way; only the environment pointer itself is this
247
261
  * function's own addition.
248
262
  */
249
- const bodyFormalsOf = (owner, effectiveAbi, admission, narrowed, borrowReceiver, borrowed = new Set()) => [
250
- ...(admission.kind === 'ok' ? [`${cppEnvironmentStructName(owner)}* ${cppEnvironmentLocalName}`] : []),
263
+ const bodyFormalsOf = (environmentStruct, effectiveAbi, admission, narrowed, borrowReceiver, borrowed = new Set(), coroutine = false) => [
264
+ ...(admission.kind === 'ok'
265
+ ? [coroutine ? `${environmentStruct} ${cppCoroutineEnvironmentName}` : `${environmentStruct}* ${cppEnvironmentLocalName}`]
266
+ : []),
251
267
  ...formalsOf(effectiveAbi, narrowed, borrowReceiver, borrowed)
252
268
  ];
253
269
  /**
@@ -262,7 +278,62 @@ const bodyFormalsOf = (owner, effectiveAbi, admission, narrowed, borrowReceiver,
262
278
  * `function*` publishes -- the carrier cannot tell them apart, only the
263
279
  * `function*` itself can.
264
280
  */
265
- const isCoroutineBody = (body) => body.generator === true || [...body.blocks.values()].some((block) => block.operations.some((operation) => operation.kind === 'yield'));
281
+ const isCoroutineBody = (body) => body.generator === true ||
282
+ isAsyncCoroutineBody(body) ||
283
+ // The declared entry of an async body emitted through its promise view only
284
+ // forwards to the coroutine, but it forwards its formals BY VALUE into that
285
+ // frame, so it takes them the way a coroutine does: no borrowed reference
286
+ // may reach a frame that outlives the call.
287
+ asyncPromiseViewOf(body) !== null ||
288
+ [...body.blocks.values()].some((block) => block.operations.some((operation) => operation.kind === 'yield'));
289
+ /** The private name an async body is emitted under when its declared entry forwards to its promise view. */
290
+ const asyncPromiseViewName = (owner) => `${cppBodyName(owner)}_async`;
291
+ /**
292
+ * The declared entry of an async body emitted through its promise view
293
+ * (`coroutine-bodies.ts`'s `asyncPromiseViewOf`): the body's own signature,
294
+ * forwarding every formal into the coroutine and viewing the promise it
295
+ * answers as the declared result -- the one boundary where the two carriers
296
+ * meet, converted by the same census every other store asks.
297
+ */
298
+ const asyncPromiseViewEntryOf = (body, view, captures, site, narrowed) => {
299
+ const abi = body.abi;
300
+ const promise = view.abi?.result;
301
+ if (!abi || !promise)
302
+ return [];
303
+ const admission = captures.of(body.sourceOwner);
304
+ const effectiveAbi = effectiveAbiOf(abi, admission) ?? abi;
305
+ const actuals = [
306
+ ...(admission.kind === 'ok' ? [`std::move(${cppCoroutineEnvironmentName})`] : []),
307
+ ...(effectiveAbi.receiver !== null ? [cppReceiverName] : []),
308
+ ...abi.parameters.map((_, ordinal) => `std::move(${cppFormalName(ordinal)})`)
309
+ ];
310
+ const call = `${asyncPromiseViewName(body.sourceOwner)}(${actuals.join(', ')})`;
311
+ const viewed = alignedValueText(site, 'translation-unit.ts:asyncPromiseViewEntryOf', promise, abi.result, call);
312
+ if (viewed === null) {
313
+ throw createCppEmitBlockedError(`conversion:${representationKey(promise)}->${representationKey(abi.result)}`, `an async body answers ${representationKey(promise)}, and its declared result ${representationKey(abi.result)} has no ` +
314
+ 'conversion from it');
315
+ }
316
+ return [`${signatureOf(body, captures, narrowed, false, new Set())} {`, `return ${viewed};`, '}'];
317
+ };
318
+ /**
319
+ * The name a coroutine body's environment COPY is bound to.
320
+ *
321
+ * A generator's frame outlives the call that created it: the thunk returns
322
+ * the suspended cursor at once, and every later `next()` resumes into a body
323
+ * that still reads its captures. A pointer to the environment is only valid
324
+ * while the carrier that owns it is held -- and not even that long for an
325
+ * inline environment, which the thunk unpacks into its own stack slot -- so
326
+ * the generator split's outer half, which allocates the inner coroutine's
327
+ * carrier and drops it on return (mongodb's `makeCounter`), left every resume
328
+ * writing through freed memory. C++ copies a coroutine's by-value parameters
329
+ * into the coroutine frame, so taking the environment by value gives the
330
+ * frame its own reference to every captured cell for as long as it lives.
331
+ * Captures that are written are cells, so the copy shares every mutation.
332
+ */
333
+ const cppCoroutineEnvironmentName = 'gea_e_frame';
334
+ const coroutineEnvironmentPrologueOf = (body, captures) => body.abi && captures.of(body.sourceOwner).kind === 'ok' && isCoroutineBody(body)
335
+ ? [`auto* ${cppEnvironmentLocalName} = &${cppCoroutineEnvironmentName};`]
336
+ : [];
266
337
  /**
267
338
  * Whether this body may take its receiver by reference.
268
339
  *
@@ -289,6 +360,36 @@ const isCoroutineBody = (body) => body.generator === true || [...body.blocks.val
289
360
  * behaviour, which is exactly why no gate above this one could have caught it.
290
361
  */
291
362
  const borrowsReceiver = (body) => body.abi?.receiver != null && cppRefcountedReceiver(body.abi.receiver) && !isCoroutineBody(body);
363
+ /**
364
+ * The struct one body's captured declarations share (`CaptureFrame`).
365
+ *
366
+ * Every field is declared at its carrier, with no box around it: the frame IS
367
+ * the shared cell, so a closure reaches a value through one handle instead of
368
+ * one per variable. The trace friend is the environment struct's, for the same
369
+ * reason -- a frame holds closures whose environments hold the frame, and the
370
+ * cycle collector has to find that edge.
371
+ */
372
+ const frameDeclarationOf = (frame, identities, identityKept = []) => {
373
+ const name = cppFrameStructName(String(frame.owner));
374
+ // A slot is reserved by position, but only declared for a closure whose convention the program ever asks the identity of.
375
+ const headers = identities.flatMap((_, index) => (identityKept[index] === false ? [] : [cppSharedIdentityFieldName(index)]));
376
+ const fields = frame.members.map((_, index) => cppFrameMemberName(index));
377
+ const traceable = fields.map((field) => `gea::detail::TraceEdges<decltype(${field})>::supported`);
378
+ return [
379
+ `struct ${name} {`,
380
+ ...frame.members.map((member, index) => ` ${cppTypeOf(member.representation)} ${cppFrameMemberName(index)};`),
381
+ // One anchor per closure whose environment is nothing but this frame's
382
+ // handle (`CaptureIndex.frameIdentitiesOf`), so identifying it mints no cell.
383
+ ...headers.map((field) => ` gea::EnvironmentIdentityHeader ${field};`),
384
+ ` [[maybe_unused]] friend auto geaTraceRefs(const ${name}& value, gea::detail::RefVisitor& visitor)`,
385
+ ` -> std::bool_constant<${traceable.length ? traceable.join(' || ') : 'false'}> {`,
386
+ ...fields.map((field) => ` gea::detail::traceRefs(value.${field}, visitor);`),
387
+ ...headers.map((field) => ` gea::detail::traceRefs(value.${field}.identity, visitor);`),
388
+ ' return {};',
389
+ ' }',
390
+ '};'
391
+ ].join('\n');
392
+ };
292
393
  /**
293
394
  * The environment struct one capturing function's allocation populates and
294
395
  * its thunk unpacks, or `null` for a function that captures nothing.
@@ -299,16 +400,65 @@ const borrowsReceiver = (body) => body.abi?.receiver != null && cppRefcountedRec
299
400
  * of every body signature (`renderTranslationUnit`), because a body's own
300
401
  * formal names this struct as a pointer type before any body is defined.
301
402
  */
302
- const environmentDeclarationOf = (owner, admission) => {
403
+ const environmentDeclarationOf = (owner, admission, group = null, memberIdentityObserved = []) => {
303
404
  if (admission.kind !== 'ok')
304
405
  return null;
406
+ // A recursion group's shared environment also records its own block and one
407
+ // identity slot per member (`gea::shareEnvironment`), after the captures so
408
+ // the allocation's brace initializer names only the captures. A member whose
409
+ // convention the program never asks the identity of (`ir/callable-identity-
410
+ // demand.ts`, the same census `emit-callable.ts`'s ordinary allocation and
411
+ // `emit-binding-reference.ts`'s `sharedGroupMemberText` already gate
412
+ // `identifyCallable` on) never mints into its header and never reads one
413
+ // back (`CallableObject::functionObjectIdentity` only anchors on a non-null
414
+ // `identityHeader`) -- so its slot is reserved for nothing, on every group
415
+ // allocation this frame ever makes. Dropping it shrinks the block those
416
+ // allocations share; `sharedGroupMemberText` matches this same predicate
417
+ // when building `&Struct::gea_identity_<n>` so a field it still spells is
418
+ // always one this struct still declares.
419
+ //
420
+ // At least one header always survives, even when every member is unobserved
421
+ // (a lone self-recursive declaration with no other captures, e.g.
422
+ // `countdown`'s `step`): `EnvironmentIdentityHeader` owns a `Ref`, so ANY
423
+ // struct that keeps one is never trivially copyable, which is what keeps
424
+ // `gea_runtime.h`'s `environmentFitsInline`/`SoleRefField` -- a check driven
425
+ // purely by the C++ TYPE, not by how a value was actually packed -- from
426
+ // ever answering true for a shared environment. `shareEnvironment` packs
427
+ // every group unconditionally through the heap/pointer representation, so
428
+ // if the struct ever shrank to just `gea_anchor` (one pointer, trivially
429
+ // copyable) the thunk's generic `unpackTransientEnvironment` would take the
430
+ // INLINE branch for it -- memcpy'ing the heap address's own bytes into the
431
+ // reconstructed struct's sole field instead of dereferencing it -- and every
432
+ // later `gea::sharedEnvironmentMember(Environment*, ...)` rebuild in that
433
+ // body would reinterpret garbage as the block pointer. Segfaulted exactly
434
+ // this way on `countdown` the first time every member's header was elided.
435
+ const identityKept = group === null ? [] : group.members.map((_, index) => memberIdentityObserved[index] ?? true);
436
+ if (identityKept.length > 0 && !identityKept.some(Boolean))
437
+ identityKept[0] = true;
438
+ const shared = group === null
439
+ ? []
440
+ : [cppSharedAnchorFieldName, ...group.members.flatMap((_, index) => (identityKept[index] ? [cppSharedIdentityFieldName(index)] : []))];
441
+ // A framed slot has no field here: the environment holds one handle to the
442
+ // frame that owns it, after the slots that do have one.
443
+ const unframed = admission.layout.slots.flatMap((slot, index) => (slot.frame === undefined ? [{ slot, index }] : []));
444
+ const frameFields = admission.layout.frames.map((frame, index) => ({
445
+ type: `gea::Ref<${cppFrameStructName(String(frame.owner))}>`,
446
+ name: cppCaptureFrameFieldName(index)
447
+ }));
305
448
  const fields = [
306
- ...admission.layout.slots.map((slot, index) => ` ${slot.boxed ? cppBoxedType(slot.representation) : cppTypeOf(slot.representation)} ${cppCaptureFieldName(index)};`),
307
- ...(admission.layout.receiver !== null ? [` ${cppTypeOf(admission.layout.receiver)} ${cppCaptureReceiverFieldName};`] : [])
449
+ ...unframed.map(({ slot, index }) => ` ${slot.boxed ? cppBoxedType(slot.representation) : cppTypeOf(slot.representation)} ${cppCaptureFieldName(index)};`),
450
+ ...frameFields.map((field) => ` ${field.type} ${field.name};`),
451
+ ...(admission.layout.receiver !== null ? [` ${cppTypeOf(admission.layout.receiver)} ${cppCaptureReceiverFieldName};`] : []),
452
+ ...shared.map((field) => field === cppSharedAnchorFieldName ? ` gea::SharedEnvironmentAnchor ${field};` : ` gea::EnvironmentIdentityHeader ${field};`)
308
453
  ];
309
454
  const traceFields = [
310
- ...admission.layout.slots.map((_, index) => cppCaptureFieldName(index)),
311
- ...(admission.layout.receiver !== null ? [cppCaptureReceiverFieldName] : [])
455
+ ...unframed.map(({ index }) => cppCaptureFieldName(index)),
456
+ ...frameFields.map((field) => field.name),
457
+ ...(admission.layout.receiver !== null ? [cppCaptureReceiverFieldName] : []),
458
+ // A member's minted identity carries the function object's own property
459
+ // table, which can hold anything -- the same edge a lone closure's block
460
+ // traces through `HeapEnvironmentBlock`'s header.
461
+ ...shared.filter((field) => field !== cppSharedAnchorFieldName).map((field) => `${field}.identity`)
312
462
  ];
313
463
  const traceableFields = traceFields.map((field) => `gea::detail::TraceEdges<decltype(${field})>::supported`);
314
464
  return [
@@ -389,8 +539,27 @@ const initializationStatements = (site, deriver, classes, layout, abi, actuals,
389
539
  // reading of 20.5.1.1. The field initializers follow it for the same
390
540
  // reason they follow a written `super()`: the language runs them once the
391
541
  // base chain has returned.
392
- if (layout.nativeBase.instance.native !== cppErrorNativeType) {
393
- return (`it extends native base ${layout.nativeBase.protocol}, which uses "${layout.nativeBase.instance.native ?? 'no native layout'}"; ` +
542
+ const nativeInstance = layout.nativeBase.instance;
543
+ if (nativeInstance.kind === 'keyed-collection') {
544
+ const baseStatements = nativeCollectionBaseInitializeStatements(site, classes, layout.declaration, (callable) => bodyAbis.get(String(callable)) ?? null, cppReceiverName, nativeInstance, abi.parameters.map((parameter, index) => {
545
+ const actual = actuals[index];
546
+ return actual === undefined ? undefined : { representation: parameter.value, text: actual };
547
+ }));
548
+ if (typeof baseStatements === 'string')
549
+ return baseStatements;
550
+ return [...baseStatements, ...fieldInitializers];
551
+ }
552
+ if (nativeInstance.kind === 'promise') {
553
+ const baseStatements = nativePromiseBaseInitializeStatements(cppReceiverName, nativeInstance, abi.parameters.map((parameter, index) => {
554
+ const actual = actuals[index];
555
+ return actual === undefined ? undefined : { representation: parameter.value, text: actual };
556
+ }));
557
+ if (typeof baseStatements === 'string')
558
+ return baseStatements;
559
+ return [...baseStatements, ...fieldInitializers];
560
+ }
561
+ if (nativeInstance.native !== cppErrorNativeType) {
562
+ return (`it extends native base ${layout.nativeBase.protocol}, which uses "${nativeInstance.native ?? 'no native layout'}"; ` +
394
563
  'only the intrinsic Error layout has an existing-receiver initializer');
395
564
  }
396
565
  const baseStatements = nativeErrorBaseInitializeStatements(deriver, cppReceiverName, abi.parameters.slice(0, 2).map((parameter, index) => {
@@ -559,7 +728,7 @@ const signatureOf = (body, captures, narrowed = new Set(), narrowedResult = fals
559
728
  const admission = captures.of(body.sourceOwner);
560
729
  const effectiveAbi = effectiveAbiOf(body.abi, admission) ?? body.abi;
561
730
  const result = narrowedResult ? cppNarrowedIntegerType : cppResultTypeOf(effectiveAbi.result);
562
- const formals = bodyFormalsOf(body.sourceOwner, effectiveAbi, admission, narrowed, borrowsReceiver(body), borrowed);
731
+ const formals = bodyFormalsOf(cppEnvironmentStructOf(captures, body.sourceOwner), effectiveAbi, admission, narrowed, borrowsReceiver(body), borrowed, isCoroutineBody(body));
563
732
  return `${result} ${name}(${formals.join(', ')})`;
564
733
  };
565
734
  const thunkOf = (body, captures, narrowed, narrowedResult, linkage) => {
@@ -574,9 +743,19 @@ const thunkOf = (body, captures, narrowed, narrowedResult, linkage) => {
574
743
  // ignores where the state is on the heap. Declared here rather than inside
575
744
  // the helper because a heap environment's members must not be constructed
576
745
  // once per call just to be overwritten by a pointer cast.
746
+ //
747
+ // A record accessor's environment was packed with `gea::packEnvironment`
748
+ // (`emit-allocation.ts`) and is also read back in place with
749
+ // `gea::storedEnvironment`, which has no slot to reconstruct a transiently-
750
+ // packed environment into -- so its thunk keeps unpacking with
751
+ // `gea::unpackEnvironment` too, matching the pack call it actually got.
752
+ // Every other capturing body was packed with `gea::packTransientEnvironment`
753
+ // (`emit-callable.ts`) and is entered only through a thunk, so its unpack
754
+ // takes the matching `gea::unpackTransientEnvironment`.
755
+ const unpackEntry = captures.isAccessorEnvironment(body.sourceOwner) ? 'gea::unpackEnvironment' : 'gea::unpackTransientEnvironment';
577
756
  const unpack = hasEnvironment
578
757
  ? `alignas(void*) unsigned char ${cppEnvironmentSlotName}[sizeof(void*)]; ` +
579
- `auto* ${cppEnvironmentLocalName} = gea::unpackEnvironment<${cppEnvironmentStructName(body.sourceOwner)}>(${cppEnvironmentParamName}, ${cppEnvironmentSlotName}); `
758
+ `auto* ${cppEnvironmentLocalName} = ${unpackEntry}<${cppEnvironmentStructOf(captures, body.sourceOwner)}>(${cppEnvironmentParamName}, ${cppEnvironmentSlotName}); `
580
759
  : '';
581
760
  const receiverActual = abi.receiver !== null
582
761
  ? [cppReceiverName]
@@ -584,7 +763,7 @@ const thunkOf = (body, captures, narrowed, narrowedResult, linkage) => {
584
763
  ? [`${cppEnvironmentLocalName}->${cppCaptureReceiverFieldName}`]
585
764
  : [];
586
765
  const call = `${cppBodyName(body.sourceOwner)}(${[
587
- ...(hasEnvironment ? [cppEnvironmentLocalName] : []),
766
+ ...(hasEnvironment ? [isCoroutineBody(body) ? `*${cppEnvironmentLocalName}` : cppEnvironmentLocalName] : []),
588
767
  ...receiverActual,
589
768
  // The thunk's own formals stay the ABI's, so the carrier's function-pointer
590
769
  // type is unchanged; a narrowed body formal is converted here, at the one
@@ -743,7 +922,8 @@ const entryDefinitionOf = (entrySymbol, moduleOrder, bodies, commonJsModules, ha
743
922
  calls.push('gea::detail::drainPromiseJobs();');
744
923
  return { text: [`void ${entrySymbol}() {`, ...calls, '}'].join('\n') };
745
924
  };
746
- const commonJsDefinitionsOf = (bodies) => {
925
+ const commonJsDefinitionsOf = (bodies, realm = false) => {
926
+ const local = (type, name) => realm ? `struct RealmTag {}; auto& ${name} = gea::detail::realmSlot<RealmTag, ${type}>();` : `static ${type} ${name};`;
747
927
  const targets = new Set();
748
928
  const builtinTargets = new Map();
749
929
  const nativeRecords = new Map();
@@ -766,8 +946,9 @@ const commonJsDefinitionsOf = (bodies) => {
766
946
  for (const operation of allOperationsOf(block)) {
767
947
  if (operation.kind === 'commonjs-require') {
768
948
  targets.add(operation.owner);
769
- targets.add(operation.target);
770
- if (operation.builtinModule !== null) {
949
+ if (operation.target !== null)
950
+ targets.add(operation.target);
951
+ if (operation.builtinModule !== null && operation.target !== null) {
771
952
  addBuiltinTarget(operation.owner, operation.builtinModule, operation.target);
772
953
  }
773
954
  }
@@ -829,6 +1010,14 @@ const commonJsDefinitionsOf = (bodies) => {
829
1010
  for (const operation of allOperationsOf(block)) {
830
1011
  if (operation.kind !== 'commonjs-require' || operation.result.representation.kind === 'dynamic')
831
1012
  continue;
1013
+ if (operation.target === null) {
1014
+ refused.push({
1015
+ owner: operation.owner,
1016
+ reason: `a require of the absent package "${operation.absentPackage}" selected a native carrier; it evaluates no module and has no exports`,
1017
+ key: 'print:refused'
1018
+ });
1019
+ continue;
1020
+ }
832
1021
  const native = nativeRecords.get(operation.target);
833
1022
  if (!native) {
834
1023
  refused.push({
@@ -877,7 +1066,7 @@ const commonJsDefinitionsOf = (bodies) => {
877
1066
  }
878
1067
  const native = nativeRecords.get(target);
879
1068
  if (!native) {
880
- definitions.push(`inline gea::commonjs::ModuleRecord& ${cppCommonJsRecordName(target)}() { static gea::commonjs::ModuleRecord record; return record; }\n` +
1069
+ definitions.push(`inline gea::commonjs::ModuleRecord& ${cppCommonJsRecordName(target)}() { ${local('gea::commonjs::ModuleRecord', 'record')} return record; }\n` +
881
1070
  `inline gea::Value ${cppCommonJsModuleName(target)}() { return gea::commonjs::evaluate(${cppCommonJsRecordName(target)}(), [] { ${cppBodyName(target)}(); }); }`);
882
1071
  continue;
883
1072
  }
@@ -901,7 +1090,7 @@ const commonJsDefinitionsOf = (bodies) => {
901
1090
  ' Phase phase = Phase::fresh;',
902
1091
  ` ${recordType} module = ${recordInit};`,
903
1092
  '};',
904
- `inline ${stateName}& ${stateAccessor}() { static ${stateName} state; return state; }`,
1093
+ `inline ${stateName}& ${stateAccessor}() { ${local(stateName, 'state')} return state; }`,
905
1094
  `inline ${recordType} ${cppCommonJsRecordName(target)}() { return ${stateAccessor}().module; }`,
906
1095
  `inline ${exportType} ${cppCommonJsModuleName(target)}() {`,
907
1096
  ` auto& state = ${stateAccessor}();`,
@@ -917,7 +1106,9 @@ const commonJsDefinitionsOf = (bodies) => {
917
1106
  .sort(([left], [right]) => left.localeCompare(right))
918
1107
  .map(([name, target]) => `gea::commonjs::registerBuiltinModule(${cppStringLiteral(name)}, &${cppCommonJsModuleName(target)});`);
919
1108
  definitions.push(`inline void gea_register_commonjs_builtin_modules() {\n` +
920
- ` static const bool registered = [] { ${registrations.join(' ')} return true; }();\n` +
1109
+ (realm
1110
+ ? ` struct RegistryTag {}; auto& registered = gea::detail::realmSlot<RegistryTag, bool>(); if (!registered) { ${registrations.join(' ')} registered = true; }\n`
1111
+ : ` static const bool registered = [] { ${registrations.join(' ')} return true; }();\n`) +
921
1112
  ` (void)registered;\n` +
922
1113
  `}`);
923
1114
  }
@@ -1013,8 +1204,38 @@ const moduleUnitNames = (base, files) => {
1013
1204
  return names;
1014
1205
  };
1015
1206
  const cppIdentifierCharacters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_';
1207
+ /**
1208
+ * A unit's alias/function session (`beginUnionAliasing`..`endUnionAliasing`)
1209
+ * is module state. A render that refuses part-way never reaches its end, and
1210
+ * the session -- active, with the dead unit's recorded spellings -- would then
1211
+ * shape every later compilation in the process (a native-selection conversion
1212
+ * rendered as a unit function instead of inline, a union spelled as an alias
1213
+ * nobody declares). The session therefore ends on every exit.
1214
+ */
1016
1215
  export const renderTranslationUnit = (input) => {
1216
+ endUnionAliasing();
1217
+ try {
1218
+ return renderTranslationUnitSession(input);
1219
+ }
1220
+ catch (error) {
1221
+ endUnionAliasing();
1222
+ throw error;
1223
+ }
1224
+ };
1225
+ const renderTranslationUnitSession = (input) => {
1226
+ publishRealmStorage(input.placements, input.realmStorage === true);
1017
1227
  const emissionRepresentations = input.emissionRepresentations ?? [...input.plan.selected.values()];
1228
+ // A retained event record can mention an opaque host identity without ever
1229
+ // invoking it (e.g. MessageEvent.source). NativeHandle needs that protocol's
1230
+ // tag declared, even when no runtime member or constructor is used.
1231
+ const nativeHandleTags = new Set();
1232
+ for (const representation of emissionRepresentations) {
1233
+ for (const nested of walkRepresentation(representation)) {
1234
+ if (nested.kind === 'native-handle' && nested.native === null)
1235
+ nativeHandleTags.add(cppNativeHandleTag(nested.protocol, nested.version));
1236
+ }
1237
+ }
1238
+ const nativeHandleDeclarations = [...nativeHandleTags].sort().map((tag) => `struct ${tag};`);
1018
1239
  const printerDrift = [];
1019
1240
  const refuse = (refused) => ({
1020
1241
  source: null,
@@ -1040,7 +1261,7 @@ export const renderTranslationUnit = (input) => {
1040
1261
  // would put the very thing isolation exists to hide back in the global
1041
1262
  // namespace.
1042
1263
  const externs = externDeclarations(input.placements);
1043
- const absent = absentDefinitions(input.placements);
1264
+ const absent = absentDefinitions(input.placements, input.realmStorage);
1044
1265
  // Spelled in full, above: an extern or an absent global is declared at
1045
1266
  // global scope, before the program's namespace and before the alias block
1046
1267
  // inside it, so neither may name an alias. Everything rendered from here on
@@ -1108,11 +1329,55 @@ export const renderTranslationUnit = (input) => {
1108
1329
  // `recordAccessorBodiesOf`.
1109
1330
  const captures = buildCaptureIndex(input.bodies, input.placements, recordAccessorBodiesOf(emissionRepresentations, input.deriver));
1110
1331
  const directCallables = buildDirectCallableIndex(input.bodies, captures, input.placements);
1111
- const { callableMemberCandidates, repeatedConstructors, dyingArguments, formalsBorrowedIn, bodyCallsUnsafeKnownCallee, callableIdentityDemand, nativeIntegrityRestricted, fixedFieldStateConstant, singleEvaluationClasses } = programFactsOf(input.bodies, directCallables, input.placements, {
1332
+ // A class constructor body is entered only from its construct function (and a
1333
+ // derived class's `super(...)`), both of which hand it OWNED arguments --
1334
+ // a stable-borrow entry is never selected for it. Giving it one anyway turned
1335
+ // the body into an owning wrapper over the borrowing body: every stored handle
1336
+ // argument was copied into its field and the wrapper's parameter then died,
1337
+ // a count dip per stored handle that bought the cycle collector a candidate
1338
+ // (the mongodb driver's request and command objects: ~35 spilled dips per
1339
+ // operation). The owning body moves a parameter into its field at the last use.
1340
+ const constructorBodies = new Set();
1341
+ for (const layout of input.classes.values())
1342
+ if (layout.constructor !== null)
1343
+ constructorBodies.add(String(layout.constructor));
1344
+ // A constructor body whose `this` can be emitted with a store held back behind later
1345
+ // reads (`planStoreSink`): every class in its chain -- and every class deriving from it,
1346
+ // whose accessors run for the same stores -- is a plain native layout. Accessors, a host
1347
+ // base, or a base the program does not lay out all fail closed.
1348
+ const integrity = integrityRestrictionsOf(input.bodies);
1349
+ // `GEA_KEY_ORDER_TRACKING=1` keeps every record's creation-order bookkeeping, for measuring what the proof removes.
1350
+ const keyOrderUnobserved = (process.env['GEA_KEY_ORDER_TRACKING'] === '1' ? nothingProvenUnobserved : keyOrderObservationOf(input.bodies, input.reflection)).unobserved;
1351
+ const unsafeForStoreSink = new Set();
1352
+ for (const [declaration, layout] of input.classes) {
1353
+ const chain = [];
1354
+ let ancestor = declaration;
1355
+ let sealed = true;
1356
+ while (ancestor !== null && sealed) {
1357
+ const link = input.classes.get(ancestor);
1358
+ if (link === undefined || link.nativeBase !== null || chain.includes(ancestor))
1359
+ sealed = false;
1360
+ else if (link.accessors.length > 0 || link.instance === null || integrity.restricts(link.instance))
1361
+ sealed = false;
1362
+ chain.push(ancestor);
1363
+ ancestor = link?.base ?? null;
1364
+ }
1365
+ if (!sealed || layout.accessors.length > 0)
1366
+ for (const member of chain)
1367
+ unsafeForStoreSink.add(member);
1368
+ }
1369
+ const storeSinkConstructors = new Set();
1370
+ for (const [declaration, layout] of input.classes)
1371
+ if (layout.constructor !== null && !unsafeForStoreSink.has(declaration))
1372
+ storeSinkConstructors.add(String(layout.constructor));
1373
+ const { callableMemberCandidates, repeatedConstructors, dyingArguments, formalsBorrowedIn, bodyCallsUnsafeKnownCallee, callableIdentityDemand, nativeIntegrityRestricted, fixedFieldStateConstant, singleEvaluationClasses, definitionCells } = programFactsOf(input.bodies, directCallables, input.placements, {
1112
1374
  captureFree: (functionId) => captures.of(functionId).kind === 'none',
1113
1375
  isBoxed: (declaration) => captures.isBoxed(declaration),
1114
1376
  isCoroutineBody,
1377
+ isConstructorBody: (body) => constructorBodies.has(String(body.sourceOwner)),
1378
+ isStoreSinkConstructor: (body) => storeSinkConstructors.has(String(body.sourceOwner)),
1115
1379
  classInstanceOf: (declaration) => input.classes.get(declaration)?.instance ?? null,
1380
+ shapeLayoutOf: (shapeId) => input.deriver.layoutOf(shapeId),
1116
1381
  plainFieldRead: (receiver, key) => {
1117
1382
  if (receiver.kind === 'class-ref') {
1118
1383
  // A class over a host base reads its members through the host's
@@ -1169,10 +1434,7 @@ export const renderTranslationUnit = (input) => {
1169
1434
  // the move of facts out of the target names as the unblocking
1170
1435
  // answer.
1171
1436
  const bodyFactsBySourceOwner = new Map(input.bodies.map((body) => [String(body.sourceOwner), body.facts]));
1172
- const capturesNothingOf = (callable) => {
1173
- const facts = bodyFactsBySourceOwner.get(String(callable));
1174
- return facts === undefined || (facts.capturedDeclarations.length === 0 && facts.capturedReceiver === null);
1175
- };
1437
+ const capturesNothingOf = (callable) => capturesNothing(bodyFactsBySourceOwner.get(String(callable)));
1176
1438
  // The conversion site of everything rendered outside a body: construct
1177
1439
  // thunks, field initializers, virtual dispatch adapters. Same census, same
1178
1440
  // drift list, one owner name.
@@ -1181,7 +1443,7 @@ export const renderTranslationUnit = (input) => {
1181
1443
  ...(selectionHelpers === undefined ? {} : { nativeSelectionHelpers: selectionHelpers }),
1182
1444
  printerDrift,
1183
1445
  owner: 'program',
1184
- layouts: recordLayoutPolicyOf(deriver, input.classes),
1446
+ layouts: recordLayoutPolicyOf(deriver, input.classes, input.wellKnownSymbols),
1185
1447
  classes: input.classes,
1186
1448
  captures
1187
1449
  };
@@ -1191,7 +1453,7 @@ export const renderTranslationUnit = (input) => {
1191
1453
  // now only renders the C++ struct members and adapter bodies for whatever
1192
1454
  // it says is dispatchable.
1193
1455
  const virtualVerdict = virtualDispatchVerdictOf(input.classes, (callable) => abiByBody.get(String(callable)) ?? null, capturesNothingOf, input.conversions);
1194
- const virtuals = virtualMethodEmission(programSite, input.classes, (callable) => abiByBody.get(String(callable)) ?? null, virtualVerdict);
1456
+ const virtuals = virtualMethodEmission(programSite, input.classes, (callable) => abiByBody.get(String(callable)) ?? null, virtualVerdict, instanceReparentTargetsOf(input.bodies, input.classes));
1195
1457
  // Which classes a box can hold, by the reflection census's own verdict. A
1196
1458
  // prototype property is read through a `gea::Value` only where an instance
1197
1459
  // reached a dynamic carrier the census could not see through -- the
@@ -1220,7 +1482,7 @@ export const renderTranslationUnit = (input) => {
1220
1482
  return held;
1221
1483
  })();
1222
1484
  publishBoxableClasses(input.classes, dynamicallyReadClasses);
1223
- const prototypeHooks = prototypeReadHooks(input.classes, (callable) => abiByBody.get(String(callable)) ?? null, capturesNothingOf, (declaration) => classBoxable(input.classes, declaration));
1485
+ const prototypeHooks = prototypeReadHooks(input.classes, (callable) => abiByBody.get(String(callable)) ?? null, capturesNothingOf, (declaration) => classBoxable(input.classes, declaration), input.wellKnownSymbols);
1224
1486
  const structMembers = new Map(virtuals.membersByStruct);
1225
1487
  for (const [struct, members] of prototypeHooks.membersByStruct)
1226
1488
  structMembers.set(struct, [...(structMembers.get(struct) ?? []), ...members]);
@@ -1232,7 +1494,7 @@ export const renderTranslationUnit = (input) => {
1232
1494
  // of the type the element declares. Each of those decides the member's type
1233
1495
  // for itself, and a census that narrowed one anyway would produce two
1234
1496
  // spellings of one storage.
1235
- const jsonStructs = renderJsonStructDeclarations(input.bodies, deriver);
1497
+ const jsonStructs = renderJsonStructDeclarations(input.bodies, deriver, programSite.layouts, input.classes, input.hosts.reactive);
1236
1498
  // A reactive class is NOT among them. `records.ts`'s `fieldStorageType`
1237
1499
  // spells a celled member from this same answer -- `Signal<long long>` where
1238
1500
  // the slot narrowed, `Signal<double>` where it did not -- so the cell and the
@@ -1342,17 +1604,25 @@ export const renderTranslationUnit = (input) => {
1342
1604
  // only to give it one has no reader and no consequence, and goes whole. Both
1343
1605
  // halves are whole-program questions, so they are answered once here rather
1344
1606
  // than per body.
1607
+ const classConstructions = new Map([...input.classes].map(([declaration, layout]) => [
1608
+ declaration,
1609
+ {
1610
+ base: constructedBaseOf(layout),
1611
+ constructor: layout.constructor,
1612
+ initializers: layout.fields.flatMap((field) => (field.initializer === null ? [] : [field.initializer]))
1613
+ }
1614
+ ]));
1345
1615
  const instantiation = {
1346
1616
  receiverIgnoringFunctions: functionsIgnoringTheirReceiver(input.bodies),
1347
- unobservableConstructions: classesConstructedUnobservably(new Map([...input.classes].map(([declaration, layout]) => [
1348
- declaration,
1349
- {
1350
- base: constructedBaseOf(layout),
1351
- constructor: layout.constructor,
1352
- initializers: layout.fields.flatMap((field) => (field.initializer === null ? [] : [field.initializer]))
1353
- }
1354
- ])), input.bodies)
1617
+ unobservableConstructions: classesConstructedUnobservably(classConstructions, input.bodies)
1355
1618
  };
1619
+ // Fields only construction writes (`ir/construction-only-fields.ts`). A
1620
+ // class whose reflection demand can write a field -- a boxed instance's
1621
+ // `obj[k] = v`, `Reflect.set`, `Object.assign` -- keeps that field's copy;
1622
+ // a missing census writes every field of every class.
1623
+ const constructionOnlyFields = constructionOnlyFieldsOf(input.bodies, classConstructions, input.reflection === undefined || input.reflection === null
1624
+ ? [...input.classes.keys()].map((declaration) => [declaration, 'all'])
1625
+ : [...input.reflection.classes].map(([declaration, demand]) => [declaration, reflectiveFieldWritesOf(demand)]));
1356
1626
  const excludedSignatureSlots = new Set();
1357
1627
  for (const body of input.bodies) {
1358
1628
  const abi = body.abi;
@@ -1375,10 +1645,13 @@ export const renderTranslationUnit = (input) => {
1375
1645
  excludedStructs,
1376
1646
  fieldSeeds,
1377
1647
  directCallees: directCallables,
1648
+ memberCandidates: callableMemberCandidates,
1378
1649
  methodBodies,
1650
+ classStructNameOf: cppClassName,
1379
1651
  excludedFormalOwners,
1380
1652
  excludedSignatureSlots
1381
1653
  });
1654
+ publishNarrowedStorageSlots(narrowedStorage.slots);
1382
1655
  // Published before `cppRecordDeclarations` runs, and for the same reason as
1383
1656
  // `classStaticFields` below: a class field's lazy-materialization plan is a
1384
1657
  // whole-compile fact (`class-layout.ts`'s `censusLazyArrowFields`), and
@@ -1396,7 +1669,10 @@ export const renderTranslationUnit = (input) => {
1396
1669
  // `cppRecordDeclarations` has not produced yet -- see the census's own
1397
1670
  // comment for why that is the right superset to refuse.
1398
1671
  publishConstantFieldInitializers(input.classes, censusConstantFieldInitializers(input.bodies, input.classes, input.hosts.reactive.fields));
1399
- const structs = cppRecordDeclarations(input.plan, deriver, input.classes, input.hosts.reactive, boundRecordFields, structMembers, narrowedStorage.slots, input.wellKnownSymbols, perFile, input.reflection, emissionRepresentations, input.physicalClasses ?? input.classes, (body) => captures.of(body).kind === 'ok', fixedFieldStateConstant, singleEvaluationClasses);
1672
+ const structs = cppRecordDeclarations(input.plan, deriver, input.classes, input.hosts.reactive, boundRecordFields, structMembers, narrowedStorage.slots, input.wellKnownSymbols, perFile, input.reflection, emissionRepresentations, input.physicalClasses ?? input.classes, (body) => captures.of(body).kind === 'ok', fixedFieldStateConstant,
1673
+ // A module may evaluate once in EACH worker realm. Keep the ordinary
1674
+ // per-instance reference to its constructor's realm-owned method state.
1675
+ input.realmStorage ? new Set() : singleEvaluationClasses, (shapeId, hasSymbolField) => nativeIntegrityRestricted.restrictsRecordShape(shapeId, hasSymbolField));
1400
1676
  const recursiveContainers = cppRecursiveContainerDeclarations(input.plan, emissionRepresentations);
1401
1677
  // Real storage for every `ClassName.KEY = value` site the whole program
1402
1678
  // contains -- three.js's own idiom for a class static, spelled as a bare
@@ -1411,9 +1687,10 @@ export const renderTranslationUnit = (input) => {
1411
1687
  // itself a struct needs that struct to already be a complete type, and
1412
1688
  // every body that reads or writes one has to find its extern-free
1413
1689
  // definition already in scope.
1414
- const classStaticFields = censusClassStaticFieldStorage(input.bodies, input.classes);
1690
+ const classStaticFields = censusClassStaticFieldStorage(input.bodies, input.classes, input.realmStorage);
1415
1691
  publishClassStaticFieldStorage(input.classes, classStaticFields.storage);
1416
- const classStatics = classStaticFieldStorageRows(classStaticFields.storage).map((row) => storageSpelling(row.type, row.name));
1692
+ publishConstructorViewShapes(input.classes, input.bodies);
1693
+ const classStatics = classStaticFieldStorageRows(classStaticFields.storage).map((row) => storageSpelling(row.type, row.storageName, input.realmStorage));
1417
1694
  // The reactive plan, completed with the two answers only this stage has.
1418
1695
  //
1419
1696
  // `revisions` is the struct renderer's own decision about which reactive
@@ -1447,7 +1724,12 @@ export const renderTranslationUnit = (input) => {
1447
1724
  const reactiveCensus = reactiveDependenciesOfBodies(input.bodies, input.classes, reactive);
1448
1725
  const hosts = {
1449
1726
  ...input.hosts,
1450
- reactive: { ...reactive, dependencies: reactiveCensus.all, nodeDependencies: reactiveCensus.node }
1727
+ reactive: {
1728
+ ...reactive,
1729
+ dependencies: reactiveCensus.all,
1730
+ nodeDependencies: reactiveCensus.node,
1731
+ projections: reactiveCensus.projections
1732
+ }
1451
1733
  };
1452
1734
  const hostMethodAliases = buildHostMethodAliasIndex(input.bodies, input.placements, hosts);
1453
1735
  // The JSON overload set the runtime header declares, re-introduced HERE when
@@ -1472,14 +1754,75 @@ export const renderTranslationUnit = (input) => {
1472
1754
  // name the host member instead (`buildHostMethodAliasIndex`) -- so declaring
1473
1755
  // it would leave a `CallableObject` of the method's own convention in the
1474
1756
  // unit, boxing an `any` formal that no code ever passes.
1475
- const globals = globalStorage(input.placements, new Set([...input.omitGlobals, ...hostMethodAliases.keys()]));
1757
+ const globals = globalStorage(input.placements, new Set([...input.omitGlobals, ...hostMethodAliases.keys()]), input.realmStorage);
1476
1758
  // Environment structs ahead of every forward signature: a capturing body's
1477
1759
  // own formal names its struct as a pointer type, so the struct must already
1478
1760
  // be a complete type by the time that formal is spelled.
1761
+ // Every member of a recursion group is entered with the group's one struct,
1762
+ // declared once under the group's name.
1763
+ // Which group members' identity the program ever asks for, keyed by
1764
+ // position in `group.members` -- the same census `sharedGroupMemberText`
1765
+ // (`emit-binding-reference.ts`) already gates `identifyCallable` on, read
1766
+ // back here so the struct reserves a header field for exactly the members
1767
+ // that census observes, never more. The carrier scanned per member is its
1768
+ // own `allocate-callable` result representation, the same value that
1769
+ // gates `sharedGroupMemberText`'s check there -- so a member absent from
1770
+ // this scan (should not happen; every group member is written from the
1771
+ // one allocation `ir/captures.ts` admitted it for) keeps its field rather
1772
+ // than dropping something this census was never asked about.
1773
+ const groupMemberIdentityObserved = (group) => {
1774
+ const ownerBody = input.bodies.find((candidate) => candidate.sourceOwner === group.owner);
1775
+ const carrierByFunction = new Map();
1776
+ if (ownerBody) {
1777
+ for (const block of ownerBody.blocks.values()) {
1778
+ for (const operation of block.operations) {
1779
+ if (operation.kind === 'allocate-callable' && !carrierByFunction.has(operation.functionId)) {
1780
+ carrierByFunction.set(operation.functionId, operation.result.representation);
1781
+ }
1782
+ }
1783
+ }
1784
+ }
1785
+ return group.members.map((member) => {
1786
+ const carrier = carrierByFunction.get(member.functionId);
1787
+ return carrier === undefined ? true : callableIdentityDemand.observes(carrier);
1788
+ });
1789
+ };
1790
+ const declaredGroups = new Set();
1791
+ const declaredFrames = new Set();
1792
+ const frames = input.bodies.flatMap((body) => {
1793
+ const frame = captures.frameOf(body.sourceOwner);
1794
+ if (frame === null || declaredFrames.has(frame.owner))
1795
+ return [];
1796
+ declaredFrames.add(frame.owner);
1797
+ const identities = captures.frameIdentitiesOf(frame.owner);
1798
+ const ownerBody = input.bodies.find((candidate) => candidate.sourceOwner === frame.owner);
1799
+ const carrierByFunction = new Map();
1800
+ if (ownerBody) {
1801
+ for (const block of ownerBody.blocks.values()) {
1802
+ for (const operation of block.operations) {
1803
+ if (operation.kind === 'allocate-callable' && !carrierByFunction.has(operation.functionId)) {
1804
+ carrierByFunction.set(operation.functionId, operation.result.representation);
1805
+ }
1806
+ }
1807
+ }
1808
+ }
1809
+ const kept = identities.map((functionId) => {
1810
+ const carrier = carrierByFunction.get(functionId);
1811
+ return carrier === undefined ? true : callableIdentityDemand.observes(carrier);
1812
+ });
1813
+ return [frameDeclarationOf(frame, identities, kept)];
1814
+ });
1479
1815
  const environments = input.bodies.flatMap((body) => {
1480
- const declaration = environmentDeclarationOf(body.sourceOwner, captures.of(body.sourceOwner));
1816
+ const group = captures.groupOf(body.sourceOwner);
1817
+ if (group !== null) {
1818
+ if (declaredGroups.has(group.id))
1819
+ return [];
1820
+ declaredGroups.add(group.id);
1821
+ }
1822
+ const declaration = environmentDeclarationOf(group?.id ?? body.sourceOwner, captures.of(body.sourceOwner), group, group ? groupMemberIdentityObserved(group) : []);
1481
1823
  return declaration === null ? [] : [declaration];
1482
1824
  });
1825
+ environments.unshift(...frames);
1483
1826
  // The census answers per SLOT; a signature is spelled per body, so its
1484
1827
  // formal slots are read back here into the positions each body declares.
1485
1828
  // A cycle can only run through something this unit renders that carries a
@@ -1536,24 +1879,117 @@ export const renderTranslationUnit = (input) => {
1536
1879
  for (const body of input.bodies) {
1537
1880
  if (isRegionId(body.sourceOwner))
1538
1881
  continue;
1539
- const entry = stableBorrowEntryOf(body, body.sourceOwner, (declaration) => {
1540
- const placement = input.placements.get(declaration);
1541
- return placement?.storage.kind === 'local' && placement.storage.owner === body.sourceOwner && !captures.isBoxed(declaration)
1542
- ? placement.representation
1543
- : null;
1544
- }, formalsBorrowedIn(body.sourceOwner), dyingArguments, bodyCallsUnsafeKnownCallee(body.sourceOwner), {
1545
- captureFree: captures.of(body.sourceOwner).kind === 'none',
1546
- synchronous: !isCoroutineBody(body),
1547
- singleBody: physicalCounts.get(String(body.sourceOwner)) === 1,
1548
- unchangedNumericAbi: formalsNarrowedIn(body.sourceOwner).size === 0 && !resultNarrowedIn(body.sourceOwner)
1549
- });
1882
+ const entry = constructorBodies.has(String(body.sourceOwner))
1883
+ ? null
1884
+ : stableBorrowEntryOf(body, body.sourceOwner, (declaration) => {
1885
+ const placement = input.placements.get(declaration);
1886
+ return placement?.storage.kind === 'local' && placement.storage.owner === body.sourceOwner && !captures.isBoxed(declaration)
1887
+ ? placement.representation
1888
+ : null;
1889
+ }, formalsBorrowedIn(body.sourceOwner), dyingArguments, {
1890
+ captureFree: captures.of(body.sourceOwner).kind === 'none',
1891
+ synchronous: !isCoroutineBody(body),
1892
+ singleBody: physicalCounts.get(String(body.sourceOwner)) === 1,
1893
+ unchangedNumericAbi: formalsNarrowedIn(body.sourceOwner).size === 0 && !resultNarrowedIn(body.sourceOwner)
1894
+ });
1550
1895
  if (entry)
1551
1896
  stableBorrowEntries.set(cppBodyName(body.sourceOwner), entry);
1897
+ if (process.env.GEA_BORROW_DEBUG) {
1898
+ const abi = body.abi;
1899
+ const constRef = abi ? abi.parameters.filter((parameter) => parameter.passing === 'const-ref').length : 0;
1900
+ const readonly = abi
1901
+ ? readonlyBorrowFormalsOf(body, (declaration) => {
1902
+ const placement = input.placements.get(declaration);
1903
+ return placement?.storage.kind === 'local' && placement.storage.owner === body.sourceOwner && !captures.isBoxed(declaration)
1904
+ ? placement.representation
1905
+ : null;
1906
+ }, dyingArguments).size
1907
+ : 0;
1908
+ const flags = [
1909
+ `entry=${entry ? 'yes' : 'no'}`,
1910
+ `abi=${abi ? 'yes' : 'no'}`,
1911
+ `rest=${abi?.restFrom ?? 'null'}`,
1912
+ `constRef=${constRef}`,
1913
+ `readonly=${readonly}`,
1914
+ `captureFree=${captures.of(body.sourceOwner).kind === 'none'}`,
1915
+ `sync=${!isCoroutineBody(body)}`,
1916
+ `single=${physicalCounts.get(String(body.sourceOwner)) === 1}`,
1917
+ `numeric=${formalsNarrowedIn(body.sourceOwner).size === 0 && !resultNarrowedIn(body.sourceOwner)}`,
1918
+ `unsafeCallee=${bodyCallsUnsafeKnownCallee(body.sourceOwner)}`,
1919
+ `borrowedAlready=${formalsBorrowedIn(body.sourceOwner).size}`
1920
+ ];
1921
+ console.error(`[stable-borrow] ${cppBodyName(body.sourceOwner)} ${flags.join(' ')}`);
1922
+ }
1923
+ }
1924
+ // The integer version: a second rendering of a body under the premise that
1925
+ // its unproved number formals hold integers, entered from the original after
1926
+ // testing exactly that (`gea::carriesExactInteger`). A formal fed from a
1927
+ // double the census cannot see into -- bson's `deserializeObject(buffer,
1928
+ // options.index ?? 0, ...)`, where the options record is filled from dynamic
1929
+ // values -- keeps every offset derived from it a double, although every call
1930
+ // the program makes passes an integer. The version buys what the census
1931
+ // cannot prove at the one place it can be tested, and computes the same
1932
+ // Numbers (`ir/integers.ts`'s rounding spelling covers what leaves +-2^53).
1933
+ //
1934
+ // Only where it pays for a second copy of the code: the premise must narrow
1935
+ // at least `integerVersionGain` more values than the body narrows today.
1936
+ const integerVersionGain = 8;
1937
+ const integerVersions = new Map();
1938
+ for (const body of input.bodies) {
1939
+ const abi = body.abi;
1940
+ if (abi === null || abi.restFrom !== null || isRegionId(body.sourceOwner))
1941
+ continue;
1942
+ if (captures.of(body.sourceOwner).kind !== 'none' || isCoroutineBody(body) || asyncPromiseViewOf(body) !== null)
1943
+ continue;
1944
+ if (commonJsOwnerOf(body) !== null || physicalCounts.get(String(body.sourceOwner)) !== 1)
1945
+ continue;
1946
+ const narrowed = formalsNarrowedIn(body.sourceOwner);
1947
+ const ordinals = new Set();
1948
+ abi.parameters.forEach((parameter, ordinal) => {
1949
+ if (parameter.value.kind === 'scalar' && parameter.value.domain === 'number' && !narrowed.has(ordinal))
1950
+ ordinals.add(ordinal);
1951
+ });
1952
+ if (ordinals.size === 0)
1953
+ continue;
1954
+ const today = narrowableIntegersOf(body, narrowedStorage.factsOf(body.sourceOwner)).values.size;
1955
+ const premised = narrowableIntegersOf(body, narrowedStorage.entryCheckedFactsOf(body.sourceOwner, ordinals)).values.size;
1956
+ if (process.env['GEA_INTEGER_VERSION_DEBUG'])
1957
+ console.error(`[integer-version] ${cppBodyName(body.sourceOwner)} ${today} -> ${premised}`);
1958
+ if (premised - today >= integerVersionGain)
1959
+ integerVersions.set(String(body.sourceOwner), ordinals);
1552
1960
  }
1961
+ const integerVersionNameOf = (body) => `${stableBorrowEntries.get(cppBodyName(body.sourceOwner))?.name ?? cppBodyName(body.sourceOwner)}_integral`;
1962
+ const integerVersionSignatureOf = (body, ordinals) => signatureOf(body, captures, new Set([...formalsNarrowedIn(body.sourceOwner), ...ordinals]), resultNarrowedIn(body.sourceOwner), stableBorrowEntries.get(cppBodyName(body.sourceOwner))?.formals ?? formalsBorrowedIn(body.sourceOwner), integerVersionNameOf(body));
1963
+ // The async bodies that also get a `_task` twin (`taskTwinEligible`): the
1964
+ // same frame answering a `gea::Task<V>` to a caller that awaits the call at
1965
+ // once. Only a body reached by its own name (no stable borrow entry, no
1966
+ // CommonJS scope of its own) and that nothing renames.
1967
+ const taskBodies = new Set();
1968
+ for (const body of input.bodies) {
1969
+ if (isRegionId(body.sourceOwner) || !taskTwinEligible(body) || commonJsOwnerOf(body) !== null || resultNarrowedIn(body.sourceOwner))
1970
+ continue;
1971
+ if (stableBorrowEntries.has(cppBodyName(body.sourceOwner)))
1972
+ continue;
1973
+ taskBodies.add(cppBodyName(body.sourceOwner));
1974
+ }
1975
+ const taskNameOf = (body) => `${cppBodyName(body.sourceOwner)}_task`;
1976
+ const taskSignatureOf = (body) => {
1977
+ const named = signatureOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), formalsBorrowedIn(body.sourceOwner), taskNameOf(body));
1978
+ const promise = 'gea::Promise<';
1979
+ if (!named.startsWith(promise))
1980
+ throw new Error(`a task twin of ${cppBodyName(body.sourceOwner)} expected a gea::Promise result, found ${named.slice(0, 60)}`);
1981
+ return `gea::Task<${named.slice(promise.length)}`;
1982
+ };
1553
1983
  const signatures = input.bodies.flatMap((body) => {
1554
1984
  const original = `${signatureOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), formalsBorrowedIn(body.sourceOwner))};`;
1985
+ if (taskBodies.has(cppBodyName(body.sourceOwner)))
1986
+ return [original, `${taskSignatureOf(body)};`];
1555
1987
  const entry = stableBorrowEntries.get(cppBodyName(body.sourceOwner));
1556
- return entry === undefined ? [original] : [original, `${signatureOf(body, captures, new Set(), false, entry.formals, entry.name)};`];
1988
+ const versioned = integerVersions.get(String(body.sourceOwner));
1989
+ const version = versioned === undefined ? [] : [`${integerVersionSignatureOf(body, versioned)};`];
1990
+ return entry === undefined
1991
+ ? [original, ...version]
1992
+ : [original, `${signatureOf(body, captures, new Set(), false, entry.formals, entry.name)};`, ...version];
1557
1993
  });
1558
1994
  // Source/name/length reflection keeps its facts program-wide, including
1559
1995
  // functions arriving through fields and ABI adapters -- one registration
@@ -1588,6 +2024,9 @@ export const renderTranslationUnit = (input) => {
1588
2024
  const preserveFunctionFacts = input.bodies.some((body) => {
1589
2025
  const keys = stringConstantsOf(body);
1590
2026
  const callable = (representation) => representation.kind === 'function-value-dispatch' || representation.kind === 'function-and-constructor';
2027
+ const holdsCallable = (representation) => callable(representation) ||
2028
+ (representation.kind === 'optional' && holdsCallable(representation.payload)) ||
2029
+ (representation.kind === 'tagged-union' && representation.arms.some((arm) => holdsCallable(arm.value)));
1591
2030
  const reflectors = new Set();
1592
2031
  for (const block of body.blocks.values())
1593
2032
  for (const operation of block.operations) {
@@ -1607,6 +2046,12 @@ export const renderTranslationUnit = (input) => {
1607
2046
  traceFunctionFacts(body, 'a callable boxed into a dynamic carrier');
1608
2047
  return true;
1609
2048
  }
2049
+ // A coercion of a callable operand -- `fn + ''`, a template, the arm
2050
+ // of a union holding one -- spells its source text (`emit-tostring.ts`).
2051
+ if (operation.kind === 'compute' && operation.operands.some((operand) => holdsCallable(operand.representation))) {
2052
+ traceFunctionFacts(body, 'a computation over a callable operand');
2053
+ return true;
2054
+ }
1610
2055
  if (operation.kind === 'get') {
1611
2056
  if (callable(operation.receiver.representation)) {
1612
2057
  const key = keys.get(operation.key.value);
@@ -1722,24 +2167,54 @@ export const renderTranslationUnit = (input) => {
1722
2167
  continue;
1723
2168
  }
1724
2169
  try {
1725
- const sections = emitBody(body, input.placements, input.classes, hosts, deriver, input.wellKnownSymbols, captures, symbolKeys, templateObjects, directCallables, virtuals.dispatched, narrowedStorage.factsOf(body.sourceOwner), formalsNarrowedIn(body.sourceOwner), repeatedConstructors, dyingArguments, instantiation, (callable) => abiByBody.get(String(callable)) ?? null, functionFacts, hostMethodAliases, callableMemberCandidates, borrowableMemberBodies, stableBorrowEntries, printerDrift, input.conversions, selectionHelpers, callableIdentityDemand, nativeIntegrityRestricted, fixedFieldStateConstant);
2170
+ const promiseView = asyncPromiseViewOf(body);
2171
+ const promiseViewEntry = promiseView === null ? null : asyncPromiseViewEntryOf(body, promiseView, captures, programSite, formalsNarrowedIn(body.sourceOwner));
2172
+ const sections = emitBody(promiseView ?? body, input.placements, input.classes, hosts, deriver, input.wellKnownSymbols, captures, symbolKeys, templateObjects, directCallables, virtuals.dispatched, narrowedStorage.factsOf(body.sourceOwner), formalsNarrowedIn(body.sourceOwner), repeatedConstructors, dyingArguments, instantiation, (callable) => abiByBody.get(String(callable)) ?? null, functionFacts, hostMethodAliases, callableMemberCandidates, borrowableMemberBodies, stableBorrowEntries, printerDrift, input.conversions, selectionHelpers, callableIdentityDemand, nativeIntegrityRestricted, fixedFieldStateConstant, definitionCells, constructionOnlyFields, keyOrderUnobserved, taskBodies);
1726
2173
  const stableEntry = stableBorrowEntries.get(cppBodyName(body.sourceOwner));
1727
- const commonJsScope = commonJsOwner === null || commonJsOwner.nativeRecord
2174
+ const versioned = integerVersions.get(String(body.sourceOwner));
2175
+ const borrowed = stableEntry?.formals ?? formalsBorrowedIn(body.sourceOwner);
2176
+ const integerVersion = versioned === undefined
1728
2177
  ? []
1729
- : [`gea::commonjs::Scope commonjs_scope(${cppCommonJsRecordName(commonJsOwner.owner)}());`];
2178
+ : (() => {
2179
+ const versionSections = emitBody(body, input.placements, input.classes, hosts, deriver, input.wellKnownSymbols, captures, symbolKeys, templateObjects, directCallables, virtuals.dispatched, narrowedStorage.entryCheckedFactsOf(body.sourceOwner, versioned), new Set([...formalsNarrowedIn(body.sourceOwner), ...versioned]), repeatedConstructors, dyingArguments, instantiation, (callable) => abiByBody.get(String(callable)) ?? null, functionFacts, hostMethodAliases, callableMemberCandidates, borrowableMemberBodies, stableBorrowEntries, printerDrift, input.conversions, selectionHelpers, callableIdentityDemand, nativeIntegrityRestricted, fixedFieldStateConstant, definitionCells, constructionOnlyFields, keyOrderUnobserved, taskBodies);
2180
+ const versionOpening = withUnreadParametersUnnamed(integerVersionSignatureOf(body, versioned), versionSections.map((section) => section.text));
2181
+ return [plain(`${versionOpening} {`), ...versionSections, plain('}')];
2182
+ })();
2183
+ const integerDispatch = versioned === undefined || body.abi === null
2184
+ ? []
2185
+ : [
2186
+ `if (${[...versioned].map((ordinal) => `gea::carriesExactInteger(${cppFormalName(ordinal)})`).join(' && ')}) ` +
2187
+ `return ${integerVersionNameOf(body)}(${[
2188
+ ...(body.abi.receiver !== null ? [cppReceiverName] : []),
2189
+ ...body.abi.parameters.map((_, ordinal) => versioned.has(ordinal)
2190
+ ? `static_cast<long long>(${cppFormalName(ordinal)})`
2191
+ : borrowed.has(ordinal)
2192
+ ? cppFormalName(ordinal)
2193
+ : `std::move(${cppFormalName(ordinal)})`)
2194
+ ].join(', ')});`
2195
+ ];
2196
+ const commonJsScope = [
2197
+ ...coroutineEnvironmentPrologueOf(promiseView ?? body, captures),
2198
+ ...(commonJsOwner === null || commonJsOwner.nativeRecord
2199
+ ? []
2200
+ : [`gea::commonjs::Scope commonjs_scope(${cppCommonJsRecordName(commonJsOwner.owner)}());`])
2201
+ ];
1730
2202
  // A body's formals are named `gea_this`/`gea_arg_N`/`gea_e` by this
1731
2203
  // emitter, never by the user's own source -- so whether the source
1732
2204
  // *read* a given position is a fact only the rendered body text can
1733
2205
  // answer, exactly as `records.ts`'s reflection hooks already spell
1734
2206
  // "unread" by omitting the name rather than by (void)-casting it.
1735
- const opening = withUnreadParametersUnnamed(signatureOf(body, captures, formalsNarrowedIn(body.sourceOwner), resultNarrowedIn(body.sourceOwner), stableEntry?.formals ?? formalsBorrowedIn(body.sourceOwner), stableEntry?.name ?? cppBodyName(body.sourceOwner)), [...commonJsScope, ...sections.map((section) => section.text)]);
2207
+ const opening = withUnreadParametersUnnamed(signatureOf(promiseView ?? body, captures, formalsNarrowedIn(body.sourceOwner), promiseView === null && resultNarrowedIn(body.sourceOwner), stableEntry?.formals ?? formalsBorrowedIn(body.sourceOwner), stableEntry?.name ?? (promiseView === null ? cppBodyName(body.sourceOwner) : asyncPromiseViewName(body.sourceOwner))), [...integerDispatch, ...commonJsScope, ...sections.map((section) => section.text)]);
1736
2208
  renderedBodies.push({
1737
2209
  body,
1738
2210
  artifacts: [
1739
2211
  plain(`${opening} {`),
2212
+ ...integerDispatch.map(plain),
1740
2213
  ...commonJsScope.map(plain),
1741
2214
  ...sections,
1742
2215
  plain('}'),
2216
+ ...integerVersion,
2217
+ ...(promiseViewEntry === null ? [] : promiseViewEntry.map(plain)),
1743
2218
  ...(stableEntry === undefined
1744
2219
  ? []
1745
2220
  : [
@@ -1757,7 +2232,22 @@ export const renderTranslationUnit = (input) => {
1757
2232
  ...stableEntry.abi.parameters.map((_, ordinal) => stableEntry.formals.has(ordinal) ? cppFormalName(ordinal) : `std::move(${cppFormalName(ordinal)})`)
1758
2233
  ].join(', ')});`),
1759
2234
  plain('}')
1760
- ])
2235
+ ]),
2236
+ // The twin: the same frame, answering a `gea::Task<V>` to a caller
2237
+ // that awaits the call at once (`taskTwinEligible`). Same text, a
2238
+ // different return type, so the promise type that makes it a
2239
+ // coroutine differs and nothing else.
2240
+ ...(taskBodies.has(cppBodyName(body.sourceOwner)) &&
2241
+ promiseView === null &&
2242
+ stableEntry === undefined &&
2243
+ integerDispatch.length === 0
2244
+ ? [
2245
+ plain(`${withUnreadParametersUnnamed(taskSignatureOf(body), [...commonJsScope, ...sections.map((section) => section.text)])} {`),
2246
+ ...commonJsScope.map(plain),
2247
+ ...sections,
2248
+ plain('}')
2249
+ ]
2250
+ : [])
1761
2251
  ],
1762
2252
  templateObjects: [...templateObjects.values()].slice(templateObjectsBefore)
1763
2253
  });
@@ -1765,11 +2255,16 @@ export const renderTranslationUnit = (input) => {
1765
2255
  catch (error) {
1766
2256
  if (!isCppEmitBlockedError(error))
1767
2257
  throw error;
1768
- refused.push({ owner: body.sourceOwner, reason: error.message, key: error.kind });
2258
+ refused.push({
2259
+ owner: body.sourceOwner,
2260
+ reason: error.message,
2261
+ key: error.kind,
2262
+ ...(error.lineage === undefined ? {} : { lineage: error.lineage })
2263
+ });
1769
2264
  }
1770
2265
  }
1771
2266
  let entry = null;
1772
- const commonJs = commonJsDefinitionsOf(input.bodies);
2267
+ const commonJs = commonJsDefinitionsOf(input.bodies, input.realmStorage);
1773
2268
  refused.push(...commonJs.refused);
1774
2269
  if (input.entrySymbol !== null) {
1775
2270
  const rendered = entryDefinitionOf(input.entrySymbol, input.moduleOrder, input.bodies, commonJs.modules, commonJs.hasBuiltinModuleRegistry);
@@ -1790,26 +2285,52 @@ export const renderTranslationUnit = (input) => {
1790
2285
  // into the rendered text rather than appended, because the aliases are
1791
2286
  // known only once the LAST body has been rendered, and the block has to
1792
2287
  // come first.
2288
+ //
2289
+ // The unit functions the same session recorded (`unitFunctionName`) are
2290
+ // declared at the end of that block, so a struct's own members may call
2291
+ // one, and defined once at `unitFunctionMarker`, after every struct body a
2292
+ // conversion builds and every body signature a record view's bound method
2293
+ // or getter calls. They are `inline` where several units include the header
2294
+ // that holds them.
1793
2295
  const unionAliasMarker = '// gea-union-aliases';
2296
+ const unitFunctionMarker = '// gea-unit-functions';
2297
+ const unitFunctionLinkage = perFile ? 'inline ' : '[[maybe_unused]] static ';
1794
2298
  const spliceUnionAliases = (source) => {
1795
- const aliases = endUnionAliasing();
2299
+ const { aliases, functions } = endUnionAliasing();
1796
2300
  const forwards = [...recursiveContainers, ...structs.declarations, ...jsonStructs.declarations].filter((declaration) => declaration.startsWith('struct ') && declaration.endsWith(';') && !declaration.includes('{'));
1797
- const block = [...forwards, ...aliases.map(({ name, spelling }) => `using ${name} = ${spelling};`)].join('\n');
1798
- return spliceRendered(source, unionAliasMarker, block);
2301
+ const block = [
2302
+ ...forwards,
2303
+ ...aliases.map(({ name, spelling }) => `using ${name} = ${spelling};`),
2304
+ ...functions.map(({ signature }) => `${unitFunctionLinkage}${signature};`)
2305
+ ].join('\n');
2306
+ const definitions = functions.map(({ signature, body }) => `${unitFunctionLinkage}${signature} { ${body} }`).join('\n');
2307
+ return spliceRendered(spliceRendered(source, unionAliasMarker, block), unitFunctionMarker, definitions);
1799
2308
  };
1800
2309
  const appendStructDeclarations = (builder) => {
1801
2310
  for (const declaration of recursiveContainers)
1802
2311
  builder.append(plain(declaration));
2312
+ const qualifier = isolate && namespaceName !== null ? `${namespaceName}::` : '';
2313
+ const recursiveTraceEdges = cppRecursiveContainerTraceEdges(input.plan, qualifier, emissionRepresentations);
2314
+ // The specializations' class halves go before any program struct, which
2315
+ // may ask `TraceEdges<wrapper>::supported` in its own definition; their
2316
+ // `visit` bodies stay below with the class-base specializations.
2317
+ if (recursiveTraceEdges.declarations.length > 0) {
2318
+ if (isolate)
2319
+ builder.append(plain(namespaceClose));
2320
+ for (const declaration of recursiveTraceEdges.declarations)
2321
+ builder.append(plain(declaration));
2322
+ if (isolate)
2323
+ builder.append(plain(namespaceOpen));
2324
+ }
1803
2325
  for (const declaration of structs.declarations)
1804
2326
  builder.append(plain(declaration));
1805
- const qualifier = isolate && namespaceName !== null ? `${namespaceName}::` : '';
1806
2327
  // A recursive callable/container wrapper's `gea::detail::TraceEdges`
1807
2328
  // specialisation has the exact same problem `structs.runtimeClassBases`
1808
2329
  // solves below: re-opening `namespace gea::detail` from INSIDE the
1809
2330
  // isolating namespace declares a shadow `gea`, not the real one. So it is
1810
2331
  // closed out to global scope here too, sharing the one close/reopen
1811
2332
  // rather than doing it twice.
1812
- const recursiveContainerTraceEdges = cppRecursiveContainerTraceEdges(input.plan, qualifier, emissionRepresentations);
2333
+ const recursiveContainerTraceEdges = recursiveTraceEdges.definitions;
1813
2334
  if (recursiveContainerTraceEdges.length === 0 && structs.runtimeClassBases.length === 0)
1814
2335
  return;
1815
2336
  // Explicit specializations belong to the runtime template's namespace,
@@ -1832,6 +2353,8 @@ export const renderTranslationUnit = (input) => {
1832
2353
  if (!perFile) {
1833
2354
  const builder = createCppDocumentBuilder();
1834
2355
  builder.append(plain(prelude));
2356
+ for (const declaration of nativeHandleDeclarations)
2357
+ builder.append(plain(declaration));
1835
2358
  // Everything from here to `runtimeDefinitions` is this program's own, and in
1836
2359
  // a resident build no other unit may see any of it. See `isolateSymbols`.
1837
2360
  //
@@ -1875,20 +2398,22 @@ export const renderTranslationUnit = (input) => {
1875
2398
  // After every body has a name, because each dispatch member forwards to one.
1876
2399
  for (const definition of virtuals.definitions)
1877
2400
  builder.append(plain(definition));
1878
- for (const definition of prototypeHooks.definitions)
1879
- builder.append(plain(definition));
2401
+ // A prototype hook names a method's declaration tag (`prototypeReadHooks`).
1880
2402
  for (const tag of declarationTags)
1881
2403
  builder.append(plain(tag));
2404
+ for (const definition of prototypeHooks.definitions)
2405
+ builder.append(plain(definition));
1882
2406
  for (const thunk of thunks.values())
1883
2407
  builder.append(plain(thunk.definition));
1884
2408
  // After the body declarations: a construct function calls the field
1885
2409
  // initializers and the constructor body by name.
1886
2410
  for (const definition of constructDefinitionsOf(constructions))
1887
2411
  builder.append(plain(definition));
1888
- for (const definition of symbolKeyDefinitions(symbolKeys))
2412
+ for (const definition of symbolKeyDefinitions(symbolKeys, input.realmStorage))
1889
2413
  builder.append(plain(definition));
1890
2414
  for (const definition of templateObjectDefinitions(templateObjects))
1891
2415
  builder.append(plain(definition));
2416
+ builder.append(plain(unitFunctionMarker));
1892
2417
  for (const rendered of renderedBodies)
1893
2418
  for (const artifact of rendered.artifacts)
1894
2419
  builder.append(artifact);
@@ -1929,6 +2454,8 @@ export const renderTranslationUnit = (input) => {
1929
2454
  const runtimeHeader = createCppDocumentBuilder();
1930
2455
  runtimeHeader.append(plain('#pragma once'));
1931
2456
  runtimeHeader.append(plain(prelude));
2457
+ for (const declaration of nativeHandleDeclarations)
2458
+ runtimeHeader.append(plain(declaration));
1932
2459
  const header = createCppDocumentBuilder();
1933
2460
  header.append(plain('#pragma once'));
1934
2461
  header.append(plain(`#include "${runtimeHeaderName}"`));
@@ -1973,41 +2500,67 @@ export const renderTranslationUnit = (input) => {
1973
2500
  for (const prototype of construction.constructPrototypes)
1974
2501
  header.append(plain(prototype));
1975
2502
  }
1976
- for (const definition of symbolKeyDefinitions(symbolKeys))
2503
+ for (const definition of symbolKeyDefinitions(symbolKeys, input.realmStorage))
1977
2504
  header.append(plain(definition));
2505
+ header.append(plain(unitFunctionMarker));
1978
2506
  if (isolate)
1979
2507
  header.append(plain(namespaceClose));
1980
- const program = createCppDocumentBuilder();
1981
- program.append(plain(include));
1982
- // At global scope whether or not the program is isolated, because that is
1983
- // where the header declared them: an absent global is a host's name, and a
1984
- // host's name is never inside the program's namespace.
1985
- for (const definition of absent)
1986
- program.append(plain(definition.text));
1987
- if (isolate)
1988
- program.append(plain(namespaceOpen));
1989
- for (const spelling of classStatics)
1990
- program.append(plain(spelling.definition));
1991
- for (const spelling of globals)
1992
- program.append(plain(spelling.definition));
1993
- for (const helper of selectionHelpers?.values() ?? [])
1994
- program.append(plain(helper.definition));
1995
- for (const definition of virtuals.definitions)
1996
- program.append(plain(definition));
1997
- for (const definition of prototypeHooks.definitions)
1998
- program.append(plain(definition));
1999
2508
  const classStructNames = new Set([...input.classes.values()].map((layout) => cppClassName(layout.declaration)));
2509
+ const recordTables = [];
2000
2510
  for (const [structName, definitions] of structs.fieldDefinitionsByStruct) {
2001
2511
  if (!classStructNames.has(structName))
2002
- for (const definition of definitions)
2003
- program.append(plain(definition));
2512
+ recordTables.push(definitions.map(plain));
2004
2513
  }
2005
- if (isolate)
2006
- program.append(plain(namespaceClose));
2007
- for (const definition of runtimeDefinitions)
2008
- program.append(plain(definition));
2009
- if (entry !== null)
2010
- program.append(plain(entry));
2514
+ const programWith = (tables) => {
2515
+ const program = createCppDocumentBuilder();
2516
+ program.append(plain(include));
2517
+ // At global scope whether or not the program is isolated, because that is
2518
+ // where the header declared them: an absent global is a host's name, and a
2519
+ // host's name is never inside the program's namespace.
2520
+ for (const definition of absent)
2521
+ program.append(plain(definition.text));
2522
+ if (isolate)
2523
+ program.append(plain(namespaceOpen));
2524
+ for (const spelling of classStatics)
2525
+ program.append(plain(spelling.definition));
2526
+ for (const spelling of globals)
2527
+ program.append(plain(spelling.definition));
2528
+ for (const helper of selectionHelpers?.values() ?? [])
2529
+ program.append(plain(helper.definition));
2530
+ for (const definition of virtuals.definitions)
2531
+ program.append(plain(definition));
2532
+ for (const definition of prototypeHooks.definitions)
2533
+ program.append(plain(definition));
2534
+ for (const table of tables)
2535
+ for (const artifact of table)
2536
+ program.append(artifact);
2537
+ if (isolate)
2538
+ program.append(plain(namespaceClose));
2539
+ for (const definition of runtimeDefinitions)
2540
+ program.append(plain(definition));
2541
+ if (entry !== null)
2542
+ program.append(plain(entry));
2543
+ return render(program.seal());
2544
+ };
2545
+ // Record field tables belong to no source file, so a program with many
2546
+ // records put every table in this one unit: 19 MB of the MongoDB driver's
2547
+ // 60, which no compiler finished inside the build's command cap. Over the
2548
+ // budget they move to units of their own; their members are out-of-line
2549
+ // definitions of structs the header declares, so any unit may hold them.
2550
+ const unitOpen = [plain(include), ...(isolate ? [plain(namespaceOpen)] : [])];
2551
+ const unitClose = isolate ? [plain(namespaceClose)] : [];
2552
+ const wholeProgram = programWith(recordTables);
2553
+ const programUnits = recordTables.length === 0 || Buffer.byteLength(wholeProgram, 'utf8') <= cppUnitByteBudget
2554
+ ? [{ role: 'program', fileName: `${input.unitBaseName}.cpp`, sourceFile: null, source: wholeProgram }]
2555
+ : [
2556
+ { role: 'program', fileName: `${input.unitBaseName}.cpp`, sourceFile: null, source: programWith([]) },
2557
+ ...chunkCppItems(unitOpen, recordTables, unitClose).map((source, index) => ({
2558
+ role: 'module',
2559
+ fileName: cppChunkFileName(`${input.unitBaseName}.records.cpp`, index),
2560
+ sourceFile: null,
2561
+ source
2562
+ }))
2563
+ ];
2011
2564
  // Bodies and classes grouped by the file that declared them. The identity is
2012
2565
  // the grouping key; the file name is only what the unit is called.
2013
2566
  const groups = new Map();
@@ -2035,39 +2588,32 @@ export const renderTranslationUnit = (input) => {
2035
2588
  const units = [
2036
2589
  { role: 'runtime-header', fileName: runtimeHeaderName, sourceFile: null, source: render(runtimeHeader.seal()) },
2037
2590
  { role: 'header', fileName: headerName, sourceFile: null, source: spliceUnionAliases(render(header.seal())) },
2038
- { role: 'program', fileName: `${input.unitBaseName}.cpp`, sourceFile: null, source: render(program.seal()) }
2591
+ ...programUnits
2039
2592
  ];
2040
2593
  for (const file of files) {
2041
2594
  const group = groups.get(file.identity);
2042
2595
  if (!group)
2043
2596
  continue;
2044
- const unit = createCppDocumentBuilder();
2045
- unit.append(plain(include));
2046
- if (isolate)
2047
- unit.append(plain(namespaceOpen));
2048
- for (const definition of group.fieldDefinitions)
2049
- unit.append(plain(definition));
2050
- for (const rendered of group.bodies)
2051
- for (const definition of rendered.templateObjects)
2052
- unit.append(plain(definition.text));
2053
- for (const rendered of group.bodies) {
2054
- const thunk = thunks.get(rendered.body);
2055
- if (thunk)
2056
- unit.append(plain(thunk.definition));
2057
- }
2058
- for (const construction of group.constructions)
2059
- for (const definition of construction.definitions)
2060
- unit.append(plain(definition));
2061
- for (const rendered of group.bodies)
2062
- for (const artifact of rendered.artifacts)
2063
- unit.append(artifact);
2064
- if (isolate)
2065
- unit.append(plain(namespaceClose));
2066
- units.push({
2067
- role: 'module',
2068
- fileName: names.get(file.identity) ?? `${input.unitBaseName}.${file.identity}.cpp`,
2069
- sourceFile: input.sourceFileNames.get(file.identity) ?? null,
2070
- source: render(unit.seal())
2597
+ // A template object is an `inline` function, so every unit whose bodies
2598
+ // may reach one repeats the file's whole set -- the one definition rule
2599
+ // allows exactly that -- and a split never strands a body from its object.
2600
+ const templateObjects = group.bodies.flatMap((rendered) => rendered.templateObjects.map((definition) => plain(definition.text)));
2601
+ // Class members, thunks, constructions, then bodies: the order the file's
2602
+ // one unit had, with its template objects moved ahead of the members they
2603
+ // never name so that every chunk can open with them.
2604
+ const items = [
2605
+ ...group.fieldDefinitions.map((definition) => [plain(definition)]),
2606
+ ...group.bodies.flatMap((rendered) => {
2607
+ const thunk = thunks.get(rendered.body);
2608
+ return thunk ? [[plain(thunk.definition)]] : [];
2609
+ }),
2610
+ ...group.constructions.map((construction) => construction.definitions.map(plain)),
2611
+ ...group.bodies.map((rendered) => rendered.artifacts)
2612
+ ];
2613
+ const fileName = names.get(file.identity) ?? `${input.unitBaseName}.${file.identity}.cpp`;
2614
+ const sourceFile = input.sourceFileNames.get(file.identity) ?? null;
2615
+ chunkCppItems([...unitOpen, ...templateObjects], items, unitClose).forEach((source, index) => {
2616
+ units.push({ role: 'module', fileName: cppChunkFileName(fileName, index), sourceFile, source });
2071
2617
  });
2072
2618
  }
2073
2619
  return {