@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,13 +1,15 @@
1
1
  import { declaredFieldRepresentationOf, declaredRecordFieldOf, nativeBaseFieldOf, recordAccessorBodiesOf, recordAccessorsOfShape, recordFieldsOfShape } from '../../projection/fields.js';
2
2
  export { declaredFieldRepresentationOf, declaredRecordFieldOf, nativeBaseFieldOf, recordAccessorBodiesOf, recordAccessorsOfShape, recordFieldsOfShape };
3
3
  import { lazyArrowFieldPlansForClass } from './class-layout.js';
4
- import { representationKey, walkRepresentation } from '../../representation/model.js';
4
+ import { representationKey, walkRepresentation, ownershipOf } from '../../representation/model.js';
5
+ import { isPrivateNameKey } from '../../semantics/model/structural-types.js';
5
6
  import { dynamicFieldAbsencePolicy } from '../../representation/field-descriptor-policy.js';
6
7
  import { integerStorageSlot } from '../../ir/integer-storage.js';
7
8
  import { recordIndexDomainContainsKey } from '../../ir/native-record-index.js';
8
- import { cppBodyName, cppClassName, cppNarrowedIntegerType, cppRecordFieldKeyIsSymbol, cppRecordFieldAttributesName, cppRecordFieldName, cppRecordAccessorEnvironmentName, cppRecordFieldPresenceName, cppArrayExtensionStructName, cppRecordStructName, cppStringLiteral, cppTypeOf } from './types.js';
9
+ import { cppBodyName, cppClassName, cppNarrowedIntegerType, cppRecordFieldKeyIsSymbol, cppRecordFieldAttributesName, cppRecordFieldName, cppRecordAccessorEnvironmentName, cppRecordFieldPresenceName, cppArrayExtensionStructName, cppRecordStructName, positionalArityText, cppStringLiteral, cppTypeOf, withoutUnitFunctions } from './types.js';
9
10
  import { storedEnvironmentText } from './emit-context.js';
10
- import { boxedText, dynamicCarrierBoxText, dynamicTagFor } from './emit-narrowing.js';
11
+ import { boxedText, dynamicCarrierBoxText, dynamicTagFor, dynamicValueLoadText } from './emit-narrowing.js';
12
+ import { recordLayoutPolicyOf } from '../../projection/fields.js';
11
13
  /**
12
14
  * The physical Optional carrier does not remember whether its empty state is
13
15
  * JavaScript null or undefined. NativeFieldWrite therefore carries the
@@ -41,15 +43,39 @@ const classBaseLinks = (classes) => {
41
43
  const links = new Map();
42
44
  const unlinkable = new Map();
43
45
  for (const layout of classes.values()) {
44
- if (layout.nativeBase !== null) {
46
+ if (layout.nativeBase !== null && layout.nativeBase.instance.kind === 'keyed-collection') {
47
+ // The runtime's own collection object is the base subobject, spelled as
48
+ // the pointee the collection's carrier holds.
49
+ links.set(cppClassName(layout.declaration), {
50
+ structName: cppTypeOf({ ...layout.nativeBase.instance, ownership: 'owned' }),
51
+ shapeId: null,
52
+ native: true,
53
+ hookless: true
54
+ });
55
+ continue;
56
+ }
57
+ // The runtime promise is the base subobject of a class extending the
58
+ // intrinsic `Promise`: the struct IS a `gea::Promise<V>` handle whose
59
+ // shared state every upcast copy observes, plus the class's own fields.
60
+ if (layout.nativeBase !== null && layout.nativeBase.instance.kind === 'promise') {
61
+ links.set(cppClassName(layout.declaration), {
62
+ structName: cppTypeOf(layout.nativeBase.instance),
63
+ shapeId: null,
64
+ native: true,
65
+ hookless: true
66
+ });
67
+ continue;
68
+ }
69
+ const nativeRecord = layout.nativeBase?.instance;
70
+ if (layout.nativeBase !== null && nativeRecord?.kind === 'native-record-ref') {
45
71
  const structName = cppClassName(layout.declaration);
46
- if (layout.nativeBase.instance.native === null) {
72
+ if (nativeRecord.native === null) {
47
73
  unlinkable.set(structName, `its native base ${layout.nativeBase.protocol} published no native C++ layout`);
48
74
  continue;
49
75
  }
50
76
  links.set(structName, {
51
- structName: layout.nativeBase.instance.native,
52
- shapeId: layout.nativeBase.instance.shapeId,
77
+ structName: nativeRecord.native,
78
+ shapeId: nativeRecord.shapeId,
53
79
  native: true
54
80
  });
55
81
  continue;
@@ -174,6 +200,7 @@ const visitRepresentation = (representation, visitStruct) => {
174
200
  visitRepresentation(representation.element, visitStruct);
175
201
  return;
176
202
  case 'iterator':
203
+ case 'async-generator':
177
204
  visitRepresentation(representation.element, visitStruct);
178
205
  visitRepresentation(representation.resume, visitStruct);
179
206
  visitRepresentation(representation.completion, visitStruct);
@@ -260,6 +287,7 @@ export const representationNamesMintedStruct = (representation) => {
260
287
  */
261
288
  const collectRequiredStructs = (representations, deriver, bases, unlinkable, classShapes, classFields) => {
262
289
  const requiredStructs = new Set();
290
+ const shapesByStruct = new Map();
263
291
  const fieldsByStruct = new Map();
264
292
  // Why a struct has no layout, kept per struct name so the refusal can name
265
293
  // the gap instead of only the symptom.
@@ -269,6 +297,13 @@ const collectRequiredStructs = (representations, deriver, bases, unlinkable, cla
269
297
  // and which one is the projection's answer rather than the walk order's.
270
298
  const shapeId = classShapes.get(structName) ?? requestedShapeId;
271
299
  requiredStructs.add(structName);
300
+ const shapes = shapesByStruct.get(structName);
301
+ if (shapes)
302
+ shapes.add(requestedShapeId);
303
+ else
304
+ shapesByStruct.set(structName, new Set([requestedShapeId]));
305
+ if (shapeId !== requestedShapeId)
306
+ shapesByStruct.get(structName).add(shapeId);
272
307
  if (fieldsByStruct.has(structName))
273
308
  return;
274
309
  if (unlayoutable.has(structName))
@@ -319,7 +354,7 @@ const collectRequiredStructs = (representations, deriver, bases, unlinkable, cla
319
354
  unlayoutable.set(structName, own);
320
355
  return;
321
356
  }
322
- fieldsByStruct.set(structName, own);
357
+ fieldsByStruct.set(structName, deriver.isTupleShape(shapeId) ? { ...own, tuple: true } : own);
323
358
  // Every field the shape has, inherited ones included: the carriers they name
324
359
  // still have to be required here, and the base struct's own expansion is not
325
360
  // guaranteed to reach a nested shape this one holds by a different route.
@@ -327,12 +362,12 @@ const collectRequiredStructs = (representations, deriver, bases, unlinkable, cla
327
362
  visitRepresentation(field.value, visitStruct);
328
363
  for (const index of resolved.indexes)
329
364
  visitRepresentation(index.value, visitStruct);
330
- if (base && !base.native)
365
+ if (base && !base.native && base.shapeId !== null)
331
366
  visitStruct(base.structName, base.shapeId, null);
332
367
  };
333
368
  for (const representation of representations)
334
369
  visitRepresentation(representation, visitStruct);
335
- return { requiredStructs, fieldsByStruct, unlayoutable };
370
+ return { requiredStructs, fieldsByStruct, unlayoutable, shapesByStruct };
336
371
  };
337
372
  /**
338
373
  * The half of a derived class's layout that it declares itself, or the reason
@@ -364,6 +399,8 @@ const collectRequiredStructs = (representations, deriver, bases, unlinkable, cla
364
399
  * by name when it cannot.
365
400
  */
366
401
  const ownFieldsOf = (deriver, derived, base, nativeFields) => {
402
+ if (base.shapeId === null)
403
+ return derived;
367
404
  const baseLayout = recordLayoutOfShape(deriver, base.shapeId);
368
405
  if (typeof baseLayout === 'string')
369
406
  return `its base struct ${base.structName} (${base.shapeId}) carries ${baseLayout}`;
@@ -469,6 +506,195 @@ const structValueDependencies = (layout) => {
469
506
  valueHeldStructNames(index.value, into, seen);
470
507
  return into;
471
508
  };
509
+ /**
510
+ * The emitted record structs that are provably LEAVES of the cycle collector:
511
+ * nothing reachable from one through its fields can be a traced edge.
512
+ *
513
+ * A struct is a leaf when every field's carrier is built only from scalars,
514
+ * strings, symbols, absent values, byte buffers, optionals, tagged unions,
515
+ * arrays and string/number dictionaries of such carriers, and other leaf
516
+ * records -- AND the type graph under it has no cycle. An index signature's
517
+ * value carrier counts as a field. Anything not named here
518
+ * is not a leaf: a class (a `Ref` to a base may hold a subclass with more
519
+ * fields, and a class owns method state), a callable, a boxed/dynamic carrier,
520
+ * a promise, a Map/Set (subclassable), a host handle or host record, a borrowed
521
+ * carrier (not an owned edge, so left to the existing answer), an array with an
522
+ * extension sidecar, a recursive-carrier wrapper, an index sidecar of non-leaf values, an accessor
523
+ * (it may carry a captured environment) and a reactive cell (it holds
524
+ * subscribers). A back edge to a struct still being walked is a cycle, so every
525
+ * struct on it fails -- that is what keeps a self-referential record traced.
526
+ *
527
+ * The verdict is only the emitter's claim: `gea_runtime.h`'s `RefTargetIsLeaf`
528
+ * additionally requires the struct's own physical `TraceEdges` to be empty.
529
+ * A native expando is a side-table entry, never a member of the struct and
530
+ * never a traced edge of any type, so dynamic-property capability does not
531
+ * decide leafness.
532
+ */
533
+ const traceLeafStructsOf = (layouts, excluded, celled, classAncestors) => {
534
+ const verdicts = new Map();
535
+ const walking = new Set();
536
+ const structIsLeaf = (structName) => {
537
+ const known = verdicts.get(structName);
538
+ if (known !== undefined)
539
+ return known;
540
+ // A back edge: the struct reaches itself, so it (and what reached it) is a cycle.
541
+ if (walking.has(structName))
542
+ return false;
543
+ const layout = layouts.get(structName);
544
+ const ancestors = classAncestors.get(structName);
545
+ let verdict = false;
546
+ if (layout !== undefined &&
547
+ !excluded.has(structName) &&
548
+ // A class's accessors live on its prototype: the struct stores only a
549
+ // presence bit and an attribute triple for each, never the callable.
550
+ (layout.accessors.length === 0 || ancestors !== undefined) &&
551
+ (celled.get(structName)?.size ?? 0) === 0) {
552
+ walking.add(structName);
553
+ // The inherited storage is this struct's storage too, and the type walk
554
+ // must see it: the physical `TraceEdges` question the runtime asks of a
555
+ // derived struct asks its base, and a base field naming the derived
556
+ // struct back would make that question circular.
557
+ const held = [layout, ...(ancestors ?? []).map((ancestor) => layouts.get(ancestor))];
558
+ verdict =
559
+ (ancestors ?? []).every((ancestor) => (celled.get(ancestor)?.size ?? 0) === 0) &&
560
+ // An index signature's sidecar stores values of ONE carrier, so it is a
561
+ // field like any other for this walk: a numeric or string index of
562
+ // scalars, strings or leaf records (`{ length: number; [i: number]: number }`)
563
+ // adds no edge a cycle could run through.
564
+ held.every((entry) => entry !== undefined &&
565
+ entry.fields.every((field) => carrierIsLeaf(field.value)) &&
566
+ entry.indexes.every((index) => carrierIsLeaf(index.value)));
567
+ walking.delete(structName);
568
+ }
569
+ verdicts.set(structName, verdict);
570
+ return verdict;
571
+ };
572
+ const carrierIsLeaf = (value) => {
573
+ switch (value.kind) {
574
+ case 'void':
575
+ case 'scalar':
576
+ case 'string':
577
+ case 'symbol':
578
+ case 'null':
579
+ case 'undefined':
580
+ return true;
581
+ case 'optional':
582
+ return carrierIsLeaf(value.payload);
583
+ case 'tagged-union':
584
+ return value.arms.every((arm) => carrierIsLeaf(arm.value));
585
+ case 'typed-array':
586
+ case 'array-buffer':
587
+ return value.ownership !== 'borrowed';
588
+ case 'array-object':
589
+ return value.ownership !== 'borrowed' && value.recursive === undefined && value.extension === null && carrierIsLeaf(value.element);
590
+ case 'dictionary':
591
+ return value.ownership !== 'borrowed' && value.recursive === undefined && value.key !== 'symbol' && carrierIsLeaf(value.value);
592
+ case 'promise':
593
+ // The state's value is traced only when the payload is; its reactions are
594
+ // opaque closures the collector never follows, whatever holds the promise.
595
+ return carrierIsLeaf(value.value);
596
+ case 'record':
597
+ return value.ownership !== 'borrowed' && structIsLeaf(cppRecordStructName(value.shapeId));
598
+ case 'native-record-ref':
599
+ return (value.ownership !== 'borrowed' &&
600
+ value.native === null &&
601
+ value.recursive === undefined &&
602
+ structIsLeaf(cppRecordStructName(value.shapeId)));
603
+ case 'class-ref':
604
+ return value.ownership !== 'borrowed' && value.nativeBase === undefined && structIsLeaf(cppClassName(value.declaration));
605
+ default:
606
+ return false;
607
+ }
608
+ };
609
+ const leaves = new Set();
610
+ for (const structName of layouts.keys())
611
+ if (structIsLeaf(structName))
612
+ leaves.add(structName);
613
+ return leaves;
614
+ };
615
+ /**
616
+ * The classes `traceLeafStructsOf` may judge, each with its ancestors: those
617
+ * whose every `Ref` provably names the exact allocated type, and whose
618
+ * per-instance state the collector can do without.
619
+ *
620
+ * A class with a descendant is never one: a `Ref<Base>` may hold a subclass
621
+ * with more fields, so what its own storage reaches says nothing about the
622
+ * object. A class with a native ancestor (`Map`, `Error`, `Promise`...) is not
623
+ * either: that base's storage is the runtime's, not this renderer's layout. A
624
+ * class with lazily materialized arrow fields keeps closures in state the
625
+ * layout does not list.
626
+ *
627
+ * What remains is `gea_method_state`. A root nothing derives from holds it as
628
+ * a static member the collector never follows, so it is eligible as it stands.
629
+ * A hierarchy holds it per instance, an edge the collector WOULD follow into
630
+ * an object that can reach callables and static-field records; it is eligible
631
+ * only when `immortalRoots` says the hierarchy's states do not matter to the
632
+ * collector (see `immortalMethodStateRoots`).
633
+ */
634
+ const leafEligibleClassesOf = (classStructNames, baseStructNames, links, staticMethodStateStructs, immortalRoots, hasHiddenState) => {
635
+ const eligible = new Map();
636
+ for (const structName of classStructNames) {
637
+ if (baseStructNames.has(structName))
638
+ continue;
639
+ const ancestors = [];
640
+ let native = false;
641
+ let root = structName;
642
+ for (let link = links.get(root); link !== undefined; link = links.get(root)) {
643
+ if (link.native || ancestors.includes(link.structName)) {
644
+ native = true;
645
+ break;
646
+ }
647
+ ancestors.push(link.structName);
648
+ root = link.structName;
649
+ }
650
+ if (native || hasHiddenState(structName) || ancestors.some(hasHiddenState))
651
+ continue;
652
+ if (ancestors.length === 0 ? !staticMethodStateStructs.has(structName) : !immortalRoots.has(root))
653
+ continue;
654
+ eligible.set(structName, ancestors);
655
+ }
656
+ return eligible;
657
+ };
658
+ /**
659
+ * The roots of class hierarchies whose per-instance method-state handle the
660
+ * collector need not follow.
661
+ *
662
+ * `gea_method_state` is shared by every instance of one class evaluation, and
663
+ * the instance's handle to it is a traced edge only so that a cycle running
664
+ * THROUGH the state (instance -> state -> a static field or a captured method
665
+ * environment -> instance) is found. A class the program evaluates once
666
+ * (`singleEvaluationClasses`: a module body or static block, outside any loop)
667
+ * has exactly one such state, so skipping the edge can strand at most that one
668
+ * object and what it holds, once per program -- never an allocation per
669
+ * instance. The count on the state then reads as held from outside the
670
+ * traced graph, which retains it, exactly as every untraced owner already
671
+ * does. A hierarchy qualifies when EVERY class in it, the root included, is
672
+ * evaluated once, because its instances write their own evaluation's state
673
+ * into the root's member. A root that itself has a native base is never a
674
+ * candidate.
675
+ */
676
+ const immortalMethodStateRoots = (classStructNames, baseStructNames, links, evaluatedOnce) => {
677
+ const roots = new Set();
678
+ for (const structName of classStructNames) {
679
+ if (links.has(structName) || !baseStructNames.has(structName) || !evaluatedOnce(structName))
680
+ continue;
681
+ roots.add(structName);
682
+ }
683
+ for (const [derived] of links) {
684
+ const walked = new Set([derived]);
685
+ let root = derived;
686
+ for (let link = links.get(root); link !== undefined && !walked.has(link.structName); link = links.get(root)) {
687
+ root = link.structName;
688
+ walked.add(root);
689
+ }
690
+ if (!roots.has(root))
691
+ continue;
692
+ for (const member of walked)
693
+ if (!evaluatedOnce(member) || (links.get(member)?.native ?? false))
694
+ roots.delete(root);
695
+ }
696
+ return roots;
697
+ };
472
698
  /**
473
699
  * Struct names ordered so every struct a definition needs COMPLETE is defined
474
700
  * before it.
@@ -614,6 +840,22 @@ const canonicalDynamicPayloads = new Map([
614
840
  * bits and the branches agreeing about which keys exist, which is the property
615
841
  * everything else in this file depends on.
616
842
  */
843
+ /** Field and accessor keys in the literal's creation order (`RecordAccessor.precedingFields`). */
844
+ const interleavedOwnKeys = (fields, accessors) => {
845
+ const keys = [];
846
+ const placed = (count) => accessors.filter((accessor) => (accessor.precedingFields ?? fields.length) === count);
847
+ for (let index = 0; index <= fields.length; index++) {
848
+ for (const accessor of placed(index))
849
+ keys.push(accessor.key);
850
+ const field = fields[index];
851
+ if (field !== undefined)
852
+ keys.push(field.key);
853
+ }
854
+ for (const accessor of accessors)
855
+ if ((accessor.precedingFields ?? 0) > fields.length)
856
+ keys.push(accessor.key);
857
+ return keys;
858
+ };
617
859
  const renderableAccessors = (layout) => layout.accessors.filter((accessor) => !cppRecordFieldKeyIsSymbol(accessor.key));
618
860
  /**
619
861
  * The boxed spelling of one accessor's value, or `null` when no static tag
@@ -663,7 +905,29 @@ const accessorUnboxText = (accessor, structName, text) => {
663
905
  return null;
664
906
  return `gea::detail::unboxField<${type}>(${text}, gea::Value::Tag::${tag}, ${cppStringLiteral(structName)}, ${cppStringLiteral(accessor.key)})`;
665
907
  };
666
- const dynamicFieldAccessOf = (field, storageType) => {
908
+ const dynamicFieldAccessOf = (field, storageType, isTailField = false) => {
909
+ // A tail field's WRITE is spelled through the lazily-allocating
910
+ // `RecordTail::ensure()` -- sound because `renderFieldDispatcher` reaches
911
+ // `member` only from a `[[Set]]`/`[[DefineOwnProperty]]` body that is about
912
+ // to store into this exact field. Its READ goes through `readMember`
913
+ // instead (`RecordTail::peek()`, `records.ts`'s `tailAwareFieldReadText`):
914
+ // every dispatcher hook is a member of `this`, so the read expression's
915
+ // `prefix` is empty (an implicit `this->`) rather than an explicit
916
+ // receiver text. Both spellings answer the same member name; this is the
917
+ // one place that decides a field is out of line, and every caller below
918
+ // composes whichever of the two the operation it is building actually is.
919
+ const member = (key) => isTailField ? `${cppRecordTailMemberName}.ensure().${cppRecordFieldName(key)}` : cppRecordFieldName(key);
920
+ // Built directly from the already-decided `isTailField`, NOT by asking
921
+ // `tailAwareFieldReadText` to re-derive it from a field list: that function
922
+ // recomputes tail-eligibility from the layout's full field COUNT
923
+ // (`sparseLayoutFieldsOf`'s threshold/fraction gate), and this call site
924
+ // only ever has the one field its own caller already resolved that
925
+ // question for -- a single-field list would always read back "too small
926
+ // to qualify" and silently answer the wrong spelling.
927
+ const readMember = (key) => isTailField
928
+ ? `([&]() { const auto* gea_tail_ptr = ${cppRecordTailMemberName}.peek(); ` +
929
+ `return gea_tail_ptr != nullptr ? gea_tail_ptr->${cppRecordFieldName(key)} : decltype(gea_tail_ptr->${cppRecordFieldName(key)})(); })()`
930
+ : cppRecordFieldName(key);
667
931
  // Whether this field can be reached dynamically is a question about its
668
932
  // VALUE's carrier, not about whether the key that names it is a string or a
669
933
  // symbol -- a `[Symbol.iterator]() {}` method boxes exactly the way a
@@ -684,7 +948,16 @@ const dynamicFieldAccessOf = (field, storageType) => {
684
948
  // handler` over `allMethods` writes nine such fields, and every one of them
685
949
  // aborted the program on the first route registration.
686
950
  if (field.value.kind === 'dynamic' && storageType === 'gea::Value') {
687
- return { key: field.key, member: cppRecordFieldName(field.key), tag: '', type: '', readable: true, writable: true, boxed: true };
951
+ return {
952
+ key: field.key,
953
+ member: member(field.key),
954
+ readMember: readMember(field.key),
955
+ tag: '',
956
+ type: '',
957
+ readable: true,
958
+ writable: true,
959
+ boxed: true
960
+ };
688
961
  }
689
962
  // Optional callable traps and union fields carry their own live tag. An open
690
963
  // dictionary likewise keeps one exact native reference type on both sides of
@@ -695,7 +968,8 @@ const dynamicFieldAccessOf = (field, storageType) => {
695
968
  if (field.value.kind === 'optional' || field.value.kind === 'tagged-union' || field.value.kind === 'dictionary') {
696
969
  return {
697
970
  key: field.key,
698
- member: cppRecordFieldName(field.key),
971
+ member: member(field.key),
972
+ readMember: readMember(field.key),
699
973
  tag: '',
700
974
  type: storageType,
701
975
  readable: true,
@@ -706,7 +980,16 @@ const dynamicFieldAccessOf = (field, storageType) => {
706
980
  }
707
981
  const tag = dynamicTagFor(field.value);
708
982
  if (tag === null) {
709
- return { key: field.key, member: cppRecordFieldName(field.key), tag: '', type: '', readable: false, writable: false, boxed: false };
983
+ return {
984
+ key: field.key,
985
+ member: member(field.key),
986
+ readMember: readMember(field.key),
987
+ tag: '',
988
+ type: '',
989
+ readable: false,
990
+ writable: false,
991
+ boxed: false
992
+ };
710
993
  }
711
994
  // The type the MEMBER is declared with, not the one its representation would
712
995
  // spell: a narrowed `number` member is a `long long`, and boxing one under
@@ -718,7 +1001,8 @@ const dynamicFieldAccessOf = (field, storageType) => {
718
1001
  const readable = canonical === undefined || canonical === type;
719
1002
  return {
720
1003
  key: field.key,
721
- member: cppRecordFieldName(field.key),
1004
+ member: member(field.key),
1005
+ readMember: readMember(field.key),
722
1006
  tag,
723
1007
  type,
724
1008
  readable,
@@ -726,7 +1010,96 @@ const dynamicFieldAccessOf = (field, storageType) => {
726
1010
  boxed: false
727
1011
  };
728
1012
  };
729
- const refuseFieldText = (structName, key) => `gea::detail::refuseUnaddressableField(${cppStringLiteral(structName)}, ${cppStringLiteral(key)});`;
1013
+ /**
1014
+ * How a boxed write lands in a field whose carrier boxes under `Object` -- a
1015
+ * record, a class, an array, a promise -- or `null` when no checked conversion
1016
+ * reaches it.
1017
+ *
1018
+ * That tag is boxed WITH its payload type, so the reverse is the same
1019
+ * `any -> T` conversion every other dynamic read into that carrier takes
1020
+ * (`unboxedLoadText`): a class reference is a checked projection of the
1021
+ * allocation the box retained, a record is its exact payload or a checked
1022
+ * product rebuilt from the object's fields, an array of records rebuilds each
1023
+ * element the same way. The value is stored in the native member, never as a
1024
+ * box. This arm used to refuse every such write at run time, which is what
1025
+ * aborted mongodb's `setOption(mongoOptions: any, ...)` on
1026
+ * `driverInfo: DriverInfo` (`default: {}`) in the MongoClient constructor.
1027
+ *
1028
+ * The three canonical primitive tags keep their exact `unboxField` arm, and a
1029
+ * member whose declared C++ type is not the representation's own spelling has
1030
+ * no conversion to name, so it stays refused. So does a `Function` field: its
1031
+ * load adapts a box to the field's frame through `DynamicCarrier`, which only
1032
+ * exists for frames whose every position has an exact carrier (a `BigInt`
1033
+ * result, an iterator parameter or a recursive alias has none), and that is a
1034
+ * C++ `static_assert`, not a fact this renderer can ask.
1035
+ */
1036
+ const objectFieldWriteLoadText = (layouts, value, access) => {
1037
+ if (layouts === undefined || access.tag !== 'Object' || cppTypeOf(value) !== access.type)
1038
+ return null;
1039
+ if (withoutUnitFunctions(() => dynamicValueLoadText(layouts, value, 'gea_value')) === null)
1040
+ return null;
1041
+ return (text) => dynamicValueLoadText(layouts, value, text);
1042
+ };
1043
+ /**
1044
+ * The checked load into an OPTIONAL object field -- the same product
1045
+ * `objectFieldWriteLoadText` builds for a required one, under the optional's
1046
+ * absence. The optional carrier's generic runtime adapter only accepts the
1047
+ * exact payload type, so a plain object written into an optional record field
1048
+ * (mongodb's `mongoOptions[name] = values[0]` for `driverInfo`, a member laid
1049
+ * out optional because `Object.create(null)` creates it absent) found no
1050
+ * conversion and the write reported a read-only property.
1051
+ */
1052
+ const optionalObjectFieldLoadText = (layouts, value) => {
1053
+ if (value.kind !== 'optional')
1054
+ return null;
1055
+ const payload = value.payload;
1056
+ const access = dynamicFieldAccessOf({ key: '', value: payload, required: true }, cppTypeOf(payload));
1057
+ if (access === null || !access.readable || access.writable || access.boxed || access.dynamicCarrier === true)
1058
+ return null;
1059
+ const load = objectFieldWriteLoadText(layouts, payload, access);
1060
+ if (load === null)
1061
+ return null;
1062
+ return { load, absentTag: value.absence === 'null' ? 'Null' : 'Undefined', type: cppTypeOf(value) };
1063
+ };
1064
+ /**
1065
+ * Whether a boxed write into one of this struct's fields converts into a
1066
+ * struct defined AFTER it. The checked record product builds that struct by
1067
+ * value and a class projection reads its operations table, both of which need
1068
+ * the complete type, and an inline dispatcher body only sees the structs
1069
+ * already defined. Such a struct's dispatcher goes out of line, the way an
1070
+ * accessor's does, rather than reordering: two records naming each other have
1071
+ * no order that completes both.
1072
+ */
1073
+ const writesConvertIntoLaterStruct = (layouts, layout, position, orderOf) => layout.fields.some((field) => {
1074
+ const access = dynamicFieldAccessOf(field, cppTypeOf(field.value));
1075
+ if (access === null || !access.readable || access.boxed)
1076
+ return false;
1077
+ const load = access.dynamicCarrier === true
1078
+ ? (optionalObjectFieldLoadText(layouts, field.value)?.load ?? null)
1079
+ : access.writable
1080
+ ? null
1081
+ : objectFieldWriteLoadText(layouts, field.value, access);
1082
+ if (load === null)
1083
+ return false;
1084
+ return withoutUnitFunctions(() => identifiersIn(load('gea_value')).some((name) => (orderOf.get(name) ?? -1) > position));
1085
+ });
1086
+ const identifiersIn = (text) => {
1087
+ const names = [];
1088
+ let start = -1;
1089
+ for (let at = 0; at <= text.length; at += 1) {
1090
+ const code = at < text.length ? text.charCodeAt(at) : 0;
1091
+ const identifier = (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122) || code === 95;
1092
+ if (identifier && start < 0)
1093
+ start = at;
1094
+ else if (!identifier && start >= 0) {
1095
+ names.push(text.slice(start, at));
1096
+ start = -1;
1097
+ }
1098
+ }
1099
+ return names;
1100
+ };
1101
+ const refuseUnaddressableFieldCall = 'gea::detail::refuseUnaddressableField(';
1102
+ const refuseFieldText = (structName, key) => `${refuseUnaddressableFieldCall}${cppStringLiteral(structName)}, ${cppStringLiteral(key)});`;
730
1103
  /**
731
1104
  * The `gea::detail::WellKnownSymbol` enum member a symbol-keyed record
732
1105
  * field's declaration denotes, or `null` when the field's key names a
@@ -745,7 +1118,7 @@ const refuseFieldText = (structName, key) => `gea::detail::refuseUnaddressableFi
745
1118
  * letter's case -- `gea_runtime.h`'s `enum class WellKnownSymbol` is
746
1119
  * generated to match `SymbolConstructor`'s own member names one for one.
747
1120
  */
748
- const wellKnownSymbolEnumNameOf = (wellKnownSymbols, key) => {
1121
+ export const wellKnownSymbolEnumNameOf = (wellKnownSymbols, key) => {
749
1122
  for (const [declaration, member] of wellKnownSymbols) {
750
1123
  if (key === `sym(${declaration})`)
751
1124
  return member.charAt(0).toUpperCase() + member.slice(1);
@@ -890,7 +1263,119 @@ export const withUnreadParametersUnnamed = (declaration, body) => {
890
1263
  });
891
1264
  return declaration.slice(0, open + 1) + rewritten.join(',') + declaration.slice(close);
892
1265
  };
893
- const renderFieldDispatcher = (structName, layout, base, classDispatch, storageTypeOf, wellKnownSymbols, definitions, dynamicProtocol = true, fieldOperations = undefined, accessorCarriesEnvironment = () => false,
1266
+ /**
1267
+ * The layout a class's reflection hooks answer for: its property-keyed
1268
+ * members, without its private elements.
1269
+ *
1270
+ * Every string-keyed hook below -- own-key enumeration, `[[Get]]`, `[[Set]]`,
1271
+ * descriptors, delete, presence -- is a view of [[OwnPropertyKeys]], and a
1272
+ * private name is not in it (`isPrivateNameKey`). Filtering once here, rather
1273
+ * than in each hook or in each consumer (JSON, Object.keys, for-in, spread),
1274
+ * keeps every hook agreeing on the key set. The struct member itself stays:
1275
+ * `this.#x` reads it directly, never through a hook.
1276
+ */
1277
+ const reflectedClassLayout = (layout) => {
1278
+ if (!layout.fields.some((field) => isPrivateNameKey(field.key)) && !layout.accessors.some((accessor) => isPrivateNameKey(accessor.key)))
1279
+ return layout;
1280
+ const fields = layout.fields.filter((field) => !isPrivateNameKey(field.key));
1281
+ // `precedingFields` counts positions in the unfiltered field list.
1282
+ const keptBefore = (count) => layout.fields.slice(0, count).filter((field) => !isPrivateNameKey(field.key)).length;
1283
+ const accessors = layout.accessors
1284
+ .filter((accessor) => !isPrivateNameKey(accessor.key))
1285
+ .map((accessor) => accessor.precedingFields === undefined ? accessor : { ...accessor, precedingFields: keptBefore(accessor.precedingFields) });
1286
+ return { ...layout, fields, accessors };
1287
+ };
1288
+ /**
1289
+ * The encoded byte length of the key a `gea_name == "..."` branch tests, read
1290
+ * back off the literal `rawCppStringLiteral` spelled: an escape is one byte
1291
+ * (a quote, a backslash, a named one, or an octal `NNN`), anything else its UTF-8
1292
+ * length. `null` when `line` is not such a branch.
1293
+ */
1294
+ const keyByteLengthOfBranch = (line) => {
1295
+ const prefix = 'if (gea_name == "';
1296
+ const text = line.trimStart();
1297
+ if (!text.startsWith(prefix))
1298
+ return null;
1299
+ let bytes = 0;
1300
+ let at = prefix.length;
1301
+ while (at < text.length) {
1302
+ const code = text.codePointAt(at) ?? 0;
1303
+ const character = String.fromCodePoint(code);
1304
+ if (character === '"')
1305
+ return text.startsWith('") ', at) ? bytes : null;
1306
+ if (character === '\\') {
1307
+ const digits = text.slice(at + 1, at + 4);
1308
+ const octal = digits.length === 3 && [...digits].every((digit) => digit >= '0' && digit <= '7');
1309
+ at += octal ? 4 : 2;
1310
+ bytes += 1;
1311
+ continue;
1312
+ }
1313
+ bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
1314
+ at += character.length;
1315
+ }
1316
+ return null;
1317
+ };
1318
+ /**
1319
+ * A run of `if (gea_name == "key") ...` branches, each answering for its own
1320
+ * key and returning or falling through to the next, dispatched by the name's
1321
+ * length first.
1322
+ *
1323
+ * Every field dispatcher is such a chain, and a chain over mongodb's
1324
+ * 134-field options family compared the name against 134 literals on every
1325
+ * dynamic read that reached it -- `string_view` folds the length test, but a
1326
+ * miss still walked all 134 branches and a hit walked to its own. Grouped
1327
+ * under `switch (gea_name.size())` a lookup compares only against the keys of
1328
+ * its own length. The branches keep their relative order inside a case, and
1329
+ * no two keys of different lengths can both match, so the chain's answer is
1330
+ * unchanged; a short chain keeps its shape because the switch costs more than
1331
+ * it skips.
1332
+ */
1333
+ const switchedKeyBranches = 6;
1334
+ const switchedByKeyLength = (body) => {
1335
+ const out = [];
1336
+ let run = [];
1337
+ const flush = () => {
1338
+ if (run.length < switchedKeyBranches) {
1339
+ for (const entry of run)
1340
+ out.push(entry.line);
1341
+ }
1342
+ else {
1343
+ const indent = run[0].line.slice(0, run[0].line.length - run[0].line.trimStart().length);
1344
+ const byLength = new Map();
1345
+ for (const entry of run) {
1346
+ const lines = byLength.get(entry.bytes) ?? [];
1347
+ lines.push(entry.line);
1348
+ byLength.set(entry.bytes, lines);
1349
+ }
1350
+ out.push(`${indent}switch (gea_name.size()) {`);
1351
+ for (const [bytes, lines] of [...byLength.entries()].sort(([a], [b]) => a - b)) {
1352
+ out.push(`${indent}case ${bytes}: {`);
1353
+ for (const line of lines)
1354
+ out.push(line);
1355
+ out.push(`${indent} break;`);
1356
+ out.push(`${indent}}`);
1357
+ }
1358
+ out.push(`${indent}default: break;`);
1359
+ out.push(`${indent}}`);
1360
+ }
1361
+ run = [];
1362
+ };
1363
+ for (const line of body) {
1364
+ const bytes = keyByteLengthOfBranch(line);
1365
+ if (bytes === null) {
1366
+ flush();
1367
+ out.push(line);
1368
+ }
1369
+ else {
1370
+ run.push({ line, bytes });
1371
+ }
1372
+ }
1373
+ flush();
1374
+ return out;
1375
+ };
1376
+ const renderFieldDispatcher = (structName, layout, base, classDispatch, storageTypeOf,
1377
+ /** Which of this layout's fields `renderStructDefinition` placed behind the tail block (`tailFieldsOf`) -- see `dynamicFieldAccessOf`'s `isTailField`. */
1378
+ tailFields = new Set(), wellKnownSymbols, definitions, dynamicProtocol = true, fieldOperations = undefined, accessorCarriesEnvironment = () => false,
894
1379
  /**
895
1380
  * Whether the class is a root nothing derives from. Its protocol members
896
1381
  * then dispatch statically: the only concrete type a handle to it can hold
@@ -905,8 +1390,29 @@ leafRoot = false,
905
1390
  * structural record, which cannot declare one (the design is per-class,
906
1391
  * keyed on the declaring class's identity).
907
1392
  */
908
- lazyArrowFields = undefined) => {
909
- const accesses = layout.fields.map((field) => ({ field, access: dynamicFieldAccessOf(field, storageTypeOf(field)) }));
1393
+ lazyArrowFields = undefined,
1394
+ /**
1395
+ * The protocol members each already-rendered struct declares virtual,
1396
+ * inherited ones included, by struct name. `definitionOrder` renders a base
1397
+ * before anything deriving from it, so a derived struct reads its base's
1398
+ * entry and adds its own.
1399
+ */
1400
+ virtualDeclarations = new Map(),
1401
+ /** The program's record layouts, which name the checked conversion a boxed write into an object-carrying field takes (`objectFieldWriteLoadText`). */
1402
+ layouts = undefined,
1403
+ /** Filled with every field operation a sealed demand names whose arm can only refuse -- see `record` below. */
1404
+ unaddressableDemands = undefined) => {
1405
+ // A write through the property protocol that creates a declared field of a
1406
+ // record creates its key now, after every key already present, the same
1407
+ // fact a static store states (`declaredFieldCreationText`). A class's
1408
+ // fields are created by its constructor, in layout order.
1409
+ const firstFieldStore = (presence, attributes, key) => classDispatch
1410
+ ? `if (!${presence}) ${attributes} = gea::NativeIndexAttributes{};`
1411
+ : `if (!${presence}) { gea::detail::noteNativeDeclaredKeyCreated(this, ${cppStringLiteral(key)}); ${attributes} = gea::NativeIndexAttributes{}; }`;
1412
+ const accesses = layout.fields.map((field) => ({
1413
+ field,
1414
+ access: dynamicFieldAccessOf(field, storageTypeOf(field), tailFields.has(field.key))
1415
+ }));
910
1416
  const symbolKeys = layout.fields.filter((field) => cppRecordFieldKeyIsSymbol(field.key));
911
1417
  const baseRead = base ? [` if (this->${base.structName}::gea_readOwnField(gea_key, gea_out)) return true;`] : [];
912
1418
  const baseWrite = base ? [` if (this->${base.structName}::gea_writeOwnField(gea_key, gea_value, gea_extensible)) return true;`] : [];
@@ -1002,7 +1508,7 @@ lazyArrowFields = undefined) => {
1002
1508
  const declaredBranches = unresolved.map((entry) => {
1003
1509
  const body = bodyOf?.get(entry.field.key);
1004
1510
  const action = body ?? refuseFieldText(structName, `[symbol] ${entry.field.key}`);
1005
- return (` if (gea_key.symbolId() == gea::detail::declaredSymbolId(${cppStringLiteral(entry.field.key)})) { ` +
1511
+ return (` if (gea_key.symbolId() == gea::detail::declaredSymbolId<${cppStringLiteral(entry.field.key)}>()) { ` +
1006
1512
  `const std::string& gea_name = ${cppStringLiteral(entry.field.key)}; (void)gea_name; ${action} }`);
1007
1513
  });
1008
1514
  const fallback = [
@@ -1031,6 +1537,7 @@ lazyArrowFields = undefined) => {
1031
1537
  const sidecarSealed = [];
1032
1538
  const sidecarNativeWrites = new Map();
1033
1539
  const sidecarKeys = [];
1540
+ const sidecarEnumerableStringKeys = [];
1034
1541
  const sidecarPresent = [];
1035
1542
  const sidecarEnumerable = [];
1036
1543
  // Key discovery does not depend on whether the sidecar's VALUE can cross a
@@ -1061,6 +1568,21 @@ lazyArrowFields = undefined) => {
1061
1568
  ? 'gea::PropertyKey::string(gea_entry.first)'
1062
1569
  : 'gea::PropertyKey::string(gea_entry.first)';
1063
1570
  sidecarKeys.push(` for (const auto& gea_entry : ${member}) gea_declared.push_back(${sidecarPropertyKey});`);
1571
+ // The single-pass `Object.keys` answer (`gea_ownEnumerableStringKeys`)
1572
+ // gives up on any key 10.1.11.1 would move ahead of the declared fields:
1573
+ // a numeric sidecar holds only such keys, and a string sidecar's entry is
1574
+ // one when it starts with a digit.
1575
+ if (index.key === 'number')
1576
+ sidecarEnumerableStringKeys.push(` if (${member}.size() != 0) return false;`);
1577
+ if (index.key === 'string')
1578
+ sidecarEnumerableStringKeys.push(` for (const auto& gea_entry : ${member}) { ` +
1579
+ `if (!gea_entry.first.empty() && gea_entry.first[0] >= '0' && gea_entry.first[0] <= '9') return false; ` +
1580
+ `if (${attributes}.attributes(gea_entry.first).enumerable) gea_out.push_back(gea_entry.first); }`);
1581
+ // A new entry is a key created outside the layout, so from here on the
1582
+ // record's keys need a creation order (`gea::detail::NativeOwnKeyOrder`).
1583
+ // Construction writes the sidecar directly, and its keys keep the layout
1584
+ // order a record has before its first key outside the layout.
1585
+ const noteCreated = 'if (!gea_exists) gea::detail::noteNativeIndexKeyCreated(this, gea_key);';
1064
1586
  const sidecarKey = index.key === 'symbol'
1065
1587
  ? 'gea::Symbol(static_cast<std::uint32_t>(gea_key.symbolId()))'
1066
1588
  : index.key === 'number'
@@ -1092,7 +1614,7 @@ lazyArrowFields = undefined) => {
1092
1614
  : `gea_value.tag() == gea::Value::Tag::${sidecarTag} && gea_value.payloadType() == gea::detail::payloadTypeTagFor<${sidecarValueType}>()`;
1093
1615
  sidecarWrite.push(` if (${sidecarGuard}) { const bool gea_exists = ${member}.has(${sidecarKey}); ` +
1094
1616
  `if ((!gea_exists && !gea_extensible) || (gea_exists && !${attributes}.attributes(${sidecarKey}).writable) || !(${sidecarAccepts})) return false; ` +
1095
- `${sidecarWriteValue}; return true; }`);
1617
+ `${sidecarWriteValue}; ${noteCreated} return true; }`);
1096
1618
  const appliedWrite = sidecarDynamicCarrier
1097
1619
  ? `gea::detail::writeDynamicField<${sidecarValueType}>(${member}[${sidecarKey}], gea_applied.value, ${cppStringLiteral(structName)}, ${cppStringLiteral(`[${index.key} index]`)})`
1098
1620
  : `${member}[${sidecarKey}] = gea_applied.value.as<${sidecarValueType}>()`;
@@ -1100,7 +1622,7 @@ lazyArrowFields = undefined) => {
1100
1622
  `if (gea_exists && !gea_ownIndexDescriptor(gea_key, gea_current)) return false; gea::PropertyDescriptor gea_applied; ` +
1101
1623
  `if (!gea::applyNativeIndexDataDescriptor(gea_exists, gea_extensible, gea_current, gea_descriptor, gea_applied)) return false; ` +
1102
1624
  `if (!(${sidecarAccepts.replaceAll('gea_value', 'gea_applied.value')})) return false; ${appliedWrite}; ` +
1103
- `${attributes}.set(${sidecarKey}, gea::NativeIndexAttributes{gea_applied.writable, gea_applied.enumerable, gea_applied.configurable}); return true; }`);
1625
+ `${attributes}.set(${sidecarKey}, gea::NativeIndexAttributes{gea_applied.writable, gea_applied.enumerable, gea_applied.configurable}); ${noteCreated} return true; }`);
1104
1626
  }
1105
1627
  else {
1106
1628
  sidecarWrite.push(` if (${sidecarGuard}) ${refuseFieldText(structName, `[${index.key} index]`)}`);
@@ -1126,7 +1648,7 @@ lazyArrowFields = undefined) => {
1126
1648
  if (index.value.kind !== 'dynamic' || dynamicProtocol)
1127
1649
  nativeWrites.push(` if (${sidecarGuard}) { ${fixedNativeWrite} const bool gea_exists = ${member}.has(${sidecarKey}); ` +
1128
1650
  `if ((!gea_exists && !gea_extensible) || (gea_exists && !${attributes}.attributes(${sidecarKey}).writable)) return false; ` +
1129
- `${member}[${sidecarKey}] = gea_value; return true; }`);
1651
+ `${member}[${sidecarKey}] = gea_value; ${noteCreated} return true; }`);
1130
1652
  sidecarNativeWrites.set(sidecarValueType, nativeWrites);
1131
1653
  }
1132
1654
  const reads = [];
@@ -1201,8 +1723,8 @@ lazyArrowFields = undefined) => {
1201
1723
  // distinct from the ordinary boxed `gea_readOwnField` below) reads
1202
1724
  // `access.member` just as directly, so it gets the same guard.
1203
1725
  const nativeRead = lazyPlan !== undefined
1204
- ? ` if (gea_name == ${literal}) { if (!${presence}) return false; ${materializeText(lazyPlan, access.member)}; return gea_out.assign(${access.member}); }`
1205
- : ` if (gea_name == ${literal}) return ${presence} && gea_out.assign(${access.member});`;
1726
+ ? ` if (gea_name == ${literal}) { if (!${presence}) return false; ${materializeText(lazyPlan, access.member)}; return gea_out.assign(${access.readMember}); }`
1727
+ : ` if (gea_name == ${literal}) return ${presence} && gea_out.assign(${access.readMember});`;
1206
1728
  if (fieldOperations === undefined ||
1207
1729
  fieldOperations.get(field.key)?.has('read') ||
1208
1730
  fieldOperations.get(field.key)?.has('native-read')) {
@@ -1214,7 +1736,7 @@ lazyArrowFields = undefined) => {
1214
1736
  fieldOperations.get(field.key)?.has('write') ||
1215
1737
  fieldOperations.get(field.key)?.has('native-write')) {
1216
1738
  const nativeWrite = ` if (gea_name == ${literal}) { if (${presence} ? !${attributes}.writable : !gea_extensible) return false; ` +
1217
- `if (!gea_value.assign${nativeFieldPolicyTemplate(field.value)}(${access.member})) return false; if (!${presence}) ${attributes} = gea::NativeIndexAttributes{}; ${presence} = true; return true; }`;
1739
+ `if (!gea_value.assign${nativeFieldPolicyTemplate(field.value)}(${access.member})) return false; ${firstFieldStore(presence, attributes, field.key)} ${presence} = true; return true; }`;
1218
1740
  nativeFieldWrites.push(nativeWrite);
1219
1741
  nativeFieldWritesByKey.set(field.key, nativeWrite);
1220
1742
  }
@@ -1234,6 +1756,11 @@ lazyArrowFields = undefined) => {
1234
1756
  const operation = byKey === readsByKey ? 'read' : byKey === writesByKey ? 'write' : byKey === descriptorsByKey ? 'descriptor' : 'define';
1235
1757
  if (fieldOperations !== undefined && !fieldOperations.get(field.key)?.has(operation))
1236
1758
  return;
1759
+ // A sealed demand names this field for this operation because the
1760
+ // program performs it, so an arm that can only refuse is an abort the
1761
+ // program provably reaches: refused here, by name, not at run time.
1762
+ if (fieldOperations !== undefined && statement.includes(refuseUnaddressableFieldCall))
1763
+ unaddressableDemands?.push(`${field.key} (${operation})`);
1237
1764
  into.push(statement);
1238
1765
  byKey.set(field.key, statement);
1239
1766
  // `descriptorsByKey` keeps the per-field body regardless: the symbol
@@ -1257,8 +1784,8 @@ lazyArrowFields = undefined) => {
1257
1784
  continue;
1258
1785
  }
1259
1786
  if (access.dynamicCarrier) {
1260
- const boxed = dynamicCarrierBoxText(field.value, access.member) ??
1261
- `gea::detail::readDynamicField(${access.member}, ${cppStringLiteral(structName)}, ${literal})`;
1787
+ const boxed = dynamicCarrierBoxText(field.value, access.readMember) ??
1788
+ `gea::detail::readDynamicField(${access.readMember}, ${cppStringLiteral(structName)}, ${literal})`;
1262
1789
  // An optional or union carrier boxes through a CONDITIONAL over its live
1263
1790
  // arms -- one `gea::Value` construction per arm, so a `Texture | null |
1264
1791
  // undefined` field spends three and an optional `number` spends two.
@@ -1274,13 +1801,23 @@ lazyArrowFields = undefined) => {
1274
1801
  const groupKey = `carrier|${representationKey(field.value)}`;
1275
1802
  const group = readGroups.get(groupKey) ?? { type: access.type, box: groupedBox, keys: [], branches: [] };
1276
1803
  group.keys.push(field.key);
1277
- group.branches.push(` if (gea_name == ${literal}) { if (!${presence}) return false; gea_slot = ${access.member}; }`);
1804
+ group.branches.push(` if (gea_name == ${literal}) { if (!${presence}) return false; gea_slot = ${access.readMember}; }`);
1278
1805
  readGroups.set(groupKey, group);
1279
1806
  }
1280
1807
  record(reads, readsByKey, ` if (gea_name == ${literal}) { if (!${presence}) return false; gea_out = ${boxed}; return true; }`);
1281
- record(writes, writesByKey, ` if (gea_name == ${literal}) { if (${presence} ? !${attributes}.writable : !gea_extensible) return false; ` +
1282
- `gea::detail::writeDynamicField(${access.member}, gea_value, ${cppStringLiteral(structName)}, ${literal}); if (!${presence}) ${attributes} = gea::NativeIndexAttributes{}; ${presence} = true; return true; }`);
1283
1808
  record(descriptors, descriptorsByKey, descriptorText(boxed));
1809
+ if (fieldOperations !== undefined && !fieldOperations.get(field.key)?.has('write') && !fieldOperations.get(field.key)?.has('define'))
1810
+ continue;
1811
+ const optionalLoad = optionalObjectFieldLoadText(layouts, field.value);
1812
+ if (optionalLoad !== null) {
1813
+ const store = (text) => `${access.member} = (${text}).tag() == gea::Value::Tag::${optionalLoad.absentTag} ? ${optionalLoad.type}{} : ${optionalLoad.type}{${optionalLoad.load(text)}}`;
1814
+ record(writes, writesByKey, ` if (gea_name == ${literal}) { if (${presence} ? !${attributes}.writable : !gea_extensible) return false; ` +
1815
+ `${store('gea_value')}; ${firstFieldStore(presence, attributes, field.key)} ${presence} = true; return true; }`);
1816
+ record(defines, definesByKey, defineText(boxed, 'true', store('gea_applied.value')));
1817
+ continue;
1818
+ }
1819
+ record(writes, writesByKey, ` if (gea_name == ${literal}) { if (${presence} ? !${attributes}.writable : !gea_extensible) return false; ` +
1820
+ `gea::detail::writeDynamicField(${access.member}, gea_value, ${cppStringLiteral(structName)}, ${literal}); ${firstFieldStore(presence, attributes, field.key)} ${presence} = true; return true; }`);
1284
1821
  const absencePolicy = dynamicFieldAbsencePolicy(field.value);
1285
1822
  record(defines, definesByKey, absencePolicy === null
1286
1823
  ? defineText(boxed, `gea::detail::dynamicFieldAccepts<${access.type}>(gea_value)`, `gea::detail::writeDynamicField(${access.member}, gea_applied.value, ${cppStringLiteral(structName)}, ${literal})`)
@@ -1289,10 +1826,10 @@ lazyArrowFields = undefined) => {
1289
1826
  continue;
1290
1827
  }
1291
1828
  if (access.boxed) {
1292
- record(reads, readsByKey, ` if (gea_name == ${literal}) { if (!${presence}) return false; gea_out = ${access.member}; return true; }`);
1293
- record(writes, writesByKey, ` if (gea_name == ${literal}) { if (${presence} ? !${attributes}.writable : !gea_extensible) return false; ${access.member} = gea_value; if (!${presence}) ${attributes} = gea::NativeIndexAttributes{}; ${presence} = true; return true; }`);
1294
- record(descriptors, descriptorsByKey, descriptorText(access.member));
1295
- record(defines, definesByKey, defineText(access.member, 'true', `${access.member} = gea_applied.value`));
1829
+ record(reads, readsByKey, ` if (gea_name == ${literal}) { if (!${presence}) return false; gea_out = ${access.readMember}; return true; }`);
1830
+ record(writes, writesByKey, ` if (gea_name == ${literal}) { if (${presence} ? !${attributes}.writable : !gea_extensible) return false; ${access.member} = gea_value; ${firstFieldStore(presence, attributes, field.key)} ${presence} = true; return true; }`);
1831
+ record(descriptors, descriptorsByKey, descriptorText(access.readMember));
1832
+ record(defines, definesByKey, defineText(access.readMember, 'true', `${access.member} = gea_applied.value`));
1296
1833
  continue;
1297
1834
  }
1298
1835
  // This dispatcher is the SAME `gea_readOwnField` the design's "dynamic
@@ -1305,9 +1842,9 @@ lazyArrowFields = undefined) => {
1305
1842
  // `this` handle inside one of these `const` dispatch methods.
1306
1843
  const boxed = access.tag === 'Function'
1307
1844
  ? lazyPlan !== undefined
1308
- ? `(${materializeText(lazyPlan, access.member)}, ${boxedText(field.value, access.tag, access.member)})`
1309
- : boxedText(field.value, access.tag, access.member)
1310
- : `gea::Value::box(gea::Value::Tag::${access.tag}, static_cast<${access.type}>(${access.member}))`;
1845
+ ? `(${materializeText(lazyPlan, access.member)}, ${boxedText(field.value, access.tag, access.readMember)})`
1846
+ : boxedText(field.value, access.tag, access.readMember)
1847
+ : `gea::Value::box(gea::Value::Tag::${access.tag}, static_cast<${access.type}>(${access.readMember}))`;
1311
1848
  // A `Function` tag boxes through `boxedText`, whose recipe is not a tag and
1312
1849
  // a cast but a choice among three `gea::Value` constructors made from the
1313
1850
  // field's own REPRESENTATION -- a method thunk, a rest-aware callable, or
@@ -1329,14 +1866,16 @@ lazyArrowFields = undefined) => {
1329
1866
  branches: []
1330
1867
  };
1331
1868
  group.keys.push(field.key);
1332
- group.branches.push(` if (gea_name == ${literal}) { if (!${presence}) return false; gea_slot = static_cast<${slotType}>(${access.member}); }`);
1869
+ group.branches.push(` if (gea_name == ${literal}) { if (!${presence}) return false; gea_slot = static_cast<${slotType}>(${access.readMember}); }`);
1333
1870
  readGroups.set(groupKey, group);
1334
1871
  }
1335
1872
  record(reads, readsByKey, ` if (gea_name == ${literal}) { if (!${presence}) return false; gea_out = ${boxed}; return true; }`);
1336
1873
  record(descriptors, descriptorsByKey, descriptorText(boxed));
1874
+ if (fieldOperations !== undefined && !fieldOperations.get(field.key)?.has('write') && !fieldOperations.get(field.key)?.has('define'))
1875
+ continue;
1337
1876
  if (access.writable) {
1338
1877
  record(writes, writesByKey, ` if (gea_name == ${literal}) { if (${presence} ? !${attributes}.writable : !gea_extensible) return false; ` +
1339
- `${access.member} = gea::detail::unboxField<${access.type}>(gea_value, gea::Value::Tag::${access.tag}, ${cppStringLiteral(structName)}, ${literal}); if (!${presence}) ${attributes} = gea::NativeIndexAttributes{}; ${presence} = true; return true; }`);
1878
+ `${access.member} = gea::detail::unboxField<${access.type}>(gea_value, gea::Value::Tag::${access.tag}, ${cppStringLiteral(structName)}, ${literal}); ${firstFieldStore(presence, attributes, field.key)} ${presence} = true; return true; }`);
1340
1879
  // `applyNativeFieldDescriptor` reads the CURRENT value through this
1341
1880
  // same `access.member` reference when the field is present,
1342
1881
  // non-configurable and non-writable (a SameValue check against the
@@ -1351,8 +1890,17 @@ lazyArrowFields = undefined) => {
1351
1890
  `${access.member}, ${attributes}, ${presence}, gea_descriptor, gea_extensible, gea::Value::Tag::${access.tag});`);
1352
1891
  }
1353
1892
  else {
1354
- record(writes, writesByKey, ` if (gea_name == ${literal}) ${refuseFieldText(structName, access.key)}`);
1355
- record(defines, definesByKey, ` if (gea_name == ${literal}) ${refuseFieldText(structName, access.key)}`);
1893
+ const load = objectFieldWriteLoadText(layouts, field.value, access);
1894
+ if (load === null) {
1895
+ record(writes, writesByKey, ` if (gea_name == ${literal}) ${refuseFieldText(structName, access.key)}`);
1896
+ record(defines, definesByKey, ` if (gea_name == ${literal}) ${refuseFieldText(structName, access.key)}`);
1897
+ }
1898
+ else {
1899
+ record(writes, writesByKey, ` if (gea_name == ${literal}) { if (${presence} ? !${attributes}.writable : !gea_extensible) return false; ` +
1900
+ `${access.member} = ${load('gea_value')}; ${firstFieldStore(presence, attributes, field.key)} ${presence} = true; return true; }`);
1901
+ record(defines, definesByKey, ` if (gea_name == ${literal}) return gea::applyNativeFieldDescriptorLoaded(` +
1902
+ `${access.member}, ${attributes}, ${presence}, gea_descriptor, gea_extensible, [&](const gea::Value& gea_value) { return ${load('gea_value')}; });`);
1903
+ }
1356
1904
  }
1357
1905
  }
1358
1906
  // An accessor is an own property with NO storage, so the boxed protocol has
@@ -1445,14 +1993,21 @@ lazyArrowFields = undefined) => {
1445
1993
  // those fields. Symbol fields are excluded because this hook supplies the
1446
1994
  // string-key list consumed by Object.keys/for-in; their runtime identity is
1447
1995
  // not a string the dispatcher can reconstruct.
1448
- // Accessor keys follow the fields rather than interleaving with them. The two
1449
- // lists come from one `shape.members` walk and each keeps its order, but the
1450
- // split does not record where one sat relative to the other, so a literal
1451
- // mixing `get g()` with `plain` enumerates `plain,g` where the engine says
1452
- // `g,plain`. That is a narrower divergence than the one it replaces -- an
1453
- // accessor used to be absent from `Object.keys` entirely -- and closing it
1454
- // means carrying a member ordinal, not reordering here.
1455
- const ownKeys = [...layout.fields.map((field) => field.key), ...accessors.map((accessor) => accessor.key)];
1996
+ // The two lists come from one `shape.members` walk and each keeps its
1997
+ // order; `precedingFields` records where each accessor sat among the fields,
1998
+ // so a literal mixing `get g()` with `plain` enumerates in the order it
1999
+ // created them. An accessor stating no place (none a class layout renders
2000
+ // here) follows every field.
2001
+ const ownKeys = interleavedOwnKeys(layout.fields, accessors);
2002
+ const stringKeys = ownKeys.filter((key) => !cppRecordFieldKeyIsSymbol(key));
2003
+ const enumerableStringKeysBody = (base && base.native) || stringKeys.some(isArrayIndexKey)
2004
+ ? [' return false;']
2005
+ : [
2006
+ ...(base ? [` if (!this->${base.structName}::gea_ownEnumerableStringKeys(gea_out)) return false;`] : []),
2007
+ ...stringKeys.map((key) => ` if (${cppRecordFieldPresenceName(key)} && ${cppRecordFieldAttributesName(key)}.enumerable) gea_out.push_back(${cppStringLiteral(key)});`),
2008
+ ...sidecarEnumerableStringKeys,
2009
+ ' return true;'
2010
+ ];
1456
2011
  const keys = ownKeys.flatMap((key) => {
1457
2012
  if (!cppRecordFieldKeyIsSymbol(key))
1458
2013
  return [` if (${cppRecordFieldPresenceName(key)}) gea_declared.push_back(gea::PropertyKey::string(${cppStringLiteral(key)}));`];
@@ -1464,17 +2019,20 @@ lazyArrowFields = undefined) => {
1464
2019
  ];
1465
2020
  });
1466
2021
  const matches = ownKeys.map((key) => ` if (gea_name == ${cppStringLiteral(key)}) return true;`);
1467
- const matchesByKey = new Map(layout.fields.map((field, index) => [field.key, matches[index]]));
2022
+ const matchesByKey = new Map(layout.fields.map((field) => [field.key, matches[ownKeys.indexOf(field.key)]]));
1468
2023
  const presentFields = ownKeys.map((key) => ` if (gea_name == ${cppStringLiteral(key)}) { gea_out = ${cppRecordFieldPresenceName(key)}; return true; }`);
1469
2024
  const enumerableFields = ownKeys.map((key) => ` if (gea_name == ${cppStringLiteral(key)}) { gea_out = ${cppRecordFieldPresenceName(key)} && ${cppRecordFieldAttributesName(key)}.enumerable; return true; }`);
1470
- const presentByKey = new Map(layout.fields.map((field, index) => [field.key, presentFields[index]]));
1471
- const enumerableByKey = new Map(layout.fields.map((field, index) => [field.key, enumerableFields[index]]));
2025
+ const presentByKey = new Map(layout.fields.map((field) => [field.key, presentFields[ownKeys.indexOf(field.key)]]));
2026
+ const enumerableByKey = new Map(layout.fields.map((field) => [field.key, enumerableFields[ownKeys.indexOf(field.key)]]));
1472
2027
  const deletes = ownKeys.map((key) => {
1473
2028
  const presence = cppRecordFieldPresenceName(key);
1474
2029
  const attributes = cppRecordFieldAttributesName(key);
1475
- return ` if (gea_name == ${cppStringLiteral(key)}) { if (!${presence}) return true; if (!${attributes}.configurable) return false; ${presence} = false; return true; }`;
2030
+ // A struct with a tail destroys its owning fields by presence bit (`renderManualDestruction`), so the value goes with the bit.
2031
+ const owning = tailFields.size > 0 && layout.fields.some((field) => field.key === key && optionalOwnsResources(field));
2032
+ const reset = owning ? ` gea_resetOwnField(${cppStringLiteral(key)});` : '';
2033
+ return ` if (gea_name == ${cppStringLiteral(key)}) { if (!${presence}) return true; if (!${attributes}.configurable) return false; ${presence} = false;${reset} return true; }`;
1476
2034
  });
1477
- const deletesByKey = new Map(layout.fields.map((field, index) => [field.key, deletes[index]]));
2035
+ const deletesByKey = new Map(layout.fields.map((field) => [field.key, deletes[ownKeys.indexOf(field.key)]]));
1478
2036
  // The one place `symbolBranchFor` (above) reads a matched field's
1479
2037
  // already-rendered body from, by hook signature -- so the symbol path and
1480
2038
  // the string path share one statement per field per hook, never two.
@@ -1511,9 +2069,36 @@ lazyArrowFields = undefined) => {
1511
2069
  const attributes = cppRecordFieldAttributesName(key);
1512
2070
  return ` if (${presence} && ${attributes}.configurable) return false;`;
1513
2071
  });
2072
+ // The per-field statements above stay the authority `symbolBranchFor` reads
2073
+ // one field's body from. The string-keyed chains are instead answered from
2074
+ // one table per struct: presence, enumerability, the key predicate,
2075
+ // deletion and the integrity levels are the same statement for every field,
2076
+ // so the runtime states each once over `gea_eachOwnField` (gea_runtime.h's
2077
+ // `nativeOwnFieldPresent` and siblings) where each hook spelled one line per
2078
+ // field -- eight lines per field of every struct, 7 MB of the MongoDB
2079
+ // driver's unit.
2080
+ // Stated for a struct with NO declared field too: the runtime's
2081
+ // `noteNativeIndexKeyCreated` walks the table of any record whose index
2082
+ // sidecar takes a key, and a `{ [key: string]: T }` record has a sidecar
2083
+ // and nothing else -- `dynamic-iterator-header-close.ts` failed to compile
2084
+ // on exactly that struct when the table was left out.
2085
+ const ownFieldTable = ownKeys.length === 0
2086
+ ? [' template <typename Self, typename F> static bool gea_eachOwnField(Self&, F&&) { return false; }']
2087
+ : [
2088
+ ' template <typename Self, typename F> static bool gea_eachOwnField(Self& self, F&& visit) {',
2089
+ ` return ${ownKeys
2090
+ .map((key) => `visit(${cppStringLiteral(key)}, self.${cppRecordFieldPresenceName(key)}, self.${cppRecordFieldAttributesName(key)})`)
2091
+ .join('\n || ')};`,
2092
+ ' }'
2093
+ ];
2094
+ const viaTable = (fields, statement) => (fields.length === 0 ? [] : [` ${statement}`]);
1514
2095
  // A struct with no addressable field of its own never reads `gea_name`, and
1515
2096
  // an unused reference is a warning in every build that enables one.
1516
- const nameOf = (body) => body.length > 0 ? [' const std::string& gea_name = gea_key.text();'] : [];
2097
+ const nameOf = (body) =>
2098
+ // A `string_view`, so each `gea_name == "literal"` below compares lengths
2099
+ // (the literal's is folded at compile time) before it touches memory: a
2100
+ // 134-field options record answered a miss with 134 `strlen`+`memcmp`s.
2101
+ body.length > 0 ? [' const std::string_view gea_name = gea_key.text();'] : [];
1517
2102
  const accessorDescriptors = descriptors.slice(dataDescriptorCount);
1518
2103
  const accessorReads = reads.slice(dataReadCount);
1519
2104
  // A group of ONE is not a group: its block spends a slot declaration and a
@@ -1550,10 +2135,25 @@ lazyArrowFields = undefined) => {
1550
2135
  // `Ref<Base>` must therefore enter the most-derived field table before that
1551
2136
  // table explicitly walks its bases. Records have no subtype identity and keep
1552
2137
  // these hooks non-virtual, preserving their plain aggregate layout.
1553
- const classMember = (stated, body) => {
2138
+ //
2139
+ // Not every member is stated by every struct in a hierarchy: an index
2140
+ // sidecar's `gea_writeOwnIndexNative` is one overload per sidecar value type,
2141
+ // and a base with no sidecar states none. So `override` is decided per
2142
+ // member against what the base chain actually declared; a member the chain
2143
+ // never declared is introduced here, `virtual` like a root's.
2144
+ const inheritedVirtuals = base !== undefined && !base.native ? virtualDeclarations.get(base.structName) : undefined;
2145
+ const ownVirtuals = new Set(inheritedVirtuals);
2146
+ if (classDispatch)
2147
+ virtualDeclarations.set(structName, ownVirtuals);
2148
+ const classMember = (stated, statedBody) => {
2149
+ const body = switchedByKeyLength(statedBody);
1554
2150
  const declaration = withUnreadParametersUnnamed(stated, body);
1555
- const prefix = classDispatch && !leafRoot && (base === undefined || base.native) ? 'virtual ' : '';
1556
- const suffix = classDispatch && base !== undefined && !base.native ? ' override' : '';
2151
+ const overrides = classDispatch && inheritedVirtuals !== undefined && inheritedVirtuals.has(stated);
2152
+ const introduces = classDispatch && !leafRoot && !overrides;
2153
+ if (overrides || introduces)
2154
+ ownVirtuals.add(stated);
2155
+ const prefix = introduces ? 'virtual ' : '';
2156
+ const suffix = overrides ? ' override' : '';
1557
2157
  const signature = ` ${prefix}${declaration}${suffix}`;
1558
2158
  if (definitions === undefined)
1559
2159
  return [`${signature} {`, ...body, ' }'];
@@ -1589,18 +2189,19 @@ lazyArrowFields = undefined) => {
1589
2189
  ...classMember(`bool gea_writeOwnIndexNative(const gea::PropertyKey& gea_key, const ${valueType}& gea_value, bool gea_extensible = true)`, [...writes, ' return false;'])
1590
2190
  ]);
1591
2191
  return [
1592
- " /** This struct's declared fields, as a boxed `gea::Value` reads them. `false` means the struct does not declare the key, which sends it to the box's expando table. */",
2192
+ ...ownFieldTable,
2193
+ // This struct's declared fields, as a boxed `gea::Value` reads them. `false` means the struct does not declare the key, which sends it to the box's expando table.
1593
2194
  ...classMember('bool gea_ownFieldPresent(const gea::PropertyKey& gea_key, bool& gea_out) const', [
1594
2195
  ...symbolBranchFor('gea_ownFieldPresent(gea_key, gea_out)', true),
1595
2196
  ...nameOf(presentFields),
1596
- ...presentFields,
2197
+ ...viaTable(presentFields, 'if (gea::detail::nativeOwnFieldPresent(*this, gea_name, gea_out)) return true;'),
1597
2198
  ...(base && !base.native ? [` if (this->${base.structName}::gea_ownFieldPresent(gea_key, gea_out)) return true;`] : []),
1598
2199
  ' return false;'
1599
2200
  ]),
1600
2201
  ...classMember('bool gea_ownFieldEnumerable(const gea::PropertyKey& gea_key, bool& gea_out) const', [
1601
2202
  ...symbolBranchFor('gea_ownFieldEnumerable(gea_key, gea_out)', true),
1602
2203
  ...nameOf(enumerableFields),
1603
- ...enumerableFields,
2204
+ ...viaTable(enumerableFields, 'if (gea::detail::nativeOwnFieldEnumerable(*this, gea_name, gea_out)) return true;'),
1604
2205
  ...(base && !base.native ? [` if (this->${base.structName}::gea_ownFieldEnumerable(gea_key, gea_out)) return true;`] : []),
1605
2206
  ' return false;'
1606
2207
  ]),
@@ -1641,7 +2242,7 @@ lazyArrowFields = undefined) => {
1641
2242
  ? [` return this->${base.structName}::gea_writeOwnFieldNative(gea_key, gea_value, gea_extensible);`]
1642
2243
  : [' return false;'])
1643
2244
  ]),
1644
- ' /** The complete data descriptor for one present fixed field. */',
2245
+ // The complete data descriptor for one present fixed field.
1645
2246
  ...dynamicMember('bool gea_ownFieldDescriptor(const gea::PropertyKey& gea_key, gea::PropertyDescriptor& gea_out) const', [
1646
2247
  // Descriptor hooks belong to generated bases, just like the text-key chain
1647
2248
  // below. A native base's field reader is not a descriptor hook.
@@ -1676,7 +2277,7 @@ lazyArrowFields = undefined) => {
1676
2277
  ...(base && !base.native ? [` if (this->${base.structName}::gea_ownFieldDescriptor(gea_key, gea_out)) return true;`] : []),
1677
2278
  ' return false;'
1678
2279
  ]),
1679
- ' /** The same, for a write. A declared field is written IN PLACE, so every native read of it sees the change. */',
2280
+ // The same, for a write. A declared field is written IN PLACE, so every native read of it sees the change.
1680
2281
  ...dynamicMember('bool gea_writeOwnField(const gea::PropertyKey& gea_key, const gea::Value& gea_value, bool gea_extensible = true)', [
1681
2282
  ...symbolBranchFor('gea_writeOwnField(gea_key, gea_value, gea_extensible)'),
1682
2283
  ...nameOf(writes),
@@ -1684,7 +2285,7 @@ lazyArrowFields = undefined) => {
1684
2285
  ...baseWrite,
1685
2286
  ' return false;'
1686
2287
  ]),
1687
- ' /** ValidateAndApplyPropertyDescriptor for a fixed native data property. */',
2288
+ // ValidateAndApplyPropertyDescriptor for a fixed native data property.
1688
2289
  ...nativeIndexMember('bool gea_defineOwnField(const gea::PropertyKey& gea_key, const gea::PropertyDescriptor& gea_descriptor, bool gea_extensible = true)', [
1689
2290
  ...symbolBranchFor('gea_defineOwnField(gea_key, gea_descriptor, gea_extensible)', true),
1690
2291
  ...nameOf(defines),
@@ -1697,104 +2298,125 @@ lazyArrowFields = undefined) => {
1697
2298
  : []),
1698
2299
  ' return false;'
1699
2300
  ]),
1700
- ' /** A field may be declared by the native layout but currently absent after delete. */',
2301
+ // A field may be declared by the native layout but currently absent after delete.
1701
2302
  ...nativeIndexMember('bool gea_matchesOwnField(const gea::PropertyKey& gea_key) const', [
1702
2303
  ...symbolBranchFor('gea_matchesOwnField(gea_key)', true),
1703
2304
  ...nameOf(matches),
1704
- ...matches,
2305
+ ...viaTable(matches, 'if (gea::detail::nativeOwnFieldMatches(*this, gea_name)) return true;'),
1705
2306
  ...baseMatches,
1706
2307
  ' return false;'
1707
2308
  ]),
1708
- ' /** OrdinaryDelete for one declared data property; false preserves a non-configurable field. */',
2309
+ // A native base answers `gea_readOwnField` for names the predicate above
2310
+ // never reports, so the predicate is not this type's whole read domain. The
2311
+ // runtime's literal-read miss cache takes "not declared" as "reads only the
2312
+ // expando" and must not do so here -- nor for anything deriving from this,
2313
+ // which inherits the marker by name lookup.
2314
+ ...(base?.native ? [' static constexpr bool gea_ownFieldNamesIncomplete = true;'] : []),
2315
+ // OrdinaryDelete for one declared data property; false preserves a non-configurable field.
1709
2316
  ...nativeIndexMember('bool gea_deleteOwnField(const gea::PropertyKey& gea_key)', [
1710
2317
  ...symbolBranchFor('gea_deleteOwnField(gea_key)', true),
1711
2318
  ...nameOf(deletes),
1712
- ...deletes,
2319
+ ...viaTable(deletes, 'if (const std::optional<bool> gea_deleted = gea::detail::nativeDeleteOwnField(*this, gea_name)) return *gea_deleted;'),
1713
2320
  ...baseDelete,
1714
2321
  ' return false;'
1715
2322
  ]),
1716
- " /** SetIntegrityLevel(frozen) changes descriptors, never the fixed fields' native carriers. */",
1717
- ...classMember('void gea_freezeOwnFields()', [...baseFreezeFields, ...freezeFields]),
1718
- ' /** SetIntegrityLevel(sealed) retains writability while making present fields non-configurable. */',
1719
- ...classMember('void gea_sealOwnFields()', [...baseSealFields, ...sealFields]),
1720
- ' /** TestIntegrityLevel(frozen) over present fixed data properties. */',
1721
- ...classMember('bool gea_ownFieldsFrozen() const', [...baseFrozenFields, ...frozenFields, ' return true;']),
1722
- ' /** TestIntegrityLevel(sealed) over present fixed data properties. */',
1723
- ...classMember('bool gea_ownFieldsSealed() const', [...baseSealedFields, ...sealedFields, ' return true;']),
1724
- " /** A present entry of this record's index-signature sidecar. It is deliberately separate from fixed C++ fields: the former is configurable, the latter is not. */",
2323
+ // SetIntegrityLevel(frozen) changes descriptors, never the fixed fields' native carriers.
2324
+ ...classMember('void gea_freezeOwnFields()', [
2325
+ ...baseFreezeFields,
2326
+ ...viaTable(freezeFields, 'gea::detail::nativeFreezeOwnFields(*this);')
2327
+ ]),
2328
+ // SetIntegrityLevel(sealed) retains writability while making present fields non-configurable.
2329
+ ...classMember('void gea_sealOwnFields()', [...baseSealFields, ...viaTable(sealFields, 'gea::detail::nativeSealOwnFields(*this);')]),
2330
+ // TestIntegrityLevel(frozen) over present fixed data properties.
2331
+ ...classMember('bool gea_ownFieldsFrozen() const', [
2332
+ ...baseFrozenFields,
2333
+ ...viaTable(frozenFields, 'if (!gea::detail::nativeOwnFieldsFrozen(*this)) return false;'),
2334
+ ' return true;'
2335
+ ]),
2336
+ // TestIntegrityLevel(sealed) over present fixed data properties.
2337
+ ...classMember('bool gea_ownFieldsSealed() const', [
2338
+ ...baseSealedFields,
2339
+ ...viaTable(sealedFields, 'if (!gea::detail::nativeOwnFieldsSealed(*this)) return false;'),
2340
+ ' return true;'
2341
+ ]),
2342
+ // A present entry of this record's index-signature sidecar. It is deliberately separate from fixed C++ fields: the former is configurable, the latter is not.
1725
2343
  ...dynamicMember('bool gea_readOwnIndex(const gea::PropertyKey& gea_key, gea::Value& gea_out) const', [
1726
2344
  ...baseIndexRead,
1727
2345
  ...sidecarRead,
1728
2346
  ' return false;'
1729
2347
  ]),
1730
- ' /** Whether a key belongs to this typed index domain, even when no entry is present. */',
2348
+ // Whether a key belongs to this typed index domain, even when no entry is present.
1731
2349
  ...dynamicMember('bool gea_matchesOwnIndex(const gea::PropertyKey& gea_key) const', [
1732
2350
  ...baseIndexMatches,
1733
2351
  ...sidecarMatches,
1734
2352
  ' return false;'
1735
2353
  ]),
1736
- ' /** Store one index-signature entry without making it masquerade as a fixed field. */',
2354
+ // Store one index-signature entry without making it masquerade as a fixed field.
1737
2355
  ...dynamicMember('bool gea_writeOwnIndex(const gea::PropertyKey& gea_key, const gea::Value& gea_value, bool gea_extensible = true)', [
1738
2356
  ...baseIndexWrite,
1739
2357
  ...sidecarWrite,
1740
2358
  ' return false;'
1741
2359
  ]),
1742
- ' /** Complete descriptor reflection for one present typed index entry. */',
2360
+ // Complete descriptor reflection for one present typed index entry.
1743
2361
  ...dynamicMember('bool gea_ownIndexDescriptor(const gea::PropertyKey& gea_key, gea::PropertyDescriptor& gea_out) const', [
1744
2362
  ...baseIndexDescriptor,
1745
2363
  ...sidecarDescriptor,
1746
2364
  ' return false;'
1747
2365
  ]),
1748
- ' /** Data-descriptor-only ValidateAndApplyPropertyDescriptor for the typed index store. */',
2366
+ // Data-descriptor-only ValidateAndApplyPropertyDescriptor for the typed index store.
1749
2367
  ...dynamicMember('bool gea_defineOwnIndex(const gea::PropertyKey& gea_key, const gea::PropertyDescriptor& gea_descriptor, bool gea_extensible)', [...baseIndexDefine, ...sidecarDefine, ' return false;']),
1750
- ' /** Typed indexed assignment keeps its value native while honoring the same descriptor bits. */',
2368
+ // Typed indexed assignment keeps its value native while honoring the same descriptor bits.
1751
2369
  ...nativeWriteMethods,
1752
- ' /** Delete an index-signature entry. Fixed fields intentionally never reach this hook. */',
2370
+ // Delete an index-signature entry. Fixed fields intentionally never reach this hook.
1753
2371
  ...dynamicMember('bool gea_deleteOwnIndex(const gea::PropertyKey& gea_key)', [
1754
2372
  ...baseIndexDelete,
1755
2373
  ...sidecarDelete,
1756
2374
  ' return false;'
1757
2375
  ]),
1758
- ' /** Freeze the sidecar entries without changing their native value carrier. */',
2376
+ // Freeze the sidecar entries without changing their native value carrier.
1759
2377
  ...classMember('void gea_freezeOwnIndex()', [...baseIndexFreeze, ...sidecarFreeze]),
1760
- ' /** Seal keeps typed index values writable while making their present entries non-configurable. */',
2378
+ // Seal keeps typed index values writable while making their present entries non-configurable.
1761
2379
  ...classMember('void gea_sealOwnIndex()', [
1762
2380
  ...(base && !base.native ? [` this->${base.structName}::gea_sealOwnIndex();`] : []),
1763
2381
  ...sidecarSeal
1764
2382
  ]),
1765
- ' /** TestIntegrityLevel(frozen) over present typed index entries. */',
2383
+ // TestIntegrityLevel(frozen) over present typed index entries.
1766
2384
  ...classMember('bool gea_ownIndexFrozen() const', [
1767
2385
  ...(base && !base.native ? [` if (!this->${base.structName}::gea_ownIndexFrozen()) return false;`] : []),
1768
2386
  ...sidecarFrozen,
1769
2387
  ' return true;'
1770
2388
  ]),
1771
- ' /** TestIntegrityLevel(sealed) over present typed index entries. */',
2389
+ // TestIntegrityLevel(sealed) over present typed index entries.
1772
2390
  ...classMember('bool gea_ownIndexSealed() const', [
1773
2391
  ...(base && !base.native ? [` if (!this->${base.structName}::gea_ownIndexSealed()) return false;`] : []),
1774
2392
  ...sidecarSealed,
1775
2393
  ' return true;'
1776
2394
  ]),
1777
- ' /** The full string-and-symbol own-key list for this native struct. String-only consumers filter symbols; reflective consumers retain them. */',
2395
+ // The full string-and-symbol own-key list for this native struct. String-only consumers filter symbols; reflective consumers retain them.
2396
+ // The keys are appended to `gea_out` itself and ordered in place: a
2397
+ // separate list copied in afterwards was a string copy per key per listing
2398
+ // (every spread of an options record lists its keys).
1778
2399
  ...classMember('void gea_ownFieldKeys(std::vector<gea::PropertyKey>& gea_out) const', [
1779
- ' std::vector<gea::PropertyKey> gea_declared;',
2400
+ ' const std::size_t gea_start = gea_out.size();',
2401
+ ' std::vector<gea::PropertyKey>& gea_declared = gea_out;',
1780
2402
  ...baseKeys,
1781
2403
  ...keys,
1782
2404
  ...sidecarKeys,
1783
- ' std::vector<gea::PropertyKey> gea_indices;',
1784
- ' std::vector<gea::PropertyKey> gea_strings;',
1785
- ' std::vector<gea::PropertyKey> gea_symbols;',
1786
- ' for (const auto& gea_key : gea_declared) {',
1787
- ' if (gea_key.isSymbol()) gea_symbols.push_back(gea_key);',
1788
- ' else if (gea::DynamicObject::arrayIndexOf(gea_key.text()) != gea::DynamicObject::kNotAnArrayIndex) gea_indices.push_back(gea_key);',
1789
- ' else gea_strings.push_back(gea_key);',
1790
- ' }',
1791
- ' std::stable_sort(gea_indices.begin(), gea_indices.end(), [](const gea::PropertyKey& gea_left, const gea::PropertyKey& gea_right) {',
1792
- ' return gea::DynamicObject::arrayIndexOf(gea_left.text()) < gea::DynamicObject::arrayIndexOf(gea_right.text());',
1793
- ' });',
1794
- ' gea_out.insert(gea_out.end(), gea_indices.begin(), gea_indices.end());',
1795
- ' gea_out.insert(gea_out.end(), gea_strings.begin(), gea_strings.end());',
1796
- ' gea_out.insert(gea_out.end(), gea_symbols.begin(), gea_symbols.end());'
1797
- ])
2405
+ // The runtime's one 10.1.11.1 ordering, which every other own-key list
2406
+ // takes; spelled out here it was the same fourteen lines in each of the
2407
+ // mongodb driver's 1126 structs.
2408
+ ' gea::detail::orderOwnPropertyKeysFrom(gea_out, gea_start);'
2409
+ ]),
2410
+ // `EnumerableOwnPropertyNames` (7.3.23) in ONE pass, for a struct whose
2411
+ // keys are still in layout order: the present enumerable string fields in
2412
+ // declaration order, then each string sidecar's entries in creation order.
2413
+ // `Object.keys` of a boxed struct otherwise built the full key list, sorted
2414
+ // it twice (once here, once in `nativeOwnKeysInCreationOrder`) and asked
2415
+ // for a descriptor per key -- thirteen allocations and a quadratic scan per
2416
+ // command document the mongodb driver serialized. `false` hands the caller
2417
+ // back to that path: a key 10.1.11.1 orders ahead of the fields, or a base
2418
+ // this emitter did not generate.
2419
+ ...classMember('bool gea_ownEnumerableStringKeys(std::vector<std::string>& gea_out) const', enumerableStringKeysBody)
1798
2420
  ];
1799
2421
  };
1800
2422
  /**
@@ -1854,6 +2476,15 @@ export const cppReactiveRevisionFieldName = (key) => `${cppRecordFieldName(key)}
1854
2476
  * nothing outside this file's own readers sees a carrier that disagrees with
1855
2477
  * the plan -- and every other spelling of the same member (`dynamicFieldAccessOf`
1856
2478
  * below) is passed this answer rather than re-deriving one.
2479
+ *
2480
+ * A field the layout moved to the TAIL (`tailFieldsOf`) is declared with this
2481
+ * exact same type -- `gea::Optional<T>`, never a distinct wrapper -- just
2482
+ * inside the generated tail struct instead of here. Physical PLACEMENT and
2483
+ * C++ TYPE are two different questions; this function only ever answers the
2484
+ * second one, which is why it needs no `sparse`/tail parameter at all (the
2485
+ * previous `gea::SparseOptional<T>` design conflated them into one spelling,
2486
+ * and paid for it with N per-field heap allocations where the whole struct
2487
+ * needed at most one -- see `RecordTail`'s own comment in the runtime header).
1857
2488
  */
1858
2489
  const fieldStorageType = (field, reactive, celled, narrowed) => {
1859
2490
  const inner = narrowed ? cppNarrowedIntegerType : cppTypeOf(field.value);
@@ -1863,6 +2494,212 @@ const fieldStorageType = (field, reactive, celled, narrowed) => {
1863
2494
  return inner;
1864
2495
  return `${reactive.cell}<${inner}>`;
1865
2496
  };
2497
+ const emptyStringSet = new Set();
2498
+ /**
2499
+ * `GEA_SPARSE_RECORD_LAYOUT=0` turns the whole tail-field split off: every
2500
+ * struct emits exactly the fields it would have before this layout existed,
2501
+ * byte-identical. The A/B this exists for is a CPU measurement on the real
2502
+ * mongodb driver, not a correctness question -- both arms are sound -- so a
2503
+ * single env read at emission time, asked everywhere `tailFieldsOf` is (never
2504
+ * cached, since one process only ever emits with one answer), is the whole
2505
+ * mechanism.
2506
+ */
2507
+ const sparseLayoutDisabled = () => process.env.GEA_SPARSE_RECORD_LAYOUT === '0';
2508
+ /**
2509
+ * The threshold past which a record's per-field storage, not its allocation
2510
+ * count, is the cost that matters: a family with this many fields, most of
2511
+ * them optional, reserves every field's bytes in the block `makeRef` takes
2512
+ * on every allocation of it, copies every one of those bytes on every
2513
+ * `{...spread}`, and touches every one of them tracing and destroying it --
2514
+ * whether or not the field was ever set. Measured against mongodb's
2515
+ * `extends`-connected options family (134 fields, ~90% optional, 18
2516
+ * instances per driver operation, 2584-byte block, 55% of all bytes the
2517
+ * driver allocates).
2518
+ */
2519
+ const sparseLayoutFieldThreshold = 32;
2520
+ /** The fraction of a qualifying struct's fields that must be optional for the layout to be worth sparsifying at all. */
2521
+ const sparseLayoutOptionalFraction = 0.5;
2522
+ /**
2523
+ * Every `optional`-carrying field of a struct large and optional-heavy enough
2524
+ * (the two constants above) that moving its rarely-set fields out of line is
2525
+ * worth considering at all -- the CANDIDATE set `tailFieldsOf` then narrows by
2526
+ * payload size. A required field is never a candidate: it is present, and its
2527
+ * payload constructed, for the whole life of every instance, so moving it
2528
+ * anywhere would only add indirection with no offsetting byte ever left
2529
+ * unreserved.
2530
+ */
2531
+ export const sparseLayoutFieldsOf = (layout) => {
2532
+ if (sparseLayoutDisabled())
2533
+ return emptyStringSet;
2534
+ if (layout.fields.length <= sparseLayoutFieldThreshold)
2535
+ return emptyStringSet;
2536
+ const optionalFields = layout.fields.filter((field) => field.value.kind === 'optional');
2537
+ if (optionalFields.length < layout.fields.length * sparseLayoutOptionalFraction)
2538
+ return emptyStringSet;
2539
+ return new Set(optionalFields.map((field) => field.key));
2540
+ };
2541
+ /**
2542
+ * Whether an `optional` field's PAYLOAD is small enough that moving it out of
2543
+ * line would cost more than it saves. Measured directly against the runtime
2544
+ * header (`gea_runtime.h`'s `Optional<T>`/pointer sizes), not estimated:
2545
+ *
2546
+ * | payload | `sizeof(Optional<T>)` | fits inline |
2547
+ * |-----------------------------------|-----------------------|-------------|
2548
+ * | `bool` | 2 | yes |
2549
+ * | `double` / narrowed `long long` | 16 | yes |
2550
+ * | `gea::Symbol` | 8 | yes |
2551
+ * | any `gea::Ref<T>` (uniform, any T) | 16 | yes |
2552
+ * | `std::string` | 32 | no |
2553
+ * | `gea::Value` (dynamic) | 56 | no |
2554
+ * | any `gea::TaggedUnion<...>` | 24-40+ (every arm measured) | no |
2555
+ * | a record/array/dictionary held BY VALUE (`ownership: 'owned'`), not `Ref` | size of the whole embedded structure | no |
2556
+ *
2557
+ * A `gea::Ref<T>` is a single type-erased smart pointer whatever `T` is
2558
+ * (`ownershipOf` answering `'shared-refcount'` is exactly "this payload's C++
2559
+ * spelling is `gea::Ref<...>`"), so its `Optional` wrapper is the same 16
2560
+ * bytes regardless of the referent -- moving it to the tail would trade a
2561
+ * cheap 16-byte member for a heap allocation on first write and STILL an
2562
+ * 8-byte pointer in the outer struct, a pure loss. `'borrowed'` is the same
2563
+ * shape (a non-owning reference) for the same reason. Every other payload
2564
+ * kind defaults to the tail: an unmodeled or unmeasured kind is never assumed
2565
+ * small, so at worst it costs one indirection a future measurement could
2566
+ * remove, never a silently bloated struct.
2567
+ */
2568
+ const sparseFieldFitsInline = (payload) => {
2569
+ if (payload.kind === 'scalar' || payload.kind === 'symbol')
2570
+ return true;
2571
+ const ownership = ownershipOf(payload);
2572
+ return ownership === 'shared-refcount' || ownership === 'borrowed';
2573
+ };
2574
+ /**
2575
+ * Which of a struct's fields this layout physically moves BEHIND the one
2576
+ * lazily-allocated `RecordTail` member (`cppRecordTailMemberName`) -- the
2577
+ * candidates from `sparseLayoutFieldsOf`, minus a reactive-celled or
2578
+ * integer-narrowed one (never actually an `optional` payload in practice, so
2579
+ * this guard is defensive rather than load-bearing -- see `fieldStorageType`'s
2580
+ * own history), minus whichever ones `sparseFieldFitsInline` says are cheaper
2581
+ * left where they are. Every OTHER field (dense, or sparse-eligible but
2582
+ * size-exempt) is declared exactly as it always was.
2583
+ *
2584
+ * Exported so `emit-properties.ts` and every other reader that spells a field
2585
+ * access can ask, of one representation and key, whether it has to route
2586
+ * through the tail -- one authority, asked with the same (defaulted, in
2587
+ * practice never differing -- see above) inputs `renderStructDefinition`
2588
+ * itself uses, so a reader outside this file's own rendering pass can never
2589
+ * compute a different answer for the same field.
2590
+ */
2591
+ export const tailFieldsOf = (layout, celled = emptyStringSet, cellName = null, isNarrowed = () => false) => {
2592
+ const candidates = sparseLayoutFieldsOf(layout);
2593
+ if (candidates.size === 0)
2594
+ return emptyStringSet;
2595
+ const tail = new Set();
2596
+ for (const field of layout.fields) {
2597
+ if (!candidates.has(field.key) || field.value.kind !== 'optional')
2598
+ continue;
2599
+ const celledField = cellName !== null && celled.has(field.key) && representationCanCell(field.value);
2600
+ if (isNarrowed(field) || celledField)
2601
+ continue;
2602
+ if (!sparseFieldFitsInline(field.value.payload))
2603
+ tail.add(field.key);
2604
+ }
2605
+ return tail;
2606
+ };
2607
+ /** The struct's one tail-block member -- present (and non-null in the type sense) whenever `tailFieldsOf` is non-empty. */
2608
+ export const cppRecordTailMemberName = 'gea_tail';
2609
+ /** The generated struct name for a layout's tail block, holding exactly its `tailFieldsOf` members as plain `gea::Optional<T>`. */
2610
+ export const cppRecordTailStructName = (structName) => `${structName}_gea_tail`;
2611
+ /**
2612
+ * The WRITE spelling of a field's VALUE storage as a C++ member-access suffix
2613
+ * (no receiver, no `.`/`->` -- the caller's own accessor prefixes it) --
2614
+ * `dynamicFieldAccessOf`'s `member` computation, generalized for every OTHER
2615
+ * emitter that STORES a record field's value directly rather than through the
2616
+ * reflection dispatcher: a construction's initial store, an ordinary `obj.key
2617
+ * = value`. Presence (`cppRecordFieldPresenceName`) and attributes
2618
+ * (`cppRecordFieldAttributesName`) are NEVER routed through this -- they stay
2619
+ * declared, and spelled, directly on the outer struct for every field, tail or
2620
+ * not (see `renderStructDefinition`'s own comment on why that bool is kept
2621
+ * rather than derived from the tail).
2622
+ *
2623
+ * Every caller already resolves its own `fields` list (a record's own, or a
2624
+ * shape's through `recordLayoutOfShapeId`/`recordFieldsOfShape` -- the same
2625
+ * underlying table, so two callers resolving it their own way never disagree
2626
+ * about which fields exist), so this takes that list rather than a
2627
+ * representation, and answers the one remaining question: which of them,
2628
+ * if any, this struct's layout moved behind the tail.
2629
+ *
2630
+ * Reached only for a value the caller already knows is BECOMING present: a
2631
+ * literal's own initializer, a `[[Set]]`/`[[DefineOwnProperty]]` that is
2632
+ * about to store into this exact field, a copy whose source presence bit a
2633
+ * surrounding guard already tested true. A caller merely reading a field's
2634
+ * CURRENT value -- including to decide whether to copy it -- must use
2635
+ * `tailAwareFieldReadText` below instead: this spelling's `RecordTail::ensure()`
2636
+ * allocates unconditionally, and using it for a read (or for a copy that has
2637
+ * not first proven the source present) forces every such call to allocate a
2638
+ * tail block an object may otherwise never need -- the defect a prior,
2639
+ * single-spelling version of this authority had (see `RecordTail`'s own
2640
+ * comment in the runtime header).
2641
+ */
2642
+ /**
2643
+ * Whether a store that makes a declared field of `representation` present
2644
+ * must tell the runtime it created that key (`declaredFieldCreationText`).
2645
+ * Only a plain record qualifies: a class declares its fields at construction,
2646
+ * so their layout order is their creation order, and an owned or borrowed
2647
+ * struct has no allocation header for a creation-order log to hang off.
2648
+ */
2649
+ export const tracksDeclaredFieldCreation = (representation) => (representation.kind === 'record' ||
2650
+ representation.kind === 'record-with-index' ||
2651
+ (representation.kind === 'native-record-ref' && representation.native === null)) &&
2652
+ representation.ownership === 'shared-refcount';
2653
+ /**
2654
+ * The statement that precedes a store creating field `key` on the shared
2655
+ * record `receiver`, so the runtime learns it was created after every key
2656
+ * already present (ECMA-262 10.1.11.1): a store into a record whose keys are
2657
+ * not known here, which asks the runtime whenever the field was absent -- the
2658
+ * only cost on a store into a field already present. A fresh record's order
2659
+ * is known statically instead (`staticKeyOrderText`).
2660
+ */
2661
+ export const declaredFieldCreationText = (receiver, key) => `if (!${receiver}->${cppRecordFieldPresenceName(key)}) gea::detail::noteNativeDeclaredKeyCreated(${receiver}, ${cppStringLiteral(key)});`;
2662
+ /**
2663
+ * The statement stating that the shared record `receiver`'s keys so far were
2664
+ * created in the order of `keys`, all known here: an out-of-order store into a
2665
+ * fresh record (`ir/facts.ts`'s `outOfOrderFreshStores`), or a record whose
2666
+ * order a spread or its allocation fixed. The keys are a constant table and
2667
+ * the runtime keeps only its address until the order is asked for
2668
+ * (`gea::detail::pendNativeKeyOrder`).
2669
+ */
2670
+ export const staticKeyOrderText = (receiver, keys) => `{ static constexpr std::string_view gea_key_order[] = {${keys
2671
+ .map((key) => `std::string_view(${cppStringLiteral(key)}, ${Buffer.byteLength(key, 'utf8')})`)
2672
+ .join(', ')}}; gea::detail::pendNativeKeyOrder(${receiver}, gea_key_order, ${keys.length}); }`;
2673
+ export const tailAwareFieldWriteText = (fields, fieldName) => tailFieldsOf({ fields }).has(fieldName)
2674
+ ? `${cppRecordTailMemberName}.ensure().${cppRecordFieldName(fieldName)}`
2675
+ : cppRecordFieldName(fieldName);
2676
+ /**
2677
+ * The READ spelling of a field's VALUE storage: a full expression (not a bare
2678
+ * suffix -- `prefix` is baked in, because the peek-based ternary below needs
2679
+ * to test the tail block's OWN pointer, which the write spelling's plain
2680
+ * member-access suffix has no room to do) that answers the field's current
2681
+ * value without ever allocating.
2682
+ *
2683
+ * `prefix` is whatever text already reaches the struct -- `"value."`, an
2684
+ * SSA operand followed by `->`, an accessor-composed member chain -- spelled
2685
+ * exactly once: it is embedded into this expression a single time (as the
2686
+ * initializer of a local pointer inside an immediately-invoked lambda), so a
2687
+ * caller may pass a deferred/side-effecting operand text here exactly as
2688
+ * safely as it could hand that text to a single ordinary member access.
2689
+ *
2690
+ * For a non-tail field this degrades to the plain member-access read
2691
+ * `tailAwareFieldWriteText` would also spell (no tail, nothing to protect
2692
+ * against allocating) -- one authority answers both "is this a tail field"
2693
+ * and "how do I read/write it", so a caller never has to ask the first
2694
+ * question itself before choosing which of these two functions to call.
2695
+ */
2696
+ export const tailAwareFieldReadText = (fields, fieldName, prefix) => {
2697
+ if (!tailFieldsOf({ fields }).has(fieldName))
2698
+ return `${prefix}${cppRecordFieldName(fieldName)}`;
2699
+ const member = cppRecordFieldName(fieldName);
2700
+ return (`([&]() { const auto* gea_tail_ptr = (${prefix}${cppRecordTailMemberName}).peek(); ` +
2701
+ `return gea_tail_ptr != nullptr ? gea_tail_ptr->${member} : decltype(gea_tail_ptr->${member})(); })()`);
2702
+ };
1866
2703
  /**
1867
2704
  * Which of a struct's fields this compilation holds in a cell, by struct name.
1868
2705
  *
@@ -1924,6 +2761,152 @@ const reactiveFieldsByStruct = (classes, reactive, fieldsByStruct, bound) => {
1924
2761
  }
1925
2762
  return byStruct;
1926
2763
  };
2764
+ /**
2765
+ * Whether a field's `gea::Optional` can own a resource: any payload but a bare
2766
+ * scalar or symbol, which is trivially destroyed. A string, a handle, a union
2767
+ * or a record held by value all have something to release when the field is
2768
+ * present, and nothing when it is not.
2769
+ */
2770
+ const optionalOwnsResources = (field) => field.value.kind === 'optional' && field.value.payload.kind !== 'scalar' && field.value.payload.kind !== 'symbol';
2771
+ /**
2772
+ * The spelling of one field's member inside the tail block or the struct.
2773
+ * `gea_resetOwnField` below stores the empty value through it.
2774
+ */
2775
+ const manualOptionalReset = (fieldName, tail) => tail
2776
+ ? `${cppRecordTailMemberName}.ensure().${fieldName} = std::decay_t<decltype(${cppRecordTailMemberName}.ensure().${fieldName})>();`
2777
+ : `${fieldName} = std::decay_t<decltype(${fieldName})>();`;
2778
+ /**
2779
+ * `gea_resetOwnField`: what `delete` stores into a field whose presence bit it
2780
+ * clears. A struct that destroys its fields by presence (`manualDestruction`)
2781
+ * reads only the bits, so a value left behind a cleared bit would never be
2782
+ * released.
2783
+ */
2784
+ const renderResetOwnField = (layout, tailFields) => {
2785
+ const lines = [' void gea_resetOwnField(std::string_view gea_name) {'];
2786
+ for (const field of layout.fields) {
2787
+ if (!optionalOwnsResources(field))
2788
+ continue;
2789
+ lines.push(` if (gea_name == ${cppStringLiteral(field.key)}) { ${manualOptionalReset(cppRecordFieldName(field.key), tailFields.has(field.key))} return; }`);
2790
+ }
2791
+ lines.push(' }');
2792
+ return lines;
2793
+ };
2794
+ /**
2795
+ * Runs of eight consecutive optional fields own eight consecutive presence
2796
+ * bytes (`presenceSkippingBody` in `emit-allocation.ts` states the same fact
2797
+ * for the spread copy), so one word test answers for the whole run. A tail of
2798
+ * fewer than eight, or a run holding a required field, is tested field by field.
2799
+ */
2800
+ const presenceRuns = (fields) => {
2801
+ const runs = [];
2802
+ let position = 0;
2803
+ while (position < fields.length) {
2804
+ const run = fields.slice(position, position + 8);
2805
+ if (run.length === 8 && run.every((field) => !field.required)) {
2806
+ runs.push([...run]);
2807
+ position += 8;
2808
+ }
2809
+ else {
2810
+ runs.push([fields[position]]);
2811
+ position += 1;
2812
+ }
2813
+ }
2814
+ return runs;
2815
+ };
2816
+ /**
2817
+ * The members a record needs when its fields that own resources are destroyed
2818
+ * by their presence bits and not by one destructor test each.
2819
+ *
2820
+ * A wide options record carries ~25 handles and unions inline and ~20 strings
2821
+ * in its tail, a handful present at a time, and the generated destructor tested
2822
+ * every one of them (~280 instructions of a ~2200-instruction spread). Each
2823
+ * such field is moved into an anonymous union -- still spelled `name` by every
2824
+ * reader and writer, but no longer destroyed by the struct's implicit
2825
+ * destructor -- and the destructor scans the presence bytes eight at a time,
2826
+ * destroying only the fields whose bit is set. That makes a cleared presence
2827
+ * bit mean "holds nothing", which `gea_resetOwnField` upholds for `delete`; a
2828
+ * field that is merely absent is never constructed past its empty state (a
2829
+ * non-const read of one default-constructs a payload that owns nothing).
2830
+ *
2831
+ * The union members have no implicit special members, so the struct states
2832
+ * each one: every data member is listed, in declaration order.
2833
+ */
2834
+ const renderManualDestruction = (structName, tailStructName, layout, tailFields, hot, members) => {
2835
+ const tailKeys = layout.fields.filter((field) => tailFields.has(field.key));
2836
+ const tailNames = tailKeys.map((field) => cppRecordFieldName(field.key));
2837
+ const tailTypes = tailKeys.map((field) => cppTypeOf(field.value));
2838
+ const tail = [
2839
+ ...tailNames.map((name, index) => ` union { ${tailTypes[index]} ${name}; };`),
2840
+ ` ${tailStructName}() {`,
2841
+ ` if constexpr ((${tailTypes.map((type) => `gea::detail::optionalEmptyIsZero<${type}>`).join(' && ')})) std::memset(static_cast<void*>(this), 0, sizeof(*this));`,
2842
+ ` else { ${tailNames.map((name) => `std::construct_at(&${name});`).join(' ')} }`,
2843
+ ' }',
2844
+ ` ${tailStructName}(const ${tailStructName}& gea_other) : ${tailNames.map((name) => `${name}(gea_other.${name})`).join(', ')} {}`,
2845
+ ` ${tailStructName}& operator=(const ${tailStructName}& gea_other) {`,
2846
+ ...tailNames.map((name) => ` ${name} = gea_other.${name};`),
2847
+ ' return *this;',
2848
+ ' }',
2849
+ ` ~${tailStructName}() {}`,
2850
+ ' void gea_destroyAll() noexcept {',
2851
+ ...tailNames.map((name) => ` std::destroy_at(&${name});`),
2852
+ ' }'
2853
+ ];
2854
+ const manual = new Set([...hot, ...tailFields]);
2855
+ const destroyField = (field) => {
2856
+ const name = cppRecordFieldName(field.key);
2857
+ const presence = cppRecordFieldPresenceName(field.key);
2858
+ return tailFields.has(field.key)
2859
+ ? `if (gea_tail_block != nullptr && ${presence}) std::destroy_at(&gea_tail_block->${name});`
2860
+ : `if (${presence}) std::destroy_at(&${name});`;
2861
+ };
2862
+ const scan = [];
2863
+ for (const run of presenceRuns(layout.fields)) {
2864
+ const owners = run.filter((field) => manual.has(field.key));
2865
+ if (owners.length === 0)
2866
+ continue;
2867
+ if (run.length === 1) {
2868
+ scan.push(` ${destroyField(run[0])}`);
2869
+ continue;
2870
+ }
2871
+ // Byte `i` of the word is field `i`'s bit: the targets this compiler
2872
+ // emits for are all little-endian.
2873
+ const mask = run.reduce((bits, field, index) => (manual.has(field.key) ? bits | (1n << BigInt(8 * index)) : bits), 0n);
2874
+ scan.push(` { std::uint64_t gea_run; std::memcpy(&gea_run, &${cppRecordFieldPresenceName(run[0].key)}, 8); ` +
2875
+ `if ((gea_run & 0x${mask.toString(16).padStart(16, '0')}ULL) != 0) { ${owners.map(destroyField).join(' ')} } }`);
2876
+ }
2877
+ const unions = hot.size > 0;
2878
+ const copyList = (wrap) => members.map((name) => `${name}(${wrap(name)})`).join(', ');
2879
+ const hotNames = layout.fields.filter((field) => hot.has(field.key)).map((field) => cppRecordFieldName(field.key));
2880
+ const struct = [
2881
+ ' static_assert(std::endian::native == std::endian::little, "a presence run is read as one little-endian word");',
2882
+ unions ? ` ${structName}() : ${hotNames.map((name) => `${name}()`).join(', ')} {}` : ` ${structName}() = default;`,
2883
+ ...(unions
2884
+ ? [
2885
+ ` ${structName}(const ${structName}& gea_o) : ${copyList((name) => `gea_o.${name}`)} {}`,
2886
+ ` ${structName}(${structName}&& gea_o) noexcept : ${copyList((name) => `std::move(gea_o.${name})`)} {}`,
2887
+ ` ${structName}& operator=(const ${structName}& gea_o) {`,
2888
+ ...members.map((name) => ` ${name} = gea_o.${name};`),
2889
+ ' return *this;',
2890
+ ' }',
2891
+ ` ${structName}& operator=(${structName}&& gea_o) noexcept {`,
2892
+ ...members.map((name) => ` ${name} = std::move(gea_o.${name});`),
2893
+ ' return *this;',
2894
+ ' }'
2895
+ ]
2896
+ : [
2897
+ ` ${structName}(const ${structName}&) = default;`,
2898
+ ` ${structName}(${structName}&&) = default;`,
2899
+ ` ${structName}& operator=(const ${structName}&) = default;`,
2900
+ ` ${structName}& operator=(${structName}&&) = default;`
2901
+ ]),
2902
+ ` ~${structName}() {`,
2903
+ ` ${tailStructName}* gea_tail_block = ${cppRecordTailMemberName}.detach();`,
2904
+ ...scan,
2905
+ ` if (gea_tail_block != nullptr) gea::RecordTail<${tailStructName}>::release(gea_tail_block);`,
2906
+ ' }'
2907
+ ];
2908
+ return { tail, struct };
2909
+ };
1927
2910
  const renderStructDefinition = (structName, layout, base, reactive, celled,
1928
2911
  /** The members `ir/integer-storage.ts` proved may be held in a `long long`, by slot. */
1929
2912
  narrowedSlots,
@@ -1964,9 +2947,71 @@ fixedFieldStateConstant = false,
1964
2947
  */
1965
2948
  staticMethodState = false,
1966
2949
  /** This class's own lazily-materialized arrow fields, by key -- see `renderFieldDispatcher`'s parameter of the same name. */
1967
- lazyArrowFields = undefined) => {
2950
+ lazyArrowFields = undefined,
2951
+ /** See `renderFieldDispatcher`'s parameter of the same name. */
2952
+ virtualDeclarations = new Map(),
2953
+ /** See `renderFieldDispatcher`'s parameter of the same name. */
2954
+ layouts = undefined,
2955
+ /** `traceLeafStructsOf` proved this struct a leaf of the cycle collector: written down for `gea::detail::RefTargetIsLeaf`. */
2956
+ traceLeaf = false,
2957
+ /**
2958
+ * Whether no `freeze`/`seal`/`defineProperty` in the program can reach an
2959
+ * instance of this struct (`integrity-restrictions.ts`'s
2960
+ * `restrictsRecordShape`, asked of every shape the struct answers for). Its
2961
+ * attribute triples are then the defaults for every instance's whole life,
2962
+ * so they are `static` members exactly as under `fixedFieldStateConstant`,
2963
+ * while presence stays per instance. Withheld for a class (its prototype
2964
+ * objects store non-default attributes) and for any derived struct.
2965
+ */
2966
+ attributesConstant = false,
2967
+ /**
2968
+ * The root of a class hierarchy every member of which the program evaluates
2969
+ * exactly once (`immortalMethodStateRoots`): its per-instance method-state
2970
+ * handle is then not an edge the collector follows -- see there.
2971
+ */
2972
+ methodStateUntraced = false) => {
1968
2973
  const isNarrowed = (field) => narrowedSlots.has(integerStorageSlot(structName, field.key));
2974
+ const tailFields = tailFieldsOf(layout, celled, reactive.cell, isNarrowed);
2975
+ const tailStructName = cppRecordTailStructName(structName);
2976
+ const tailLines = [];
2977
+ if (tailFields.size > 0) {
2978
+ // The tail block: exactly the fields this layout moved out of line, each
2979
+ // still `gea::Optional<T>` -- placement changed, the type did not (see
2980
+ // `fieldStorageType`'s own comment). One `geaTraceRefs` friend here, so the
2981
+ // outer struct's own trace body (below) calls it ONCE through
2982
+ // `RecordTail`'s own trace rather than repeating a per-field call for
2983
+ // every field this block holds.
2984
+ tailLines.push(`struct ${tailStructName} {`);
2985
+ for (const field of layout.fields) {
2986
+ if (!tailFields.has(field.key))
2987
+ continue;
2988
+ // `field.value` is always `optional` here (`tailFieldsOf` only ever
2989
+ // selects those), and `cppTypeOf` already spells an `optional`
2990
+ // representation as `gea::Optional<T>` -- the same call
2991
+ // `fieldStorageType` makes for an inline field, so this is the
2992
+ // identical type text, just written into a different struct.
2993
+ tailLines.push(` ${cppTypeOf(field.value)} ${cppRecordFieldName(field.key)};`);
2994
+ }
2995
+ const tailTraceable = layout.fields
2996
+ .filter((field) => tailFields.has(field.key))
2997
+ .map((field) => `gea::detail::TraceEdges<decltype(${cppRecordFieldName(field.key)})>::supported`);
2998
+ tailLines.push(` [[maybe_unused]] friend auto geaTraceRefs(const ${tailStructName}& value, gea::detail::RefVisitor& visitor)`);
2999
+ tailLines.push(` -> std::bool_constant<${tailTraceable.length ? tailTraceable.join(' || ') : 'false'}> {`);
3000
+ for (const field of layout.fields) {
3001
+ if (!tailFields.has(field.key))
3002
+ continue;
3003
+ tailLines.push(` gea::detail::traceRefs(value.${cppRecordFieldName(field.key)}, visitor);`);
3004
+ }
3005
+ tailLines.push(' return {};');
3006
+ tailLines.push(' }');
3007
+ tailLines.push('};');
3008
+ tailLines.push('');
3009
+ }
1969
3010
  const lines = [`struct ${structName}${isFinal ? ' final' : ''}${base ? ` : ${base.structName}` : ''} {`];
3011
+ // Every non-static data member in declaration order, and where each field's own line sits: what
3012
+ // `renderManualDestruction` needs to state the special members and to move fields into unions.
3013
+ const members = [];
3014
+ const fieldLineAt = new Map();
1970
3015
  const ownsMethodState = classDispatch && (!base || base.native);
1971
3016
  if (ownsMethodState)
1972
3017
  lines.push(` ${staticMethodState ? 'static inline ' : ''}gea::Ref<gea::NativeClassMethodState> gea_method_state;`);
@@ -2003,6 +3048,19 @@ lazyArrowFields = undefined) => {
2003
3048
  // constructor and `staticCast` now `static_assert` against erasing a
2004
3049
  // standalone handle, so a future attempt fails to COMPILE rather than to run.
2005
3050
  for (const field of layout.fields) {
3051
+ // A tail field's value lives in the tail block, not here -- see the
3052
+ // `gea_tail` member below. Its presence bit and attributes (further down)
3053
+ // are declared exactly as any other field's, unconditionally: this
3054
+ // deliberately keeps the redundant-looking `bool` beside a pointer that
3055
+ // could in principle encode presence itself, because deriving presence
3056
+ // from the tail instead would touch every one of the ~15 call sites that
3057
+ // already hardcode `cppRecordFieldPresenceName` for reflection
3058
+ // (freeze/seal/ownKeys/enumerate/matches/delete/descriptor-visit) -- a
3059
+ // second axis of change this design does not need to buy back one bool.
3060
+ if (tailFields.has(field.key))
3061
+ continue;
3062
+ fieldLineAt.set(field.key, lines.length);
3063
+ members.push(cppRecordFieldName(field.key));
2006
3064
  lines.push(` ${fieldStorageType(field, reactive, celled, isNarrowed(field))} ${cppRecordFieldName(field.key)};`);
2007
3065
  // A reactive field whose own carrier cannot be a cell gets the companion
2008
3066
  // revision cell instead -- see `cppReactiveRevisionFieldName`.
@@ -2010,6 +3068,10 @@ lazyArrowFields = undefined) => {
2010
3068
  lines.push(` ${reactive.cell}<double> ${cppReactiveRevisionFieldName(field.key)};`);
2011
3069
  }
2012
3070
  }
3071
+ if (tailFields.size > 0) {
3072
+ members.push(cppRecordTailMemberName);
3073
+ lines.push(` gea::RecordTail<${tailStructName}> ${cppRecordTailMemberName};`);
3074
+ }
2013
3075
  // A capturing accessor's environment. Declared beside the fields because it
2014
3076
  // IS storage -- see `cppRecordAccessorEnvironmentName` -- and type-erased
2015
3077
  // (`gea::PackedEnvironment` is a `void*` plus the handle that owns it), so
@@ -2043,12 +3105,23 @@ lazyArrowFields = undefined) => {
2043
3105
  // configurable. Bits follow all value/index members so existing aggregate
2044
3106
  // initializers keep their positional field layout.
2045
3107
  const constantPresence = (required) => (required && fixedFieldStateConstant ? 'static inline ' : '');
2046
- const constantAttributes = fixedFieldStateConstant ? 'static inline ' : '';
3108
+ const constantAttributes = fixedFieldStateConstant || attributesConstant ? 'static inline ' : '';
2047
3109
  for (const field of layout.fields) {
3110
+ if (constantPresence(field.required) === '')
3111
+ members.push(cppRecordFieldPresenceName(field.key));
2048
3112
  lines.push(` ${constantPresence(field.required)}bool ${cppRecordFieldPresenceName(field.key)} = ${field.required ? 'true' : 'false'};`);
2049
3113
  }
2050
- for (const field of layout.fields)
3114
+ for (const field of layout.fields) {
3115
+ if (constantAttributes === '')
3116
+ members.push(cppRecordFieldAttributesName(field.key));
2051
3117
  lines.push(` ${constantAttributes}gea::NativeIndexAttributes ${cppRecordFieldAttributesName(field.key)};`);
3118
+ }
3119
+ // `gea_runtime.h`'s `IsArrayPayload` keys on this member: a boxed tuple is
3120
+ // still an Array for `Array.isArray`, and its `length` is the count of its
3121
+ // present leading slots, not a field.
3122
+ const tupleArity = layout.tuple === true && !base ? positionalArityText(layout.fields, cppRecordFieldPresenceName) : null;
3123
+ if (tupleArity !== null)
3124
+ lines.push(` std::size_t gea_tupleLength() const { return ${tupleArity}; }`);
2052
3125
  // An accessor stores no VALUE, but it is still an own property, so it needs
2053
3126
  // the two bits every own property has: whether it is currently present (a
2054
3127
  // configurable one can be deleted) and its attributes. Without them a boxed
@@ -2057,16 +3130,33 @@ lazyArrowFields = undefined) => {
2057
3130
  lines.push(` ${constantPresence(true)}bool ${cppRecordFieldPresenceName(accessor.key)} = true;`);
2058
3131
  lines.push(` ${constantAttributes}gea::NativeIndexAttributes ${cppRecordFieldAttributesName(accessor.key)};`);
2059
3132
  }
3133
+ // An emitted copy (`Object.entries`/`values`/`assign`, spread) unrolls the
3134
+ // struct's DATA members and has no arm for an accessor, which is an own
3135
+ // property of a literal all the same. Saying so here, once, sends every such
3136
+ // copy to the runtime's creation-order walk (`gea::copyOwnPropertiesInCreationOrder`),
3137
+ // which reads each key through [[Get]] and so runs the getter. A class is not
3138
+ // this case: its accessors live on the prototype and are never copied.
3139
+ if (!classDispatch && renderableAccessors(layout).length > 0)
3140
+ lines.push(' static constexpr bool gea_ownAccessors = true;');
2060
3141
  // Trace the actual stored fields, including inherited storage and the
2061
3142
  // index sidecar. The collector counts ownership edges, never a reflective
2062
3143
  // property read (which could allocate, box, or run a getter).
2063
3144
  // A STATIC method state is not an edge the instance owns -- the collector's
2064
3145
  // trial deletion would subtract one reference per instance from an object
2065
- // only the class holds -- so it is traced by nobody.
3146
+ // only the class holds -- so it is traced by nobody. A per-instance state of a
3147
+ // hierarchy the program evaluates once is left out for the opposite reason: it
3148
+ // is one object whose strays cost one object (`immortalMethodStateRoots`).
2066
3149
  const traceableFields = [
2067
- ...(ownsMethodState && !staticMethodState ? ['true'] : []),
3150
+ ...(ownsMethodState && !staticMethodState && !methodStateUntraced ? ['true'] : []),
2068
3151
  ...(base ? [`gea::detail::TraceEdges<${base.structName}>::supported`] : []),
2069
- ...layout.fields.map((field) => `gea::detail::TraceEdges<decltype(${cppRecordFieldName(field.key)})>::supported`),
3152
+ ...layout.fields
3153
+ .filter((field) => !tailFields.has(field.key))
3154
+ .map((field) => `gea::detail::TraceEdges<decltype(${cppRecordFieldName(field.key)})>::supported`),
3155
+ // A tail field traces through the ONE `gea_tail` member instead of its own
3156
+ // per-field term: `RecordTail`'s own `TraceEdges` specialization asks the
3157
+ // same question of the whole block (gea_runtime.h), so a struct whose only
3158
+ // ref-reaching fields moved to the tail still reports `supported` truthfully.
3159
+ ...(tailFields.size > 0 ? [`gea::detail::TraceEdges<gea::RecordTail<${tailStructName}>>::supported`] : []),
2070
3160
  ...layout.indexes.map((index) => `gea::detail::TraceEdges<decltype(${cppRecordIndexSidecarNameFor(index, layout.indexes)})>::supported`)
2071
3161
  ];
2072
3162
  // `geaTraceRefs`'s only caller is `gea::detail::traceRefs`'s `if constexpr
@@ -2083,27 +3173,115 @@ lazyArrowFields = undefined) => {
2083
3173
  // answer `linkagePrefix` already gives every minted function for the same
2084
3174
  // reason: whether a minted entity has a caller is a program-wide fact this
2085
3175
  // renderer cannot see from one struct, so it never tries to predict it.
3176
+ if (traceLeaf)
3177
+ lines.push(' static constexpr bool gea_traceLeaf = true;');
2086
3178
  lines.push(` [[maybe_unused]] friend auto geaTraceRefs(const ${structName}& value, gea::detail::RefVisitor& visitor)`);
2087
3179
  lines.push(` -> std::bool_constant<${traceableFields.length ? traceableFields.join(' || ') : 'false'}> {`);
2088
3180
  if (base)
2089
3181
  lines.push(` gea::detail::traceRefs(static_cast<const ${base.structName}&>(value), visitor);`);
2090
- if (ownsMethodState && !staticMethodState)
3182
+ if (ownsMethodState && !staticMethodState && !methodStateUntraced)
2091
3183
  lines.push(' gea::detail::traceRefs(value.gea_method_state, visitor);');
2092
- for (const field of layout.fields)
3184
+ for (const field of layout.fields) {
3185
+ if (tailFields.has(field.key))
3186
+ continue;
2093
3187
  lines.push(` gea::detail::traceRefs(value.${cppRecordFieldName(field.key)}, visitor);`);
3188
+ }
3189
+ if (tailFields.size > 0)
3190
+ lines.push(` gea::detail::traceRefs(value.${cppRecordTailMemberName}, visitor);`);
2094
3191
  for (const index of layout.indexes)
2095
3192
  lines.push(` gea::detail::traceRefs(value.${cppRecordIndexSidecarNameFor(index, layout.indexes)}, visitor);`);
2096
3193
  lines.push(' return {};');
2097
3194
  lines.push(' }');
2098
- for (const line of renderFieldDispatcher(structName, layout, base, classDispatch, (field) => fieldStorageType(field, reactive, celled, isNarrowed(field)), wellKnownSymbols, definitions, dynamicProtocol, fieldOperations, accessorCarriesEnvironment, isFinal && base === undefined, lazyArrowFields))
3195
+ const unaddressableDemands = [];
3196
+ for (const line of renderFieldDispatcher(structName, classDispatch ? reflectedClassLayout(layout) : layout, base?.hookless ? undefined : base, classDispatch, (field) => fieldStorageType(field, reactive, celled, isNarrowed(field)), tailFields, wellKnownSymbols, definitions, dynamicProtocol, fieldOperations, accessorCarriesEnvironment, isFinal && base === undefined, lazyArrowFields, virtualDeclarations, layouts, unaddressableDemands))
2099
3197
  lines.push(line);
3198
+ if (unaddressableDemands.length > 0)
3199
+ return {
3200
+ structName,
3201
+ reason: `the program reaches ${unaddressableDemands.join(', ')} dynamically, and no checked conversion boxes or unboxes that field's carrier`
3202
+ };
3203
+ // `gea::makeRef<T>()` with no arguments value-initializes, and for an
3204
+ // aggregate that is a memset of the whole object before any member's own
3205
+ // constructor runs -- 2.4 KB per 134-field options record in the mongodb
3206
+ // driver, 18 of them per operation, all of it overwritten a byte at a time
3207
+ // by the members' constructors. The marker tells `makeRef` (gea_runtime.h)
3208
+ // to default-initialize instead. It is written only when every member
3209
+ // provably initializes itself: an `Optional` writes its state, a `Ref` its
3210
+ // null, a `std::string`/`gea::Value` its empty form, a `TaggedUnion` its first default-constructible arm, and the presence and
3211
+ // attribute members carry initializers. A plain scalar member (`double`,
3212
+ // `bool`, a narrowed integer) would be left indeterminate, as would a
3213
+ // reactive cell, a base subobject or an index sidecar, so any of those
3214
+ // withholds the marker and keeps value-initialization.
3215
+ const selfInitializing = (value) => {
3216
+ switch (value.kind) {
3217
+ case 'optional':
3218
+ case 'tagged-union':
3219
+ case 'string':
3220
+ case 'dynamic':
3221
+ case 'callable-identity':
3222
+ case 'constructor-identity':
3223
+ case 'error-constructor':
3224
+ return true;
3225
+ case 'class-ref':
3226
+ case 'record':
3227
+ case 'record-with-index':
3228
+ case 'native-record-ref':
3229
+ case 'array-object':
3230
+ case 'typed-array':
3231
+ case 'array-buffer':
3232
+ case 'shared-array-buffer':
3233
+ case 'data-view':
3234
+ case 'keyed-collection':
3235
+ case 'dictionary':
3236
+ return value.ownership === 'shared-refcount';
3237
+ default:
3238
+ return false;
3239
+ }
3240
+ };
3241
+ const defaultInitializes = base === undefined &&
3242
+ !classDispatch &&
3243
+ !stabilizeRefAddress &&
3244
+ virtualMembers.length === 0 &&
3245
+ layout.indexes.length === 0 &&
3246
+ layout.accessors.length === 0 &&
3247
+ layout.fields.every((field) => !celled.has(field.key) && !isNarrowed(field) && selfInitializing(field.value));
3248
+ // The creation-order log of a plain record, held in the object: the runtime's
3249
+ // key-order paths find it through the block's operations table, with no
3250
+ // address lookup and no weak owner (`InlineKeyOrder`, gea_runtime.h). A class
3251
+ // declares its fields at construction, so its layout order is its creation
3252
+ // order and it never has one; a derived struct inherits its base's slot.
3253
+ if (base === undefined && !classDispatch) {
3254
+ members.push('gea_keyOrder');
3255
+ lines.push(' gea::detail::InlineKeyOrder gea_keyOrder{};');
3256
+ }
3257
+ if (defaultInitializes)
3258
+ lines.push(' using gea_default_init = void;');
3259
+ if (tailFields.size > 0)
3260
+ for (const line of renderResetOwnField(layout, tailFields))
3261
+ lines.push(line);
3262
+ // Only a struct whose every member initializes itself: its default constructor is then written
3263
+ // here without a value-initialization it would lose, and nothing but fields, the tail, presence
3264
+ // bits and the key-order slot has to be copied.
3265
+ if (defaultInitializes && tailFields.size > 0 && layout.tuple !== true && process.env.GEA_PRESENCE_DESTRUCTION !== '0') {
3266
+ const hot = new Set(layout.fields.filter((field) => !tailFields.has(field.key) && optionalOwnsResources(field)).map((field) => field.key));
3267
+ const manual = renderManualDestruction(structName, tailStructName, layout, tailFields, hot, members);
3268
+ for (const key of hot) {
3269
+ const at = fieldLineAt.get(key);
3270
+ if (at !== undefined)
3271
+ lines[at] = ` union { ${lines[at].trim()} };`;
3272
+ }
3273
+ const head = tailLines.findIndex((line) => line.startsWith(' [[maybe_unused]] friend auto geaTraceRefs'));
3274
+ tailLines.splice(1, head - 1, ...manual.tail);
3275
+ for (const line of manual.struct)
3276
+ lines.push(line);
3277
+ }
2100
3278
  // Declared only; the definitions go out of line, after every body has been
2101
3279
  // forward-declared -- a member cannot forward to a body the file has not
2102
3280
  // named yet.
2103
3281
  for (const line of virtualMembers)
2104
3282
  lines.push(line);
2105
3283
  lines.push('};');
2106
- return lines.join('\n');
3284
+ return [...tailLines, ...lines].join('\n');
2107
3285
  };
2108
3286
  /**
2109
3287
  * Every struct definition the selected carriers require, in a deterministic
@@ -2140,9 +3318,11 @@ accessorCarriesEnvironment = () => false,
2140
3318
  /** `program-facts.ts`'s `fixedFieldStateConstant` -- see `renderStructDefinition`'s parameter of the same name. */
2141
3319
  fixedFieldStateConstant = false,
2142
3320
  /** `program-facts.ts`'s `singleEvaluationClasses` -- which classes may hold their method state statically. */
2143
- singleEvaluationClasses = new Set()) => {
3321
+ singleEvaluationClasses = new Set(),
3322
+ /** `integrity-restrictions.ts`'s `restrictsRecordShape` -- see `renderStructDefinition`'s `attributesConstant`. */
3323
+ recordShapeRestricted = () => true) => {
2144
3324
  const { links, unlinkable } = classBaseLinks(physicalClasses);
2145
- const { requiredStructs, fieldsByStruct, unlayoutable } = collectRequiredStructs(representations, deriver, links, unlinkable, classInstanceShapes(physicalClasses), new Map([...physicalClasses.values()].flatMap((layout) => layout.nativeStorage === undefined ? [] : [[cppClassName(layout.declaration), layout.nativeStorage.fields]])));
3325
+ const { requiredStructs, fieldsByStruct, unlayoutable, shapesByStruct } = collectRequiredStructs(representations, deriver, links, unlinkable, classInstanceShapes(physicalClasses), new Map([...physicalClasses.values()].flatMap((layout) => layout.nativeStorage === undefined ? [] : [[cppClassName(layout.declaration), layout.nativeStorage.fields]])));
2146
3326
  const celledByStruct = reactiveFieldsByStruct(classes, reactive, fieldsByStruct, boundRecordFields);
2147
3327
  // A `native-record-ref` never carries its own layout (model.ts): the shape
2148
3328
  // it names is expanded wherever a `record`/`record-with-index` for that
@@ -2260,7 +3440,21 @@ singleEvaluationClasses = new Set()) => {
2260
3440
  staticMethodStateClasses.add(declaration);
2261
3441
  staticMethodStateStructs.add(structName);
2262
3442
  }
2263
- const rendered = definitionOrder(structNames, links, valueDependencies).map((structName) => {
3443
+ const virtualDeclarations = new Map();
3444
+ const layouts = recordLayoutPolicyOf(deriver, classes, wellKnownSymbols);
3445
+ const ordered = definitionOrder(structNames, links, valueDependencies);
3446
+ const evaluatedOnce = (structName) => {
3447
+ const declaration = declarationByStruct.get(structName);
3448
+ return declaration !== undefined && singleEvaluationClasses.has(declaration);
3449
+ };
3450
+ const immortalStateRoots = immortalMethodStateRoots(classStructNames, baseStructNames, links, evaluatedOnce);
3451
+ const leafClasses = leafEligibleClassesOf(classStructNames, baseStructNames, links, staticMethodStateStructs, immortalStateRoots, (structName) => {
3452
+ const declaration = declarationByStruct.get(structName);
3453
+ return declaration === undefined || (lazyArrowFieldPlansForClass(classes, declaration)?.size ?? 0) > 0;
3454
+ });
3455
+ const traceLeafStructs = traceLeafStructsOf(fieldsByStruct, new Set([...classStructNames, ...baseStructNames, ...links.keys()].filter((structName) => !leafClasses.has(structName))), celledByStruct, leafClasses);
3456
+ const orderOf = new Map(ordered.map((structName, index) => [structName, index]));
3457
+ const rendered = ordered.map((structName) => {
2264
3458
  const layout = fieldsByStruct.get(structName);
2265
3459
  // Unreachable given the check above, and stated rather than assumed: an
2266
3460
  // entry that got past `missing` with no layout would render a struct with
@@ -2284,11 +3478,16 @@ singleEvaluationClasses = new Set()) => {
2284
3478
  // line too, however `splitFieldDefinitions`/`perFile` would otherwise
2285
3479
  // treat classes.
2286
3480
  const needsOutOfLineFields = (renderableAccessors(layout).length > 0 && !classStructNames.has(structName)) ||
2287
- (lazyArrowFields !== undefined && lazyArrowFields.size > 0);
3481
+ (lazyArrowFields !== undefined && lazyArrowFields.size > 0) ||
3482
+ writesConvertIntoLaterStruct(layouts, layout, orderOf.get(structName) ?? 0, orderOf);
2288
3483
  const definitions = splitFieldDefinitions || needsOutOfLineFields ? [] : undefined;
2289
3484
  if (definitions)
2290
3485
  fieldDefinitionsByStruct.set(structName, definitions);
2291
- return renderStructDefinition(structName, layout, links.get(structName), reactive, celledByStruct.get(structName) ?? new Set(), narrowedSlots, virtualMembersByStruct.get(structName) ?? [], classStructNames.has(structName), refAddressStableStructs.has(structName), !baseStructNames.has(structName), wellKnownSymbols, definitions, dynamicProtocolByStruct.get(structName) ?? true, fieldOperationsByStruct.get(structName), accessorCarriesEnvironment, fixedFieldStateConstant, staticMethodStateStructs.has(structName), lazyArrowFields);
3486
+ return renderStructDefinition(structName, layout, links.get(structName), reactive, celledByStruct.get(structName) ?? new Set(), narrowedSlots, virtualMembersByStruct.get(structName) ?? [], classStructNames.has(structName), refAddressStableStructs.has(structName), !baseStructNames.has(structName), wellKnownSymbols, definitions, dynamicProtocolByStruct.get(structName) ?? true, fieldOperationsByStruct.get(structName), accessorCarriesEnvironment, fixedFieldStateConstant, staticMethodStateStructs.has(structName), lazyArrowFields, virtualDeclarations, layouts, traceLeafStructs.has(structName), !classStructNames.has(structName) &&
3487
+ !links.has(structName) &&
3488
+ !baseStructNames.has(structName) &&
3489
+ [...(shapesByStruct.get(structName) ?? [])].every((shapeId) => !recordShapeRestricted(shapeId, layout.fields.some((field) => cppRecordFieldKeyIsSymbol(field.key)))) &&
3490
+ (shapesByStruct.get(structName)?.size ?? 0) > 0, immortalStateRoots.has(structName));
2292
3491
  });
2293
3492
  const refused = rendered.filter((entry) => typeof entry !== 'string');
2294
3493
  if (refused.length > 0)
@@ -2423,5 +3622,5 @@ export const classStaticFieldStorageRows = (storage) => {
2423
3622
  return rows
2424
3623
  .filter((entry) => entry.representation.kind !== 'unresolved' && entry.representation.kind !== 'void')
2425
3624
  .sort((left, right) => left.name.localeCompare(right.name))
2426
- .map((entry) => ({ type: cppTypeOf(entry.representation), name: entry.name }));
3625
+ .map((entry) => ({ type: cppTypeOf(entry.representation), name: entry.name, storageName: entry.storageName ?? entry.name }));
2427
3626
  };