@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,38 +1,248 @@
1
+ import { nullableUnionArmsOf } from '../../representation/json-nullable.js';
1
2
  import { allOperationsOf } from '../../ir/model.js';
3
+ import { hostTemplateFrameOf } from '../../ir/call-entry.js';
4
+ import { classMemberOf, declaredRecordFieldOf } from '../../projection/fields.js';
5
+ import { symbolPropertyKeyDeclarationOf } from '../../semantics/model/structural-types.js';
2
6
  import { representationKey } from '../../representation/model.js';
7
+ import { isPrivateNameKey } from '../../semantics/model/structural-types.js';
3
8
  import { bindingReference, createCppEmitBlockedError, declareCell, defineValueAlias, operandText } from './emit-context.js';
4
9
  import { cellValueText } from './emit-bindings.js';
5
10
  import { dynamicCarrierBoxText } from './emit-narrowing.js';
6
11
  import { classBoxable } from './class-layout.js';
7
12
  import { readsCell } from './deferral-safety.js';
8
13
  import { cppDateType } from './prototype/emit-prototype-date.js';
9
- import { recordFieldsOfShape } from './records.js';
10
- import { cppRecordFieldName, cppRecordFieldPresenceName, cppRecordStructName, cppStringLiteral, cppTypeOf } from './types.js';
14
+ import { recordFieldsOfShape, tailAwareFieldWriteText, tailAwareFieldReadText } from './records.js';
15
+ import { cppBodyName, cppClassName, cppRecordFieldAttributesName, cppRecordFieldKeyIsSymbol, cppRecordFieldPresenceName, cppRecordStructName, cppStringLiteral, cppTypeOf } from './types.js';
11
16
  import { armAt, armIs } from './emit-union-properties.js';
17
+ /** A fresh, empty collector for one walk. */
18
+ const emptyJsonCollected = () => ({ structs: new Map(), classes: new Map(), nullableUnions: new Map() });
19
+ const jsonWorldOf = (ctx) => ({
20
+ deriver: ctx.deriver,
21
+ classes: ctx.classes,
22
+ reactiveFields: ctx.hosts.reactive.cell === null ? null : ctx.hosts.reactive.fields
23
+ });
24
+ /** Every carrier kind whose value is a function object. SerializeJSONProperty (ECMA-262 25.5.2.2 step 10) answers `undefined` for one, so an own property holding it is left out of the object. */
25
+ const callableKinds = new Set([
26
+ 'function',
27
+ 'function-family',
28
+ 'constructor-family',
29
+ 'constructor-value-dispatch',
30
+ 'function-and-constructor',
31
+ 'function-value-family',
32
+ 'function-value-dispatch',
33
+ 'callable-identity',
34
+ 'constructor-identity',
35
+ 'error-constructor',
36
+ 'generic-function-set'
37
+ ]);
38
+ /** Whether every value `representation` can hold is either a function or `undefined` -- a property JSON always omits. */
39
+ const neverSerialized = (representation) => {
40
+ if (representation.kind === 'undefined' || callableKinds.has(representation.kind))
41
+ return true;
42
+ if (representation.kind === 'optional')
43
+ return representation.absence === 'undefined' && neverSerialized(representation.payload);
44
+ if (representation.kind === 'tagged-union')
45
+ return representation.arms.every((arm) => neverSerialized(arm.value));
46
+ return false;
47
+ };
48
+ /** Whether some arm of `representation` holds a function object while another does not -- a member whose presence in the text depends on a value this writer cannot dispatch on. */
49
+ const partlyCallable = (representation) => {
50
+ if (callableKinds.has(representation.kind))
51
+ return true;
52
+ if (representation.kind === 'optional')
53
+ return partlyCallable(representation.payload);
54
+ if (representation.kind === 'tagged-union')
55
+ return representation.arms.some((arm) => partlyCallable(arm.value));
56
+ return false;
57
+ };
12
58
  /**
13
- * Whether `representation` is one JSON-carrying arm plus absence arms.
59
+ * The own enumerable string-keyed properties an instance of `declaration`
60
+ * has, in the order OrdinaryOwnPropertyKeys (ECMA-262 10.1.11.1) lists them --
61
+ * or the reason no native writer can list them.
62
+ *
63
+ * A class instance is created by the base's construction first, and each
64
+ * class's field definitions run in declaration order (ECMA-262 15.7.14
65
+ * `InitializeInstanceElements`), so the keys are the chain's fields root
66
+ * first. A derived redeclaration of an inherited field redefines the existing
67
+ * property in place and keeps its position. Methods and accessors live on the
68
+ * prototype and are never own; a private name is a PrivateElement, not a
69
+ * property; a symbol key is not a string key. Anything a program ADDS past its
70
+ * declared fields lives in the object's expando sidecar, which the writer
71
+ * reads after these -- a declared field exists from construction, so it
72
+ * precedes every key the sidecar could hold.
14
73
  *
15
- * Anything wider is a genuine sum with no JSON discriminator -- a document
16
- * says `3`, not which arm of `number | Point` produced it -- so it answers
17
- * `null` and the caller refuses by name. Shared by the collector and by the
18
- * record renderer so both read exactly one rule.
74
+ * Refused rather than approximated: a class something extends (a carrier
75
+ * typed as it may hold a subclass instance with more own properties, and this
76
+ * writer is chosen by the static type), a class whose chain answers `toJSON`
77
+ * (SerializeJSONProperty would call it -- only the top-level direct case is
78
+ * rendered, by `classToJsonOf`), a native or reparented base (its own
79
+ * properties are the runtime's, or its construction never runs), and a
80
+ * reactive cell (the member is not the value).
19
81
  */
20
- const nullableUnionArmsOf = (representation) => {
21
- if (representation.kind !== 'tagged-union')
22
- return null;
23
- const nullIndex = representation.arms.findIndex((arm) => arm.value.kind === 'null');
24
- const undefinedIndex = representation.arms.findIndex((arm) => arm.value.kind === 'undefined');
25
- const presentIndex = representation.arms.findIndex((arm) => arm.value.kind !== 'null' && arm.value.kind !== 'undefined');
26
- const absenceCount = (nullIndex === -1 ? 0 : 1) + (undefinedIndex === -1 ? 0 : 1);
27
- const payload = representation.arms[presentIndex]?.value;
28
- if (nullIndex === -1 || presentIndex === -1 || payload === undefined)
29
- return null;
30
- if (representation.arms.length !== absenceCount + 1)
82
+ const classJsonMembersOf = (world, representation) => {
83
+ const classes = world.classes;
84
+ if (classes === null)
85
+ return 'no class layouts reach this JSON walk';
86
+ const declaration = representation.declaration;
87
+ const layout = classes.get(declaration);
88
+ if (layout === undefined)
89
+ return `class ${declaration} has no published layout`;
90
+ for (const other of classes.values()) {
91
+ if (other.base === declaration) {
92
+ return (`class ${declaration} is extended by ${other.declaration}, so a value typed as it may be a subclass instance with own ` +
93
+ 'properties this statically chosen writer does not list');
94
+ }
95
+ }
96
+ if (classMemberOf(classes, declaration, 'toJSON') !== null) {
97
+ return `class ${declaration} answers toJSON, which SerializeJSONProperty calls before writing; only a direct no-argument toJSON at the top level is rendered`;
98
+ }
99
+ const chain = [];
100
+ const seen = new Set();
101
+ for (let current = layout; current !== undefined;) {
102
+ if (seen.has(current.declaration))
103
+ return `class ${declaration} has a cyclic base chain`;
104
+ seen.add(current.declaration);
105
+ if (current.nativeBase !== null)
106
+ return `class ${current.declaration} extends a native ${current.nativeBase.protocol}, whose own properties the runtime holds`;
107
+ if (current.prototypeBase === true)
108
+ return `class ${current.declaration} was reparented, so its base's construction -- and its fields -- never run`;
109
+ chain.unshift(current);
110
+ current = current.base === null ? undefined : classes.get(current.base);
111
+ if (current === undefined && chain[0]?.base !== null)
112
+ return `a base of class ${declaration} has no published layout`;
113
+ }
114
+ const members = [];
115
+ const listed = new Set();
116
+ for (const link of chain) {
117
+ for (const field of link.fields) {
118
+ if (field.syntheticSubclassMemberOverlay || listed.has(field.key))
119
+ continue;
120
+ // A private name keys its field `#name` (`class-lifecycle.ts`), the
121
+ // spelling the layout itself uses; a symbol key is `sym(...)`.
122
+ if (isPrivateNameKey(field.key) || symbolPropertyKeyDeclarationOf(field.key) !== null)
123
+ continue;
124
+ listed.add(field.key);
125
+ if (world.reactiveFields?.get(link.declaration)?.has(field.key) === true) {
126
+ return `field "${field.key}" of class ${link.declaration} is a reactive cell, not the value it holds`;
127
+ }
128
+ const storage = declaredRecordFieldOf(world.deriver, representation, field.key, classes);
129
+ if (storage === null)
130
+ return `field "${field.key}" of class ${link.declaration} has no storage in its struct`;
131
+ members.push({ key: field.key, value: storage.value });
132
+ }
133
+ }
134
+ return members;
135
+ };
136
+ /** The class-instance case of `jsonUnsupportedReason`: collects a write-only overload over the instance's own properties. */
137
+ const classJsonUnsupportedReason = (world, representation, collected, visiting, direction, inRecordPair) => {
138
+ if (direction === 'read') {
139
+ return 'a JSON document decodes into plain objects, never into a class instance; `JSON.parse(text) as C` asserts a prototype the grammar cannot carry';
140
+ }
141
+ if (inRecordPair) {
142
+ return ('a class instance inside a record has no JSON mapping here: a record renders its write and read overloads as one pair, and ' +
143
+ 'the read half would have to decode a class instance out of a document');
144
+ }
145
+ const structName = cppClassName(representation.declaration);
146
+ // A class reached while it is still being walked is a recursive TYPE, not a
147
+ // cyclic value -- the record case's own reasoning, unchanged.
148
+ if (visiting.has(structName) || collected.classes.has(structName))
31
149
  return null;
32
- return { nullIndex, presentIndex, undefinedIndex, payload };
150
+ const members = classJsonMembersOf(world, representation);
151
+ if (typeof members === 'string')
152
+ return members;
153
+ const stillVisiting = new Set(visiting);
154
+ stillVisiting.add(structName);
155
+ for (const member of members) {
156
+ if (neverSerialized(member.value))
157
+ continue;
158
+ if (partlyCallable(member.value)) {
159
+ return `field "${member.key}" of class ${representation.declaration} may hold a function or a value, and only the value is written`;
160
+ }
161
+ // Both absences are spelled by the writer itself: `undefined` omits the
162
+ // property, `null` writes the literal.
163
+ const payload = member.value.kind === 'optional' ? member.value.payload : member.value;
164
+ const reason = jsonUnsupportedReason(world, payload, collected, stillVisiting, 'write', false);
165
+ if (reason !== null)
166
+ return `field "${member.key}" of class ${representation.declaration}: ${reason}`;
167
+ }
168
+ collected.classes.set(structName, { structName, members });
169
+ return null;
170
+ };
171
+ /** Runtime key ordering selects a field, while its value retains its native carrier. */
172
+ const renderJsonMemberWriter = (structName, fields) => {
173
+ const lines = [
174
+ `inline bool gea_json_write_member(std::string& out, const ${structName}& value, const gea::PropertyKey& key, bool& first) {`
175
+ ];
176
+ for (const field of fields) {
177
+ const member = tailAwareFieldReadText(fields, field.key, 'value.');
178
+ lines.push(` if (key.text() == ${cppStringLiteral(field.key)}) {`);
179
+ if (neverSerialized(field.value)) {
180
+ lines.push(' return true;', ' }');
181
+ continue;
182
+ }
183
+ const arms = nullableUnionArmsOf(field.value);
184
+ if (field.value.kind === 'optional' && field.value.absence === 'undefined')
185
+ lines.push(` if (!${member}.has_value()) return true;`);
186
+ if (arms !== null && arms.undefinedIndex !== -1)
187
+ lines.push(` if (${member}.is<${arms.undefinedIndex}>()) return true;`);
188
+ lines.push(` if (!first) out += ',';`, ` out += ${jsonKeyLiteral(field.key)};`);
189
+ if (field.value.kind === 'optional')
190
+ lines.push(` if (${member}.has_value()) gea_json_write(out, *${member}); else out += "null";`);
191
+ else
192
+ lines.push(` gea_json_write(out, ${member});`);
193
+ lines.push(' first = false;', ' return true;', ' }');
194
+ }
195
+ lines.push(' return false;', '}');
196
+ return lines.join('\n');
197
+ };
198
+ /**
199
+ * The `gea_json_write` overload for one class struct: SerializeJSONObject
200
+ * (ECMA-262 25.5.2.5) over the own properties `classJsonMembersOf` listed.
201
+ *
202
+ * A declared field can still be absent (deleted) or non-enumerable
203
+ * (`Object.defineProperty`), which is what its presence bit and attribute
204
+ * triple record, so each is asked at run time; a member holding `undefined`
205
+ * is omitted exactly as the record writer omits one. Write-only: nothing in a
206
+ * document decodes into a class.
207
+ */
208
+ const renderJsonClassOverload = (entry) => {
209
+ const lines = [
210
+ `inline void gea_json_write(std::string& out, const ${entry.structName}& value) {`,
211
+ ` out += '{';`,
212
+ ` bool gea_json_first = true;`
213
+ ];
214
+ for (const member of entry.members) {
215
+ if (neverSerialized(member.value))
216
+ continue;
217
+ const field = tailAwareFieldReadText(entry.members, member.key, 'value.');
218
+ const owned = `value.${cppRecordFieldPresenceName(member.key)} && value.${cppRecordFieldAttributesName(member.key)}.enumerable`;
219
+ const keyLiteral = jsonKeyLiteral(member.key);
220
+ const arms = nullableUnionArmsOf(member.value);
221
+ const guard = member.value.kind === 'optional' && member.value.absence === 'undefined'
222
+ ? ` && ${field}.has_value()`
223
+ : arms !== null && arms.undefinedIndex !== -1
224
+ ? ` && !${field}.is<${arms.undefinedIndex}>()`
225
+ : '';
226
+ const written = member.value.kind === 'optional' && member.value.absence === 'undefined'
227
+ ? `*${field}`
228
+ : member.value.kind === 'optional'
229
+ ? null
230
+ : field;
231
+ lines.push(` if (${owned}${guard}) {`);
232
+ lines.push(` if (!gea_json_first) out += ',';`);
233
+ lines.push(` out += ${keyLiteral};`);
234
+ if (written === null)
235
+ lines.push(` if (${field}.has_value()) gea_json_write(out, *${field}); else out += "null";`);
236
+ else
237
+ lines.push(` gea_json_write(out, ${written});`);
238
+ lines.push(` gea_json_first = false;`);
239
+ lines.push(` }`);
240
+ }
241
+ lines.push(` gea::json::writeNativeExpandoMembers(out, &value, gea_json_first);`);
242
+ lines.push(` out += '}';`);
243
+ lines.push(`}`);
244
+ return `${renderJsonMemberWriter(entry.structName, entry.members)}\n\n${lines.join('\n')}`;
33
245
  };
34
- /** A fresh, empty collector for one walk. */
35
- const emptyJsonCollected = () => ({ structs: new Map(), nullableUnions: new Map() });
36
246
  /**
37
247
  * Whether `representation` has a native `gea_json_write`/`gea_json_read`
38
248
  * mapping, and -- as a side effect -- every record struct reaching that
@@ -49,16 +259,30 @@ const emptyJsonCollected = () => ({ structs: new Map(), nullableUnions: new Map(
49
259
  * recursing forever the way a genuinely cyclic *value* would at runtime (see
50
260
  * this file's own top comment).
51
261
  */
52
- const jsonUnsupportedReason = (deriver, representation, collected, visiting, direction) => {
262
+ const jsonUnsupportedReason = (world, representation, collected, visiting, direction,
263
+ /** Whether this value is a field of a generated record, whose write and read overloads render as one pair. */
264
+ inRecordPair = false) => {
265
+ const deriver = world.deriver;
53
266
  switch (representation.kind) {
54
267
  case 'dynamic':
55
268
  return null;
56
269
  case 'dictionary':
57
- return direction === 'write' && representation.key === 'string' && representation.value.kind === 'dynamic'
58
- ? null
270
+ return representation.key === 'string'
271
+ ? jsonUnsupportedReason(world, representation.value, collected, visiting, direction, inRecordPair)
272
+ : `representation "${representationKey(representation)}" has no native JSON.stringify/parse mapping`;
273
+ case 'optional':
274
+ return representation.absence === 'null'
275
+ ? jsonUnsupportedReason(world, representation.payload, collected, visiting, direction, inRecordPair)
59
276
  : `representation "${representationKey(representation)}" has no native JSON.stringify/parse mapping`;
60
277
  case 'string':
61
278
  return null;
279
+ // One-valued carriers: `null` writes `null`; `undefined` writes `null` as
280
+ // an array element (ECMA-262 25.5.2.6) and is omitted as a record member
281
+ // (the struct writer skips it). Without them a record holding either --
282
+ // `{ NULL: null }`, `{ b: [] }` typed `never[]` -- fell back to its box.
283
+ case 'null':
284
+ case 'undefined':
285
+ return null;
62
286
  case 'scalar':
63
287
  // `bigint`/`int32`/`uint32`/`float64` are narrower numeric domains this
64
288
  // backend infers for typed-array elements and similar contexts, never
@@ -70,7 +294,7 @@ const jsonUnsupportedReason = (deriver, representation, collected, visiting, dir
70
294
  ? null
71
295
  : `a "${representation.domain}" scalar has no JSON.stringify/parse mapping`;
72
296
  case 'array-object':
73
- return jsonUnsupportedReason(deriver, representation.element, collected, visiting, direction);
297
+ return jsonUnsupportedReason(world, representation.element, collected, visiting, direction, inRecordPair);
74
298
  case 'record':
75
299
  case 'native-record-ref': {
76
300
  // A carrier whose struct the HOST declares has no compiler-emitted
@@ -109,7 +333,7 @@ const jsonUnsupportedReason = (deriver, representation, collected, visiting, dir
109
333
  return ('JSON has no date type, so nothing in a document decodes into a Date; `JSON.parse(text) as Date` asserts a shape the ' +
110
334
  'grammar cannot carry (node answers a string for it), and reviving one is the `reviver` parameter this backend does not implement');
111
335
  }
112
- if (visiting.size > 0) {
336
+ if (inRecordPair) {
113
337
  return ('a Date inside a record has no JSON mapping here: a record renders its write and read overloads as one pair, and ' +
114
338
  'the read half would have to decode a Date out of a document that has no date type. A Date serialized on its own, ' +
115
339
  'or as an array element, does render');
@@ -154,14 +378,17 @@ const jsonUnsupportedReason = (deriver, representation, collected, visiting, dir
154
378
  // element or a bare call argument does not, so `optional` anywhere
155
379
  // else falls through to the `default:` refusal below.
156
380
  const fieldRepresentation = field.value.kind === 'optional' && field.value.absence === 'undefined' ? field.value.payload : field.value;
157
- const reason = jsonUnsupportedReason(deriver, fieldRepresentation, collected, stillVisiting, direction);
381
+ const reason = jsonUnsupportedReason(world, fieldRepresentation, collected, stillVisiting, direction, true);
158
382
  if (reason)
159
383
  return `field "${field.key}" of record "${structName}": ${reason}`;
160
384
  }
161
385
  // Recorded only after every field resolved: a record that turns out to
162
386
  // be unsupported must not leave a partial entry another call site's
163
387
  // `collected.structs.has(structName)` short-circuit could mistake for done.
164
- collected.structs.set(structName, { structName, fields });
388
+ const layout = representation.kind === 'record' ? representation : deriver.layoutOf(representation.shapeId);
389
+ const accessors = layout.kind === 'record' ? layout.accessors.filter((accessor) => !cppRecordFieldKeyIsSymbol(accessor.key)) : [];
390
+ const tuple = deriver.isTupleShape(representation.shapeId);
391
+ collected.structs.set(structName, { structName, fields, accessors, tuple });
165
392
  return null;
166
393
  }
167
394
  case 'tagged-union': {
@@ -170,7 +397,7 @@ const jsonUnsupportedReason = (deriver, representation, collected, visiting, dir
170
397
  return ('representation kind "tagged-union" has no native JSON.stringify/parse mapping unless its arms are one JSON-carrying type ' +
171
398
  'plus `null` (optionally with `undefined` too); a wider sum has no discriminator in the document to decode back with');
172
399
  }
173
- const reason = jsonUnsupportedReason(deriver, arms.payload, collected, visiting, direction);
400
+ const reason = jsonUnsupportedReason(world, arms.payload, collected, visiting, direction, inRecordPair);
174
401
  if (reason !== null)
175
402
  return reason;
176
403
  const typeName = cppTypeOf(representation);
@@ -186,8 +413,10 @@ const jsonUnsupportedReason = (deriver, representation, collected, visiting, dir
186
413
  }
187
414
  return null;
188
415
  }
416
+ case 'class-ref':
417
+ return classJsonUnsupportedReason(world, representation, collected, visiting, direction, inRecordPair);
189
418
  default:
190
- // `dynamic`, `class-ref`, `record-with-index`, `dictionary`, `function`,
419
+ // `dynamic`, `record-with-index`, `dictionary`, `function`,
191
420
  // `promise`, and everything else this switch does not name above: none
192
421
  // has a native JSON mapping, and reaching for `gea_cpp_value` to give it
193
422
  // one anyway is exactly the boxing shortcut this compiler forbids (see
@@ -288,7 +517,71 @@ const isPlainAsciiKey = (key) => {
288
517
  return true;
289
518
  };
290
519
  /** The `gea_json_write(std::string&, const StructName&)` / `gea_json_read(gea::json::Reader&, StructName&)` overload pair for one record struct, walking its real fields -- never a boxed intermediate. */
520
+ /**
521
+ * The overload pair for a positional tuple struct: an Array to JSON.
522
+ *
523
+ * SerializeJSONArray writes every index below `length`, and an element that is
524
+ * `undefined` (or a function or symbol) as `null` -- the one place JSON spells
525
+ * `undefined` -- rather than omitting it as an object property would be. A
526
+ * tuple's `length` is its leading present slots (`gea_tupleLength()`), and
527
+ * only a trailing optional position can be absent, so an absent slot ends the
528
+ * array. The reader is the positional mirror: element N decodes into slot N.
529
+ */
530
+ const renderJsonTupleOverloads = (entry) => {
531
+ const writeLines = [`inline void gea_json_write(std::string& out, const ${entry.structName}& value) {`, ` out += '[';`];
532
+ const readLines = [
533
+ `inline void gea_json_read(gea::json::Reader& reader, ${entry.structName}& out) {`,
534
+ ` if (!reader.consumeIf('[')) {`,
535
+ ` reader.skipValue();`,
536
+ ` return;`,
537
+ ` }`,
538
+ ` if (reader.consumeIf(']')) return;`,
539
+ ` for (std::size_t gea_json_at = 0;; ++gea_json_at) {`,
540
+ ` switch (gea_json_at) {`
541
+ ];
542
+ let closes = 0;
543
+ for (const [index, field] of entry.fields.entries()) {
544
+ const member = tailAwareFieldReadText(entry.fields, field.key, 'value.');
545
+ const separator = index === 0 ? '' : ` out += ',';`;
546
+ if (!field.required) {
547
+ writeLines.push(` if (value.${cppRecordFieldPresenceName(field.key)}) {`);
548
+ closes += 1;
549
+ }
550
+ if (separator)
551
+ writeLines.push(separator);
552
+ const unionArms = nullableUnionArmsOf(field.value);
553
+ if (unionArms !== null && unionArms.undefinedIndex !== -1) {
554
+ writeLines.push(` if (${member}.is<${unionArms.undefinedIndex}>()) out += "null"; else gea_json_write(out, ${member});`);
555
+ }
556
+ else if (field.value.kind === 'optional' && (field.value.absence === 'undefined' || field.value.absence === 'null')) {
557
+ writeLines.push(` if (${member}.has_value()) gea_json_write(out, *${member}); else out += "null";`);
558
+ }
559
+ else {
560
+ writeLines.push(` gea_json_write(out, ${member});`);
561
+ }
562
+ const target = tailAwareFieldWriteText(entry.fields, field.key);
563
+ const optional = field.value.kind === 'optional' && (field.value.absence === 'undefined' || field.value.absence === 'null');
564
+ readLines.push(` case ${index}: {`);
565
+ if (optional) {
566
+ const payloadType = cppTypeOf(field.value.kind === 'optional' ? field.value.payload : field.value);
567
+ readLines.push(` if (!reader.consumeNull()) {`, ` ${payloadType} gea_json_element{};`, ` gea_json_read(reader, gea_json_element);`, ` out.${target} = gea_json_element;`, ` }`);
568
+ }
569
+ else {
570
+ readLines.push(` gea_json_read(reader, out.${target});`);
571
+ }
572
+ if (!field.required)
573
+ readLines.push(` out.${cppRecordFieldPresenceName(field.key)} = true;`);
574
+ readLines.push(` break;`, ` }`);
575
+ }
576
+ for (let close = 0; close < closes; close++)
577
+ writeLines.push(` }`);
578
+ writeLines.push(` out += ']';`, `}`);
579
+ readLines.push(` default:`, ` reader.skipValue();`, ` break;`, ` }`, ` if (!reader.advanceArray()) break;`, ` }`, `}`);
580
+ return `${writeLines.join('\n')}\n\n${readLines.join('\n')}`;
581
+ };
291
582
  const renderJsonRecordOverloads = (entry) => {
583
+ if (entry.tuple)
584
+ return renderJsonTupleOverloads(entry);
292
585
  // Whether the object's first property is known at GENERATION time. It is,
293
586
  // until a field that ECMA-262 25.5.2.2 may omit is reached -- and for a record
294
587
  // with no such field (every record in the corpus) the whole `gea_json_first`
@@ -301,7 +594,7 @@ const renderJsonRecordOverloads = (entry) => {
301
594
  return true;
302
595
  return field.value.kind === 'optional' && field.value.absence === 'undefined';
303
596
  };
304
- const anyOmittable = entry.fields.some(omittable);
597
+ const anyOmittable = entry.fields.some(omittable) || entry.accessors.length > 0;
305
598
  let staticFirst = true;
306
599
  const writeLines = [`inline void gea_json_write(std::string& out, const ${entry.structName}& value) {`, ` out += '{';`];
307
600
  if (anyOmittable)
@@ -309,7 +602,7 @@ const renderJsonRecordOverloads = (entry) => {
309
602
  // The body that reads ONE field's value, rendered once and used by both key
310
603
  // chains below.
311
604
  const readBodyOf = (field, indent) => {
312
- const target = cppRecordFieldName(field.key);
605
+ const target = tailAwareFieldWriteText(entry.fields, field.key);
313
606
  const optional = field.value.kind === 'optional' && (field.value.absence === 'undefined' || field.value.absence === 'null');
314
607
  if (!optional) {
315
608
  return [
@@ -318,6 +611,12 @@ const renderJsonRecordOverloads = (entry) => {
318
611
  ];
319
612
  }
320
613
  const payloadType = cppTypeOf(field.value.kind === 'optional' ? field.value.payload : field.value);
614
+ if (field.value.kind === 'optional' && field.value.absence === 'null') {
615
+ return [
616
+ `${indent}gea_json_read(reader, out.${target});`,
617
+ ...(!field.required ? [`${indent}out.${cppRecordFieldPresenceName(field.key)} = true;`] : [])
618
+ ];
619
+ }
321
620
  return [
322
621
  `${indent}${payloadType} gea_json_field{};`,
323
622
  `${indent}gea_json_read(reader, gea_json_field);`,
@@ -361,8 +660,40 @@ const renderJsonRecordOverloads = (entry) => {
361
660
  const inner = fastKeys ? ' ' : ' ';
362
661
  readLines.push(`${inner}if (!reader.nextKey(gea_json_key, gea_json_scratch)) break;`);
363
662
  let firstKey = true;
663
+ // An accessor's value is known only once its getter ran, so whether it is
664
+ // written (a getter answering `undefined` or a function is omitted) and
665
+ // hence the separator after it are run-time facts, like an omittable
666
+ // field's. The read goes through the struct's own-field hook, the one that
667
+ // already runs the getter for a boxed read, so the two cannot disagree.
668
+ const writeAccessorsAt = (position) => {
669
+ for (const accessor of entry.accessors) {
670
+ if ((accessor.precedingFields ?? entry.fields.length) !== position)
671
+ continue;
672
+ if (staticFirst !== null) {
673
+ if (!staticFirst)
674
+ writeLines.push(` gea_json_first = false;`);
675
+ staticFirst = null;
676
+ }
677
+ const presence = `value.${cppRecordFieldPresenceName(accessor.key)}`;
678
+ const attributes = `value.${cppRecordFieldAttributesName(accessor.key)}`;
679
+ writeLines.push(` if (${presence} && ${attributes}.enumerable) {`);
680
+ writeLines.push(` gea::Value gea_json_member;`);
681
+ writeLines.push(` if (!value.gea_readOwnField(gea::PropertyKey::string(${cppStringLiteral(accessor.key)}), gea_json_member)) ` +
682
+ `gea::host::throwRuntimeError("TypeError", "JSON.stringify could not read the accessor ${accessor.key}");`);
683
+ writeLines.push(` const auto gea_json_member_tag = gea_json_member.tag();`, ` if (gea_json_member_tag != gea::Value::Tag::Undefined && gea_json_member_tag != gea::Value::Tag::Function && gea_json_member_tag != gea::Value::Tag::Symbol) {`, ` if (!gea_json_first) out += ',';`, ` out += ${jsonKeyLiteral(accessor.key)};`, ` gea_json_write(out, gea_json_member);`, ` gea_json_first = false;`, ` }`, ` }`);
684
+ }
685
+ };
364
686
  for (const [index, field] of entry.fields.entries()) {
365
- const member = cppRecordFieldName(field.key);
687
+ writeAccessorsAt(index);
688
+ if (field.value.kind === 'undefined') {
689
+ // ECMA-262 25.5.2.5 omits a property whose value is `undefined`; one
690
+ // that can hold nothing else is never written, and is still matched
691
+ // (and skipped) when a document names it.
692
+ readLines.push(`${inner}${firstKey ? 'if' : 'else if'} (gea_json_key == ${cppStringLiteral(field.key)}) gea_json_which = ${index};`);
693
+ firstKey = false;
694
+ continue;
695
+ }
696
+ const member = tailAwareFieldReadText(entry.fields, field.key, 'value.');
366
697
  const keyLiteral = jsonKeyLiteral(field.key);
367
698
  // The read side compares the DECODED key text `nextKey` produced against
368
699
  // the field's own JS property name -- an ordinary C++ string literal, not
@@ -396,18 +727,18 @@ const renderJsonRecordOverloads = (entry) => {
396
727
  if (!field.required)
397
728
  writeLines.push(` if (value.${cppRecordFieldPresenceName(field.key)}) {`);
398
729
  if (undefinedArmIndex !== null) {
399
- writeLines.push(` if (!value.${member}.is<${undefinedArmIndex}>()) {`);
730
+ writeLines.push(` if (!${member}.is<${undefinedArmIndex}>()) {`);
400
731
  writeLines.push(` if (!gea_json_first) out += ',';`);
401
732
  writeLines.push(` out += ${keyLiteral};`);
402
- writeLines.push(` gea_json_write(out, value.${member});`);
733
+ writeLines.push(` gea_json_write(out, ${member});`);
403
734
  writeLines.push(` gea_json_first = false;`);
404
735
  writeLines.push(` }`);
405
736
  }
406
737
  else if (isOptionalUndefined) {
407
- writeLines.push(` if (value.${member}.has_value()) {`);
738
+ writeLines.push(` if (${member}.has_value()) {`);
408
739
  writeLines.push(` if (!gea_json_first) out += ',';`);
409
740
  writeLines.push(` out += ${keyLiteral};`);
410
- writeLines.push(` gea_json_write(out, *value.${member});`);
741
+ writeLines.push(` gea_json_write(out, *${member});`);
411
742
  writeLines.push(` gea_json_first = false;`);
412
743
  writeLines.push(` }`);
413
744
  }
@@ -417,7 +748,7 @@ const renderJsonRecordOverloads = (entry) => {
417
748
  if (!field.required)
418
749
  writeLines.push(` if (!gea_json_first) out += ',';`);
419
750
  writeLines.push(` out += ${foldedKey};`);
420
- writeLines.push(` if (value.${member}.has_value()) gea_json_write(out, *value.${member}); else out += "null";`);
751
+ writeLines.push(` if (${member}.has_value()) gea_json_write(out, *${member}); else out += "null";`);
421
752
  if (staticFirst === null)
422
753
  writeLines.push(` gea_json_first = false;`);
423
754
  }
@@ -425,7 +756,7 @@ const renderJsonRecordOverloads = (entry) => {
425
756
  if (!field.required)
426
757
  writeLines.push(` if (!gea_json_first) out += ',';`);
427
758
  writeLines.push(` out += ${foldedKey};`);
428
- writeLines.push(` gea_json_write(out, value.${member});`);
759
+ writeLines.push(` gea_json_write(out, ${member});`);
429
760
  if (staticFirst === null)
430
761
  writeLines.push(` gea_json_first = false;`);
431
762
  }
@@ -434,11 +765,26 @@ const renderJsonRecordOverloads = (entry) => {
434
765
  readLines.push(`${inner}${firstKey ? 'if' : 'else if'} (gea_json_key == ${keyComparisonLiteral}) gea_json_which = ${index};`);
435
766
  firstKey = false;
436
767
  }
768
+ writeAccessorsAt(entry.fields.length);
437
769
  if (fastKeys)
438
770
  readLines.push(` }`);
439
771
  readLines.push(` switch (gea_json_which) {`);
772
+ // A document may list the fields in any order, and its order is the
773
+ // parsed object's creation order. A field arriving after a later-declared
774
+ // one was already read is out of layout order, and only then does the
775
+ // record get a creation-order log (`noteNativeIndexKeyCreated`); a
776
+ // document in layout order pays a flag test per key. A repeated key keeps
777
+ // its first place, as 10.1.9 [[Set]] on an existing property does.
778
+ const ordered = entry.fields.length > 1;
779
+ if (ordered) {
780
+ const opening = readLines.indexOf(` for (;;) {`);
781
+ readLines.splice(opening, 0, ` bool gea_json_seen[${entry.fields.length}] = {};`, ` int gea_json_last = -1;`);
782
+ }
440
783
  entry.fields.forEach((field, at) => {
441
784
  readLines.push(` case ${at}: {`);
785
+ if (ordered)
786
+ readLines.push(` if (!gea_json_seen[${at}]) { gea_json_seen[${at}] = true; if (${at} < gea_json_last) ` +
787
+ `gea::detail::noteNativeIndexKeyCreated(&out, gea::PropertyKey::string(${cppStringLiteral(field.key)})); else gea_json_last = ${at}; }`);
442
788
  readLines.push(...readBodyOf(field, ' '));
443
789
  readLines.push(` break;`);
444
790
  readLines.push(` }`);
@@ -450,9 +796,13 @@ const renderJsonRecordOverloads = (entry) => {
450
796
  readLines.push(` if (!reader.advance()) break;`);
451
797
  readLines.push(` }`);
452
798
  readLines.push(`}`);
799
+ // The keys a record gains past its declared fields live in its expando
800
+ // sidecar, and JSON reads them too -- see `writeNativeExpandoMembers`.
801
+ const nothingWritten = staticFirst === null ? 'gea_json_first' : staticFirst ? 'true' : 'false';
802
+ writeLines.push(` gea::json::writeNativeExpandoMembers(out, &value, ${nothingWritten});`);
453
803
  writeLines.push(` out += '}';`);
454
804
  writeLines.push(`}`);
455
- return `${writeLines.join('\n')}\n\n${readLines.join('\n')}`;
805
+ return `${renderJsonMemberWriter(entry.structName, entry.fields)}\n\n${writeLines.join('\n')}\n\n${readLines.join('\n')}`;
456
806
  };
457
807
  /**
458
808
  * Every `JSON.stringify`/`JSON.parse` call site in `bodies`, found by walking
@@ -469,7 +819,26 @@ const renderJsonRecordOverloads = (entry) => {
469
819
  * emission-time bookkeeping. A `'call'` operation is then a JSON call when its
470
820
  * callee traces back to one such `'get'`.
471
821
  */
472
- const jsonRootsOf = (bodies) => {
822
+ /**
823
+ * What `JSON.stringify` writes for a class instance whose prototype chain
824
+ * answers `toJSON` with one statically known body: SerializeJSONProperty
825
+ * (ECMA-262 25.5.2.2 step 2) replaces the value with `toJSON(key)` before
826
+ * anything else looks at it, so the text is exactly the writer of that
827
+ * body's result. `classDirectMethodFor` declines an overridden key, so the
828
+ * body called is the one every instance of the carrier dispatches to. A
829
+ * `toJSON` that declares a parameter would receive the key -- `""` at the
830
+ * top level, not the `undefined` a direct no-argument call binds -- and is
831
+ * left to refuse.
832
+ */
833
+ const classToJsonOf = (layouts, representation) => {
834
+ if (representation.kind !== 'class-ref')
835
+ return null;
836
+ const direct = layouts?.classDirectMethodFor?.(representation.declaration, 'toJSON') ?? null;
837
+ if (direct === null || direct.absentParameters.length !== 0)
838
+ return null;
839
+ return { callable: direct.callable, result: direct.result };
840
+ };
841
+ const jsonRootsOf = (bodies, layouts) => {
473
842
  const sites = [];
474
843
  for (const body of bodies) {
475
844
  const constantTextOf = new Map();
@@ -512,8 +881,9 @@ const jsonRootsOf = (bodies) => {
512
881
  continue;
513
882
  if (member === 'stringify') {
514
883
  const argument = operation.arguments[0];
515
- if (argument)
516
- sites.push({ member, representation: argument.representation });
884
+ if (argument) {
885
+ sites.push({ member, representation: classToJsonOf(layouts, argument.representation)?.result ?? argument.representation });
886
+ }
517
887
  }
518
888
  else if (operation.result) {
519
889
  sites.push({ member, representation: operation.result.representation });
@@ -539,13 +909,28 @@ const jsonRootsOf = (bodies) => {
539
909
  * translation unit it belongs to is discarded whole, same as any other
540
910
  * refused body (`translation-unit.ts`'s `CppTranslationUnitResult.source`).
541
911
  */
542
- export const renderJsonStructDeclarations = (bodies, deriver) => {
912
+ export const renderJsonStructDeclarations = (bodies, deriver, layouts, classes, reactive) => {
543
913
  const collected = emptyJsonCollected();
544
- for (const site of jsonRootsOf(bodies)) {
545
- jsonUnsupportedReason(deriver, site.representation, collected, new Set(), site.member === 'stringify' ? 'write' : 'read');
914
+ const world = { deriver, classes, reactiveFields: reactive.cell === null ? null : reactive.fields };
915
+ for (const site of jsonRootsOf(bodies, layouts)) {
916
+ jsonUnsupportedReason(world, site.representation, collected, new Set(), site.member === 'stringify' ? 'write' : 'read');
546
917
  }
547
918
  const names = [...collected.structs.keys()].sort();
919
+ const classNames = [...collected.classes.keys()].sort();
548
920
  const unionNames = [...collected.nullableUnions.keys()].sort();
921
+ // A class writer names every member up its chain through the derived
922
+ // struct, so each struct of the chain is one whose member types it reads.
923
+ const classChainStructs = new Set();
924
+ for (const layout of classes.values()) {
925
+ if (!collected.classes.has(cppClassName(layout.declaration)))
926
+ continue;
927
+ const seen = new Set();
928
+ for (let current = layout; current !== undefined && !seen.has(current.declaration);) {
929
+ seen.add(current.declaration);
930
+ classChainStructs.add(cppClassName(current.declaration));
931
+ current = current.base === null ? undefined : classes.get(current.base);
932
+ }
933
+ }
549
934
  // Every pair is declared before any pair is defined. Required as soon as a
550
935
  // record's field reaches the record itself: the write body calls
551
936
  // `gea_json_write` on its own struct -- through `std::vector`'s template for
@@ -558,12 +943,15 @@ export const renderJsonStructDeclarations = (bodies, deriver) => {
558
943
  `inline void gea_json_write(std::string& out, const ${name}& value);`,
559
944
  `inline void gea_json_read(gea::json::Reader& reader, ${name}& out);`
560
945
  ]);
946
+ const classForwards = classNames.map((name) => `inline void gea_json_write(std::string& out, const ${name}& value);`);
561
947
  const declarations = [
562
948
  ...forwards,
949
+ ...classForwards,
563
950
  ...names.map((name) => renderJsonRecordOverloads(collected.structs.get(name))),
951
+ ...classNames.map((name) => renderJsonClassOverload(collected.classes.get(name))),
564
952
  ...unionNames.map((name) => renderJsonNullableUnionOverloads(collected.nullableUnions.get(name)))
565
953
  ];
566
- return { declarations, structNames: new Set(names) };
954
+ return { declarations, structNames: new Set([...names, ...classChainStructs]) };
567
955
  };
568
956
  /**
569
957
  * One `JSON.stringify`/`JSON.parse` call, rendered as a single C++ expression
@@ -629,16 +1017,78 @@ const boxedJsonArgumentText = (ctx, argument) => {
629
1017
  if (boxed === null)
630
1018
  return null;
631
1019
  const dynamic = { kind: 'dynamic', reason: 'declared-any-never-narrowed' };
632
- return jsonUnsupportedReason(ctx.deriver, dynamic, emptyJsonCollected(), new Set(), 'write') === null ? boxed : null;
1020
+ return jsonUnsupportedReason(jsonWorldOf(ctx), dynamic, emptyJsonCollected(), new Set(), 'write') === null ? boxed : null;
1021
+ };
1022
+ /**
1023
+ * The call-frame proof (`hostTemplateFrameOf`'s `json-stringify` arm) told
1024
+ * reflection demand this argument never crosses a dynamic boundary, so its
1025
+ * records were emitted with only the field reads the program names. Boxing it
1026
+ * would serialize through those pruned hooks and silently drop keys
1027
+ * (`{"b":[]}` for `{ a: 1, b: [] }`): the proof and this writer disagreeing is
1028
+ * a defect to refuse, never one to paper over with a box.
1029
+ */
1030
+ const refuseBoxingProvenDataTree = (ctx, operation, reason) => {
1031
+ if (hostTemplateFrameOf(operation, undefined, ctx.deriver, ctx.classes) !== true)
1032
+ return;
1033
+ throw createCppEmitBlockedError('host-member-call:JSON.stringify', `JSON.stringify's argument was proven a native data tree but has no native writer: ${reason}`);
1034
+ };
1035
+ /**
1036
+ * `JSON.stringify` whose result the program holds as `string | undefined`
1037
+ * (`structural.ts`'s `json-stringify-may-be-undefined`): a top-level value
1038
+ * with no JSON form -- `undefined`, a function, a symbol -- produces
1039
+ * `undefined` rather than any text (ECMA-262 25.5.2.1), where the writer on
1040
+ * its own would print `null`, the answer only an array element or a nested
1041
+ * position gets. `null` for a call this does not cover.
1042
+ */
1043
+ const absentWhenUnserializableText = (ctx, operation) => {
1044
+ const result = operation.result?.representation;
1045
+ if (result?.kind !== 'optional' || result.absence !== 'undefined' || result.payload.kind !== 'string')
1046
+ return null;
1047
+ if (operation.arguments.length !== 1)
1048
+ return null;
1049
+ const argument = operation.arguments[0];
1050
+ const resultType = cppTypeOf(result);
1051
+ const writeText = (value) => `std::string gea_json_out; gea_json_write(gea_json_out, ${value}); return ${resultType}(std::move(gea_json_out));`;
1052
+ const representation = argument.representation;
1053
+ const unsupported = representation.kind === 'dynamic'
1054
+ ? null
1055
+ : jsonUnsupportedReason(jsonWorldOf(ctx), representation, emptyJsonCollected(), new Set(), 'write');
1056
+ if (unsupported !== null)
1057
+ refuseBoxingProvenDataTree(ctx, operation, unsupported);
1058
+ const dynamicText = representation.kind === 'dynamic' ? operandText(ctx, argument) : unsupported !== null ? boxedJsonArgumentText(ctx, argument) : null;
1059
+ if (dynamicText !== null) {
1060
+ return (`[&]() -> ${resultType} { const gea::Value& gea_json_value = ${dynamicText}; const auto gea_json_tag = gea_json_value.tag(); ` +
1061
+ `if (gea_json_tag == gea::Value::Tag::Undefined || gea_json_tag == gea::Value::Tag::Function || gea_json_tag == gea::Value::Tag::Symbol) ` +
1062
+ `return ${resultType}(); ${writeText('gea_json_value')} }()`);
1063
+ }
1064
+ if (representation.kind === 'optional' && representation.absence === 'undefined') {
1065
+ return `[&]() -> ${resultType} { const auto& gea_json_value = ${operandText(ctx, argument)}; if (!gea_json_value.has_value()) return ${resultType}(); ${writeText('*gea_json_value')} }()`;
1066
+ }
1067
+ if (representation.kind === 'undefined')
1068
+ return `${resultType}()`;
1069
+ return null;
633
1070
  };
634
1071
  export const jsonCallText = (ctx, member, operation) => {
635
1072
  if (member === 'stringify') {
1073
+ const absentWhenUnserializable = absentWhenUnserializableText(ctx, operation);
1074
+ if (absentWhenUnserializable !== null)
1075
+ return absentWhenUnserializable;
636
1076
  if (operation.arguments.length < 1 || operation.arguments.length > 3) {
637
1077
  throw createCppEmitBlockedError('host-member-call:JSON.stringify', `JSON.stringify takes one to three arguments; this call passes ${operation.arguments.length}`);
638
1078
  }
639
1079
  const argument = operation.arguments[0];
640
- const reason = jsonUnsupportedReason(ctx.deriver, argument.representation, emptyJsonCollected(), new Set(), 'write');
1080
+ const toJson = operation.arguments.length === 1 ? classToJsonOf(ctx.layouts, argument.representation) : null;
1081
+ if (toJson !== null) {
1082
+ const reason = jsonUnsupportedReason(jsonWorldOf(ctx), toJson.result, emptyJsonCollected(), new Set(), 'write');
1083
+ if (reason !== null) {
1084
+ throw createCppEmitBlockedError('host-member-call:JSON.stringify', `JSON.stringify of a class instance writes its toJSON() result, which cannot be serialized natively: ${reason}`);
1085
+ }
1086
+ const replaced = `${cppBodyName(toJson.callable)}(${operandText(ctx, argument)})`;
1087
+ return `[&]() { std::string gea_json_out; gea_json_write(gea_json_out, ${replaced}); return gea_json_out; }()`;
1088
+ }
1089
+ const reason = jsonUnsupportedReason(jsonWorldOf(ctx), argument.representation, emptyJsonCollected(), new Set(), 'write');
641
1090
  if (reason !== null) {
1091
+ refuseBoxingProvenDataTree(ctx, operation, reason);
642
1092
  const boxed = operation.arguments.length === 1 ? boxedJsonArgumentText(ctx, argument) : null;
643
1093
  if (boxed !== null)
644
1094
  return `[&]() { std::string gea_json_out; gea_json_write(gea_json_out, ${boxed}); return gea_json_out; }()`;
@@ -715,20 +1165,110 @@ export const jsonCallText = (ctx, member, operation) => {
715
1165
  }
716
1166
  return `[&]() { std::string gea_json_out; gea_json_write(gea_json_out, ${valueText}); return gea_json_out; }()`;
717
1167
  }
1168
+ if (operation.arguments.length === 2)
1169
+ return jsonParseWithReviverText(ctx, operation);
718
1170
  if (operation.arguments.length !== 1) {
719
- throw createCppEmitBlockedError('host-member-call:JSON.parse', `JSON.parse's "reviver" parameter is not implemented (this call passes ${operation.arguments.length} argument(s); only the single-argument form is)`);
1171
+ throw createCppEmitBlockedError('host-member-call:JSON.parse', `JSON.parse takes one or two arguments; this call passes ${operation.arguments.length}`);
720
1172
  }
721
1173
  if (operation.result === null) {
722
1174
  throw createCppEmitBlockedError('host-member-call:JSON.parse', 'this JSON.parse result is discarded; this backend only renders a parse whose value is used somewhere');
723
1175
  }
724
1176
  const resultRepresentation = operation.result.representation;
725
- const reason = jsonUnsupportedReason(ctx.deriver, resultRepresentation, emptyJsonCollected(), new Set(), 'read');
1177
+ const reason = jsonUnsupportedReason(jsonWorldOf(ctx), resultRepresentation, emptyJsonCollected(), new Set(), 'read');
726
1178
  if (reason !== null)
727
1179
  throw createCppEmitBlockedError('host-member-call:JSON.parse', `JSON.parse cannot decode natively into this asserted type: ${reason}`);
728
- const textArgument = operandText(ctx, operation.arguments[0]);
1180
+ const textOperand = operation.arguments[0];
1181
+ const textArgument = operandText(ctx, textOperand);
729
1182
  const resultType = cppTypeOf(resultRepresentation);
1183
+ // `JSON.stringify(x)` is typed `string` and answers `undefined` for a value
1184
+ // JSON cannot represent, so its carrier here is `optional(string)`. Feeding
1185
+ // that to `JSON.parse` is ToString(undefined) = "undefined", which is not
1186
+ // JSON: the parse throws its SyntaxError, as it does for any other
1187
+ // malformed text.
1188
+ if (textOperand.representation.kind === 'optional' && textOperand.representation.payload.kind === 'string') {
1189
+ const text = 'gea_json_arg.has_value() ? std::string(*gea_json_arg) : std::string("undefined")';
1190
+ return (`[&]() { const auto& gea_json_arg = ${textArgument}; const std::string gea_json_text = ${text}; ` +
1191
+ `gea::json::Reader gea_json_reader(gea_json_text); ${resultType} gea_json_result{}; ` +
1192
+ `gea_json_read(gea_json_reader, gea_json_result); gea_json_reader.finish(); return gea_json_result; }()`);
1193
+ }
730
1194
  return `[&]() { const std::string& gea_json_text = ${textArgument}; gea::json::Reader gea_json_reader(gea_json_text); ${resultType} gea_json_result{}; gea_json_read(gea_json_reader, gea_json_result); gea_json_reader.finish(); return gea_json_result; }()`;
731
1195
  };
1196
+ /**
1197
+ * `JSON.parse(text, reviver)`, ECMA-262 25.5.1 with InternalizeJSONProperty
1198
+ * (`gea::json::parseWithReviver`).
1199
+ *
1200
+ * The reviver sees and answers every value of the parsed tree, so the tree it
1201
+ * walks is the parse's own dynamic one and the call's result is that dynamic
1202
+ * value: admitted only where the program reads the result as the genuinely
1203
+ * dynamic carrier (`any`). A typed decode (`JSON.parse(t, r) as T`) would need
1204
+ * the revived tree converted to `T`, which this does not do -- refused by name.
1205
+ *
1206
+ * The reviver must be ONE callable arm (a nullish arm parses without reviving,
1207
+ * as the language does for a non-callable reviver) whose convention takes the
1208
+ * key as a string and the value, and answers, as the dynamic carrier: the
1209
+ * declared `(this: any, key: string, value: any) => any`. A reviver whose
1210
+ * parameters or result the program narrowed to a static type would need a
1211
+ * checked conversion at each call; that is not rendered here.
1212
+ */
1213
+ const jsonParseWithReviverText = (ctx, operation) => {
1214
+ if (operation.result === null) {
1215
+ throw createCppEmitBlockedError('host-member-call:JSON.parse', 'this JSON.parse result is discarded; this backend only renders a parse whose value is used somewhere');
1216
+ }
1217
+ if (operation.result.representation.kind !== 'dynamic') {
1218
+ throw createCppEmitBlockedError('host-member-call:JSON.parse', `JSON.parse with a reviver answers the revived dynamic tree, and this call's result carries "${representationKey(operation.result.representation)}"`);
1219
+ }
1220
+ const text = operation.arguments[0];
1221
+ const reviver = operation.arguments[1];
1222
+ if (text.representation.kind !== 'string') {
1223
+ throw createCppEmitBlockedError('host-member-call:JSON.parse', `JSON.parse's text carries "${representationKey(text.representation)}"; only a string is rendered with a reviver`);
1224
+ }
1225
+ const leaves = [];
1226
+ const collect = (representation, at, conditions) => {
1227
+ if (representation.kind === 'optional') {
1228
+ collect(representation.payload, `(*(${at}))`, [...conditions, `(${at}).has_value()`]);
1229
+ return;
1230
+ }
1231
+ if (representation.kind === 'tagged-union') {
1232
+ representation.arms.forEach((arm, index) => collect(arm.value, armAt(at, index), [...conditions, armIs(at, index)]));
1233
+ return;
1234
+ }
1235
+ leaves.push({ condition: conditions.length === 0 ? 'true' : conditions.join(' && '), text: at, representation });
1236
+ };
1237
+ collect(reviver.representation, '__gea_reviver', []);
1238
+ const callable = leaves.filter((leaf) => leaf.representation.kind === 'function-value-dispatch');
1239
+ const invalid = leaves.filter((leaf) => leaf.representation.kind !== 'function-value-dispatch' &&
1240
+ leaf.representation.kind !== 'null' &&
1241
+ leaf.representation.kind !== 'undefined');
1242
+ if (callable.length !== 1 || invalid.length !== 0) {
1243
+ throw createCppEmitBlockedError('host-member-call:JSON.parse', `JSON.parse reviver carries "${representationKey(reviver.representation)}"; expected one callable arm, optionally beside null or undefined`);
1244
+ }
1245
+ const selected = callable[0];
1246
+ const abi = selected.representation.abi;
1247
+ const parameterKinds = abi.parameters.map((parameter) => parameter.value.kind);
1248
+ // The answer lands in the dynamic tree: lib declares it `any`, so a reviver
1249
+ // whose body the checker typed narrower (`(k, v) => \`${k}:${v}\``) widens
1250
+ // into the dynamic carrier exactly as any store of that type into `any` does.
1251
+ const invoked = (text) => (abi.result.kind === 'dynamic' ? text : dynamicCarrierBoxText(abi.result, text));
1252
+ const conventional = abi.restFrom === null &&
1253
+ invoked('__gea_answer') !== null &&
1254
+ (abi.receiver === null || abi.receiver.kind === 'dynamic') &&
1255
+ parameterKinds.length <= 2 &&
1256
+ (parameterKinds[0] === undefined || parameterKinds[0] === 'string') &&
1257
+ (parameterKinds[1] === undefined || parameterKinds[1] === 'dynamic');
1258
+ if (!conventional) {
1259
+ throw createCppEmitBlockedError('host-member-call:JSON.parse', `JSON.parse reviver's convention "${representationKey(selected.representation)}" is not (this: any, key: string, value: any) => any`);
1260
+ }
1261
+ const argumentsText = ['__gea_key', '__gea_member'].slice(0, parameterKinds.length);
1262
+ const invoke = `__gea_callable.call(${[...(abi.receiver === null ? [] : ['__gea_holder']), ...argumentsText].join(', ')})`;
1263
+ const answer = abi.result.kind === 'dynamic' ? `return ${invoke};` : `const auto __gea_answer = ${invoke}; return ${invoked('__gea_answer')};`;
1264
+ const plain = `[&]() { gea::json::Reader gea_json_reader(__gea_text); gea::Value gea_json_result = gea_json_reader.readDynamicValue(); gea_json_reader.finish(); return gea_json_result; }()`;
1265
+ return (`([&]() -> gea::Value { const std::string& __gea_text = ${operandText(ctx, text)}; const auto& __gea_reviver = ${operandText(ctx, reviver)}; ` +
1266
+ `if (${selected.condition}) { const auto& __gea_callable = ${selected.text}; ` +
1267
+ `return gea::json::parseWithReviver(__gea_text, ` +
1268
+ `[&](const gea::Value& __gea_holder, const std::string& __gea_key, const gea::Value& __gea_member) -> gea::Value { ` +
1269
+ `(void)__gea_holder; (void)__gea_key; (void)__gea_member; ${answer} }); } ` +
1270
+ `return ${plain}; })()`);
1271
+ };
732
1272
  /**
733
1273
  * `JSON.stringify(v)` written straight into the cell that receives it, as
734
1274
  * whole statements, instead of into a temporary the following write copies out
@@ -791,7 +1331,7 @@ export const jsonStringifyFillLines = (ctx, operation) => {
791
1331
  if (placement.storage.kind !== 'local' && placement.storage.kind !== 'region')
792
1332
  return null;
793
1333
  const argument = operation.arguments[0];
794
- const reason = jsonUnsupportedReason(ctx.deriver, argument.representation, emptyJsonCollected(), new Set(), 'write');
1334
+ const reason = jsonUnsupportedReason(jsonWorldOf(ctx), argument.representation, emptyJsonCollected(), new Set(), 'write');
795
1335
  if (reason !== null) {
796
1336
  // The expression form serializes the boxed value instead (`jsonCallText`).
797
1337
  if (boxedJsonArgumentText(ctx, argument) !== null)
@@ -799,7 +1339,7 @@ export const jsonStringifyFillLines = (ctx, operation) => {
799
1339
  throw createCppEmitBlockedError('host-member-call:JSON.stringify', `JSON.stringify cannot serialize this argument natively: ${reason}`);
800
1340
  }
801
1341
  const cell = bindingReference(ctx, declaration, 'a JSON.stringify written in place');
802
- if (cell.boxed)
1342
+ if (cell.boxed || cell.frame === true)
803
1343
  return null;
804
1344
  const target = cellValueText(cell);
805
1345
  if (readsCell(ctx, argument.value, declaration))