@geastack/compiler 1.0.20 → 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 (534) 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/render-bridge.d.ts +4 -2
  146. package/dist/plugins/gea/render-bridge.js +23 -7
  147. package/dist/plugins/model.d.ts +2 -0
  148. package/dist/project-preparation.d.ts +5 -1
  149. package/dist/project-preparation.js +164 -7
  150. package/dist/projection/bindings.d.ts +5 -2
  151. package/dist/projection/bindings.js +40 -1
  152. package/dist/projection/callee.d.ts +16 -0
  153. package/dist/projection/callee.js +35 -6
  154. package/dist/projection/class-prototype.js +5 -1
  155. package/dist/projection/classes.d.ts +65 -2
  156. package/dist/projection/classes.js +159 -2
  157. package/dist/projection/dispatch.d.ts +69 -18
  158. package/dist/projection/dispatch.js +391 -19
  159. package/dist/projection/fields.d.ts +4 -3
  160. package/dist/projection/fields.js +89 -21
  161. package/dist/projection/instance-test.d.ts +12 -0
  162. package/dist/projection/instance-test.js +40 -10
  163. package/dist/projection/method-value-escapes.d.ts +43 -0
  164. package/dist/projection/method-value-escapes.js +113 -0
  165. package/dist/projection/slots.d.ts +34 -1
  166. package/dist/projection/slots.js +82 -5
  167. package/dist/representation/any-null-record-members.d.ts +41 -0
  168. package/dist/representation/any-null-record-members.js +115 -0
  169. package/dist/representation/collections.d.ts +3 -1
  170. package/dist/representation/collections.js +5 -2
  171. package/dist/representation/derive.d.ts +9 -1
  172. package/dist/representation/derive.js +366 -25
  173. package/dist/representation/difference.js +14 -0
  174. package/dist/representation/embedded-carriers.js +1 -0
  175. package/dist/representation/host-abi.d.ts +15 -0
  176. package/dist/representation/host-abi.js +28 -0
  177. package/dist/representation/host-templates.d.ts +1 -1
  178. package/dist/representation/host-templates.js +7 -3
  179. package/dist/representation/intersection.js +22 -0
  180. package/dist/representation/json-nullable.d.ts +18 -0
  181. package/dist/representation/json-nullable.js +22 -0
  182. package/dist/representation/model.d.ts +141 -0
  183. package/dist/representation/model.js +47 -3
  184. package/dist/representation/object-shape.d.ts +5 -1
  185. package/dist/representation/object-shape.js +5 -2
  186. package/dist/representation/policies.d.ts +66 -1
  187. package/dist/representation/proxy-carriers.d.ts +71 -0
  188. package/dist/representation/proxy-carriers.js +330 -0
  189. package/dist/representation/publish.d.ts +9 -1
  190. package/dist/representation/publish.js +186 -18
  191. package/dist/representation/record-fields.d.ts +5 -0
  192. package/dist/representation/record-fields.js +7 -1
  193. package/dist/representation/static-field-cells.d.ts +61 -0
  194. package/dist/representation/static-field-cells.js +80 -0
  195. package/dist/representation/unassigned-binding-cells.d.ts +32 -0
  196. package/dist/representation/unassigned-binding-cells.js +44 -0
  197. package/dist/representation/union.js +17 -1
  198. package/dist/representation/unwritten-record-members.d.ts +54 -0
  199. package/dist/representation/unwritten-record-members.js +167 -0
  200. package/dist/representation/value-records.js +153 -11
  201. package/dist/semantics/ambient.d.ts +102 -0
  202. package/dist/semantics/ambient.js +183 -0
  203. package/dist/semantics/any-null-member-declarations.d.ts +32 -0
  204. package/dist/semantics/any-null-member-declarations.js +90 -0
  205. package/dist/semantics/borrowed-builtin-call-bind-source-transform.js +14 -0
  206. package/dist/semantics/borrowed-method-receiver-copy-source-transform.d.ts +51 -0
  207. package/dist/semantics/borrowed-method-receiver-copy-source-transform.js +367 -0
  208. package/dist/semantics/call-invalidated-narrowing.d.ts +3 -0
  209. package/dist/semantics/call-invalidated-narrowing.js +715 -0
  210. package/dist/semantics/callable-origins.d.ts +39 -0
  211. package/dist/semantics/callable-origins.js +73 -2
  212. package/dist/semantics/class-alias.d.ts +21 -0
  213. package/dist/semantics/class-alias.js +45 -14
  214. package/dist/semantics/class-heritage.d.ts +64 -0
  215. package/dist/semantics/class-heritage.js +278 -2
  216. package/dist/semantics/commonjs-wrapper.d.ts +1 -1
  217. package/dist/semantics/commonjs-wrapper.js +24 -7
  218. package/dist/semantics/constructor-function-class-source-transform.d.ts +4 -0
  219. package/dist/semantics/constructor-function-class-source-transform.js +327 -0
  220. package/dist/semantics/constructor-slot-subclasses.js +163 -4
  221. package/dist/semantics/declaration-overlay-transform.js +197 -3
  222. package/dist/semantics/frontend.d.ts +31 -0
  223. package/dist/semantics/frontend.js +177 -19
  224. package/dist/semantics/host-methods.d.ts +27 -2
  225. package/dist/semantics/host-methods.js +57 -4
  226. package/dist/semantics/host-protocols.d.ts +19 -8
  227. package/dist/semantics/host-protocols.js +145 -31
  228. package/dist/semantics/interface-families.d.ts +51 -2
  229. package/dist/semantics/interface-families.js +609 -23
  230. package/dist/semantics/interface-implementors.d.ts +20 -0
  231. package/dist/semantics/interface-implementors.js +130 -6
  232. package/dist/semantics/known-caller-predicate-parameters.d.ts +2 -0
  233. package/dist/semantics/known-caller-predicate-parameters.js +161 -0
  234. package/dist/semantics/model/intrinsic-accessor-getters.d.ts +10 -0
  235. package/dist/semantics/model/intrinsic-accessor-getters.js +4 -0
  236. package/dist/semantics/model/operands.d.ts +10 -0
  237. package/dist/semantics/model/operations.d.ts +107 -0
  238. package/dist/semantics/model/selected-signature.d.ts +33 -0
  239. package/dist/semantics/model/structural-type-table.d.ts +15 -0
  240. package/dist/semantics/model/structural-type-table.js +19 -1
  241. package/dist/semantics/model/structural-types.d.ts +99 -0
  242. package/dist/semantics/model/structural-types.js +31 -2
  243. package/dist/semantics/normalize/absent-globals.d.ts +1 -1
  244. package/dist/semantics/normalize/absent-globals.js +3 -3
  245. package/dist/semantics/normalize/bivariant-slot-parameter.d.ts +46 -0
  246. package/dist/semantics/normalize/bivariant-slot-parameter.js +357 -0
  247. package/dist/semantics/normalize/callback-parameter-contracts.d.ts +2 -0
  248. package/dist/semantics/normalize/callback-parameter-contracts.js +21 -0
  249. package/dist/semantics/normalize/census.d.ts +2 -1
  250. package/dist/semantics/normalize/census.js +25 -2
  251. package/dist/semantics/normalize/class-instance-record-statement.d.ts +37 -0
  252. package/dist/semantics/normalize/class-instance-record-statement.js +74 -0
  253. package/dist/semantics/normalize/collection-bindings.js +242 -5
  254. package/dist/semantics/normalize/commonjs-require.d.ts +26 -0
  255. package/dist/semantics/normalize/commonjs-require.js +355 -121
  256. package/dist/semantics/normalize/dead-event-emissions.d.ts +6 -0
  257. package/dist/semantics/normalize/dead-event-emissions.js +866 -0
  258. package/dist/semantics/normalize/dead-method-copies.d.ts +56 -0
  259. package/dist/semantics/normalize/dead-method-copies.js +239 -0
  260. package/dist/semantics/normalize/derived-expression-type.d.ts +149 -2
  261. package/dist/semantics/normalize/derived-expression-type.js +418 -14
  262. package/dist/semantics/normalize/field-bindings.js +139 -4
  263. package/dist/semantics/normalize/flow/callable-reach.js +162 -9
  264. package/dist/semantics/normalize/flow/member-call-forwarding.js +6 -0
  265. package/dist/semantics/normalize/flow/owned-class-receivers.js +40 -2
  266. package/dist/semantics/normalize/flow/source-class-data.d.ts +7 -1
  267. package/dist/semantics/normalize/flow/source-class-data.js +28 -9
  268. package/dist/semantics/normalize/flow/source-value-session.js +32 -13
  269. package/dist/semantics/normalize/flow/targets.d.ts +32 -0
  270. package/dist/semantics/normalize/flow/targets.js +65 -6
  271. package/dist/semantics/normalize/flow/value-flow.d.ts +7 -0
  272. package/dist/semantics/normalize/flow/value-flow.js +30 -2
  273. package/dist/semantics/normalize/fresh-array-result.d.ts +32 -0
  274. package/dist/semantics/normalize/fresh-array-result.js +125 -0
  275. package/dist/semantics/normalize/gating.js +2 -0
  276. package/dist/semantics/normalize/global-host-mutations.d.ts +11 -1
  277. package/dist/semantics/normalize/global-host-mutations.js +691 -27
  278. package/dist/semantics/normalize/host-effect-contracts.d.ts +43 -1
  279. package/dist/semantics/normalize/host-effect-contracts.js +60 -3
  280. package/dist/semantics/normalize/identities.js +49 -3
  281. package/dist/semantics/normalize/intrinsic-accessor-getter.d.ts +59 -0
  282. package/dist/semantics/normalize/intrinsic-accessor-getter.js +129 -0
  283. package/dist/semantics/normalize/local-bindings.js +117 -21
  284. package/dist/semantics/normalize/merged-declaration.d.ts +41 -0
  285. package/dist/semantics/normalize/merged-declaration.js +81 -0
  286. package/dist/semantics/normalize/never-override-result.d.ts +21 -0
  287. package/dist/semantics/normalize/never-override-result.js +64 -0
  288. package/dist/semantics/normalize/null-blind-parameter.d.ts +21 -0
  289. package/dist/semantics/normalize/null-blind-parameter.js +77 -0
  290. package/dist/semantics/normalize/object-bag-bindings.js +10 -0
  291. package/dist/semantics/normalize/override-field-arms.d.ts +33 -0
  292. package/dist/semantics/normalize/override-field-arms.js +362 -0
  293. package/dist/semantics/normalize/parameter-bindings.d.ts +64 -1
  294. package/dist/semantics/normalize/parameter-bindings.js +801 -81
  295. package/dist/semantics/normalize/parameter-slot.d.ts +1 -0
  296. package/dist/semantics/normalize/parameter-slot.js +69 -0
  297. package/dist/semantics/normalize/physical-overload-result.d.ts +45 -0
  298. package/dist/semantics/normalize/physical-overload-result.js +132 -0
  299. package/dist/semantics/normalize/producer-context.d.ts +23 -0
  300. package/dist/semantics/normalize/producers/allocations.d.ts +13 -0
  301. package/dist/semantics/normalize/producers/allocations.js +8 -15
  302. package/dist/semantics/normalize/producers/binding-kind.d.ts +11 -0
  303. package/dist/semantics/normalize/producers/binding-kind.js +31 -0
  304. package/dist/semantics/normalize/producers/bindings.js +16 -1
  305. package/dist/semantics/normalize/producers/boundary.js +21 -1
  306. package/dist/semantics/normalize/producers/class-lifecycle.js +23 -14
  307. package/dist/semantics/normalize/producers/computations.js +8 -67
  308. package/dist/semantics/normalize/producers/control-loops.d.ts +1 -1
  309. package/dist/semantics/normalize/producers/control-loops.js +25 -1
  310. package/dist/semantics/normalize/producers/control.js +87 -60
  311. package/dist/semantics/normalize/producers/declaration-lifecycle.js +5 -0
  312. package/dist/semantics/normalize/producers/enums.d.ts +10 -0
  313. package/dist/semantics/normalize/producers/enums.js +169 -0
  314. package/dist/semantics/normalize/producers/erasure.d.ts +10 -0
  315. package/dist/semantics/normalize/producers/erasure.js +23 -0
  316. package/dist/semantics/normalize/producers/intrinsic-accessor-getter.d.ts +15 -0
  317. package/dist/semantics/normalize/producers/intrinsic-accessor-getter.js +33 -0
  318. package/dist/semantics/normalize/producers/invocations.js +255 -18
  319. package/dist/semantics/normalize/producers/iteration-yield.js +6 -1
  320. package/dist/semantics/normalize/producers/logical-merge-type.d.ts +36 -0
  321. package/dist/semantics/normalize/producers/logical-merge-type.js +163 -0
  322. package/dist/semantics/normalize/producers/properties.js +207 -18
  323. package/dist/semantics/normalize/producers/protocol.d.ts +4 -0
  324. package/dist/semantics/normalize/producers/protocol.js +147 -12
  325. package/dist/semantics/normalize/producers/references.js +50 -9
  326. package/dist/semantics/normalize/producers/shared.d.ts +120 -0
  327. package/dist/semantics/normalize/producers/shared.js +359 -10
  328. package/dist/semantics/normalize/producers/spread-arguments.js +85 -4
  329. package/dist/semantics/normalize/producers/tuple-spread.d.ts +1 -0
  330. package/dist/semantics/normalize/producers/tuple-spread.js +1 -1
  331. package/dist/semantics/normalize/property-key-domain.js +6 -0
  332. package/dist/semantics/normalize/reachability.d.ts +7 -0
  333. package/dist/semantics/normalize/reachability.js +166 -9
  334. package/dist/semantics/normalize/record-home-arms.d.ts +25 -0
  335. package/dist/semantics/normalize/record-home-arms.js +87 -0
  336. package/dist/semantics/normalize/record-link-families.d.ts +74 -0
  337. package/dist/semantics/normalize/record-link-families.js +327 -0
  338. package/dist/semantics/normalize/record-stand-in-arms.d.ts +56 -0
  339. package/dist/semantics/normalize/record-stand-in-arms.js +484 -0
  340. package/dist/semantics/normalize/return-bindings.d.ts +6 -2
  341. package/dist/semantics/normalize/return-bindings.js +60 -7
  342. package/dist/semantics/normalize/script-global-redefinition.js +5 -0
  343. package/dist/semantics/normalize/shared-array-storage.d.ts +42 -0
  344. package/dist/semantics/normalize/shared-array-storage.js +373 -0
  345. package/dist/semantics/normalize/sloppy-absence.d.ts +41 -0
  346. package/dist/semantics/normalize/sloppy-absence.js +199 -0
  347. package/dist/semantics/normalize/specialization.d.ts +40 -0
  348. package/dist/semantics/normalize/specialization.js +770 -36
  349. package/dist/semantics/normalize/structural-array-element.js +196 -6
  350. package/dist/semantics/normalize/structural-array-read.js +12 -0
  351. package/dist/semantics/normalize/structural-creation-order.d.ts +15 -0
  352. package/dist/semantics/normalize/structural-creation-order.js +51 -48
  353. package/dist/semantics/normalize/structural-declarations.d.ts +16 -0
  354. package/dist/semantics/normalize/structural-declarations.js +43 -0
  355. package/dist/semantics/normalize/structural-generics.d.ts +13 -0
  356. package/dist/semantics/normalize/structural-generics.js +22 -0
  357. package/dist/semantics/normalize/structural-indexed-access.js +16 -0
  358. package/dist/semantics/normalize/structural-instantiated-member.js +68 -2
  359. package/dist/semantics/normalize/structural-joins.js +2 -0
  360. package/dist/semantics/normalize/structural-layout-relevance.d.ts +30 -0
  361. package/dist/semantics/normalize/structural-layout-relevance.js +164 -0
  362. package/dist/semantics/normalize/structural-layout-type.js +270 -14
  363. package/dist/semantics/normalize/structural-leaves.d.ts +1 -1
  364. package/dist/semantics/normalize/structural-leaves.js +17 -3
  365. package/dist/semantics/normalize/structural-mutable-method.js +5 -1
  366. package/dist/semantics/normalize/structural-parts.d.ts +18 -5
  367. package/dist/semantics/normalize/structural-parts.js +68 -19
  368. package/dist/semantics/normalize/structural-receiver.d.ts +1 -1
  369. package/dist/semantics/normalize/structural-receiver.js +23 -1
  370. package/dist/semantics/normalize/structural-self-reference.d.ts +1 -1
  371. package/dist/semantics/normalize/structural-self-reference.js +23 -2
  372. package/dist/semantics/normalize/structural.d.ts +12 -1
  373. package/dist/semantics/normalize/structural.js +1420 -53
  374. package/dist/semantics/normalize/suppressed-write-arms.d.ts +47 -0
  375. package/dist/semantics/normalize/suppressed-write-arms.js +393 -0
  376. package/dist/semantics/normalize/unresolvable-names.d.ts +15 -2
  377. package/dist/semantics/normalize/unresolvable-names.js +30 -6
  378. package/dist/semantics/normalize/unshared-array-result.d.ts +32 -0
  379. package/dist/semantics/normalize/unshared-array-result.js +125 -0
  380. package/dist/semantics/package-sources.d.ts +1 -1
  381. package/dist/semantics/package-sources.js +120 -8
  382. package/dist/semantics/program.d.ts +20 -0
  383. package/dist/semantics/program.js +145 -14
  384. package/dist/semantics/stable-checker.d.ts +1 -1
  385. package/dist/semantics/stable-checker.js +7 -2
  386. package/dist/semantics/unchecked-guard-argument-copies.d.ts +67 -0
  387. package/dist/semantics/unchecked-guard-argument-copies.js +163 -0
  388. package/dist/semantics/unchecked-write-member-declarations.d.ts +46 -0
  389. package/dist/semantics/unchecked-write-member-declarations.js +331 -0
  390. package/dist/targets/cpp/balanced-units.d.ts +31 -0
  391. package/dist/targets/cpp/balanced-units.js +57 -0
  392. package/dist/targets/cpp/borrowed-arm-projections.d.ts +31 -0
  393. package/dist/targets/cpp/borrowed-arm-projections.js +106 -0
  394. package/dist/targets/cpp/borrowed-call-entry.d.ts +1 -1
  395. package/dist/targets/cpp/borrowed-call-entry.js +24 -20
  396. package/dist/targets/cpp/captures.js +314 -8
  397. package/dist/targets/cpp/char-code-buffers.d.ts +36 -0
  398. package/dist/targets/cpp/char-code-buffers.js +214 -0
  399. package/dist/targets/cpp/class-layout.d.ts +7 -1
  400. package/dist/targets/cpp/class-layout.js +42 -17
  401. package/dist/targets/cpp/class-properties/computed-method-value.d.ts +17 -2
  402. package/dist/targets/cpp/class-properties/computed-method-value.js +50 -4
  403. package/dist/targets/cpp/class-properties/emit-class-properties.d.ts +31 -1
  404. package/dist/targets/cpp/class-properties/emit-class-properties.js +174 -17
  405. package/dist/targets/cpp/class-ref-transport.d.ts +32 -0
  406. package/dist/targets/cpp/class-ref-transport.js +56 -1
  407. package/dist/targets/cpp/conversions.js +1827 -1502
  408. package/dist/targets/cpp/coroutine-bodies.d.ts +97 -0
  409. package/dist/targets/cpp/coroutine-bodies.js +187 -0
  410. package/dist/targets/cpp/document.js +11 -1
  411. package/dist/targets/cpp/emit-allocation.js +535 -21
  412. package/dist/targets/cpp/emit-arrays.d.ts +10 -0
  413. package/dist/targets/cpp/emit-arrays.js +147 -16
  414. package/dist/targets/cpp/emit-binding-reference.d.ts +26 -2
  415. package/dist/targets/cpp/emit-binding-reference.js +97 -5
  416. package/dist/targets/cpp/emit-bindings.d.ts +9 -1
  417. package/dist/targets/cpp/emit-bindings.js +108 -8
  418. package/dist/targets/cpp/emit-buffers.d.ts +2 -16
  419. package/dist/targets/cpp/emit-buffers.js +124 -25
  420. package/dist/targets/cpp/emit-callable.d.ts +35 -72
  421. package/dist/targets/cpp/emit-callable.js +647 -82
  422. package/dist/targets/cpp/emit-carrier-members.d.ts +13 -2
  423. package/dist/targets/cpp/emit-carrier-members.js +50 -9
  424. package/dist/targets/cpp/emit-constructor-identity-family.d.ts +20 -0
  425. package/dist/targets/cpp/emit-constructor-identity-family.js +45 -0
  426. package/dist/targets/cpp/emit-context.d.ts +329 -15
  427. package/dist/targets/cpp/emit-context.js +104 -13
  428. package/dist/targets/cpp/emit-dynamic-properties.d.ts +44 -0
  429. package/dist/targets/cpp/emit-dynamic-properties.js +256 -37
  430. package/dist/targets/cpp/emit-equality.js +117 -2
  431. package/dist/targets/cpp/emit-error-constructor.d.ts +19 -0
  432. package/dist/targets/cpp/emit-error-constructor.js +73 -0
  433. package/dist/targets/cpp/emit-exceptions.d.ts +25 -3
  434. package/dist/targets/cpp/emit-exceptions.js +215 -26
  435. package/dist/targets/cpp/emit-in.js +52 -5
  436. package/dist/targets/cpp/emit-instanceof.js +59 -11
  437. package/dist/targets/cpp/emit-integers.d.ts +6 -0
  438. package/dist/targets/cpp/emit-integers.js +10 -0
  439. package/dist/targets/cpp/emit-iterable-object-view.d.ts +15 -0
  440. package/dist/targets/cpp/emit-iterable-object-view.js +51 -0
  441. package/dist/targets/cpp/emit-iterator-object-view.d.ts +15 -0
  442. package/dist/targets/cpp/emit-iterator-object-view.js +125 -0
  443. package/dist/targets/cpp/emit-iterator.d.ts +7 -10
  444. package/dist/targets/cpp/emit-iterator.js +361 -24
  445. package/dist/targets/cpp/emit-json.d.ts +7 -1
  446. package/dist/targets/cpp/emit-json.js +595 -55
  447. package/dist/targets/cpp/emit-jsx.d.ts +0 -37
  448. package/dist/targets/cpp/emit-jsx.js +70 -8
  449. package/dist/targets/cpp/emit-narrowing.d.ts +192 -28
  450. package/dist/targets/cpp/emit-narrowing.js +1595 -120
  451. package/dist/targets/cpp/emit-native-selection.js +8 -2
  452. package/dist/targets/cpp/emit-presence.js +13 -0
  453. package/dist/targets/cpp/emit-properties.d.ts +3 -1
  454. package/dist/targets/cpp/emit-properties.js +303 -54
  455. package/dist/targets/cpp/emit-protocol-iterator.d.ts +14 -0
  456. package/dist/targets/cpp/emit-protocol-iterator.js +203 -0
  457. package/dist/targets/cpp/emit-proxy.d.ts +17 -0
  458. package/dist/targets/cpp/emit-proxy.js +35 -0
  459. package/dist/targets/cpp/emit-record-view.d.ts +12 -1
  460. package/dist/targets/cpp/emit-record-view.js +429 -18
  461. package/dist/targets/cpp/emit-return.d.ts +38 -0
  462. package/dist/targets/cpp/emit-return.js +143 -21
  463. package/dist/targets/cpp/emit-scopes.d.ts +78 -0
  464. package/dist/targets/cpp/emit-scopes.js +196 -0
  465. package/dist/targets/cpp/emit-sum-widening.js +6 -3
  466. package/dist/targets/cpp/emit-tonumber.d.ts +40 -1
  467. package/dist/targets/cpp/emit-tonumber.js +75 -4
  468. package/dist/targets/cpp/emit-tostring.d.ts +28 -2
  469. package/dist/targets/cpp/emit-tostring.js +115 -12
  470. package/dist/targets/cpp/emit-typeof.js +2 -2
  471. package/dist/targets/cpp/emit-union-properties.d.ts +9 -0
  472. package/dist/targets/cpp/emit-union-properties.js +375 -46
  473. package/dist/targets/cpp/emit.d.ts +3 -1
  474. package/dist/targets/cpp/emit.js +725 -90
  475. package/dist/targets/cpp/evaluated-once.d.ts +51 -0
  476. package/dist/targets/cpp/evaluated-once.js +140 -0
  477. package/dist/targets/cpp/host/core-globals.d.ts +0 -21
  478. package/dist/targets/cpp/host/core-globals.js +10 -2
  479. package/dist/targets/cpp/host/emit-host-invoke.d.ts +0 -10
  480. package/dist/targets/cpp/host/emit-host-invoke.js +454 -36
  481. package/dist/targets/cpp/host/emit-host-object.js +733 -88
  482. package/dist/targets/cpp/host/emit-host-properties.js +26 -2
  483. package/dist/targets/cpp/host/emit-host-reflect.d.ts +1 -0
  484. package/dist/targets/cpp/host/emit-host-reflect.js +26 -7
  485. package/dist/targets/cpp/host/emit-host-value.d.ts +13 -0
  486. package/dist/targets/cpp/host/emit-host-value.js +47 -3
  487. package/dist/targets/cpp/host/host-members.d.ts +11 -0
  488. package/dist/targets/cpp/host/host-members.js +50 -4
  489. package/dist/targets/cpp/host/native-protocols.js +3 -0
  490. package/dist/targets/cpp/host/object-protocol.d.ts +8 -0
  491. package/dist/targets/cpp/host/object-protocol.js +55 -13
  492. package/dist/targets/cpp/key-order-tracking.d.ts +11 -0
  493. package/dist/targets/cpp/key-order-tracking.js +18 -0
  494. package/dist/targets/cpp/manifest/capabilities.js +107 -8
  495. package/dist/targets/cpp/manifest.js +14 -0
  496. package/dist/targets/cpp/native-collection-base.d.ts +27 -0
  497. package/dist/targets/cpp/native-collection-base.js +202 -0
  498. package/dist/targets/cpp/native-error-base.d.ts +14 -0
  499. package/dist/targets/cpp/native-error-base.js +19 -4
  500. package/dist/targets/cpp/native-promise-base.d.ts +23 -0
  501. package/dist/targets/cpp/native-promise-base.js +30 -0
  502. package/dist/targets/cpp/native-symbol-keys.js +1 -1
  503. package/dist/targets/cpp/prototype/emit-prototype-array.js +258 -20
  504. package/dist/targets/cpp/prototype/emit-prototype-date.js +5 -4
  505. package/dist/targets/cpp/prototype/emit-prototype-invoke.d.ts +9 -1
  506. package/dist/targets/cpp/prototype/emit-prototype-invoke.js +232 -26
  507. package/dist/targets/cpp/prototype/emit-prototype-iterator.d.ts +1 -1
  508. package/dist/targets/cpp/prototype/emit-prototype-iterator.js +111 -13
  509. package/dist/targets/cpp/prototype/emit-prototype-promise.d.ts +33 -4
  510. package/dist/targets/cpp/prototype/emit-prototype-promise.js +218 -10
  511. package/dist/targets/cpp/prototype/emit-prototype-regexp.js +8 -5
  512. package/dist/targets/cpp/prototype/emit-prototype-string.js +24 -7
  513. package/dist/targets/cpp/prototype/prototype-method-reads.js +18 -3
  514. package/dist/targets/cpp/reactive-dependencies.d.ts +2 -0
  515. package/dist/targets/cpp/reactive-dependencies.js +94 -3
  516. package/dist/targets/cpp/realm-storage.d.ts +5 -0
  517. package/dist/targets/cpp/realm-storage.js +12 -0
  518. package/dist/targets/cpp/records.d.ts +151 -1
  519. package/dist/targets/cpp/records.js +1321 -122
  520. package/dist/targets/cpp/recursive-containers.d.ts +4 -1
  521. package/dist/targets/cpp/recursive-containers.js +28 -9
  522. package/dist/targets/cpp/translation-unit.d.ts +10 -0
  523. package/dist/targets/cpp/translation-unit.js +686 -140
  524. package/dist/targets/cpp/types.d.ts +56 -6
  525. package/dist/targets/cpp/types.js +218 -12
  526. package/dist/targets/cpp/virtual-methods.d.ts +3 -3
  527. package/dist/targets/cpp/virtual-methods.js +174 -17
  528. package/package.json +6 -5
  529. package/src/targets/cpp/runtime/gea_dynamic_proxy.h +155 -25
  530. package/src/targets/cpp/runtime/gea_eval.h +3 -0
  531. package/src/targets/cpp/runtime/gea_pcm.h +116 -0
  532. package/src/targets/cpp/runtime/gea_runtime.h +18096 -4876
  533. package/src/targets/cpp/runtime/gea_runtime_builtins.cpp +7 -45
  534. package/src/targets/cpp/runtime/gea_runtime_rtc.h +247 -0
@@ -1,6 +1,13 @@
1
1
  import ts from 'typescript';
2
+ import { isAmbientDeclaration } from '../ambient.js';
3
+ import { transparentClassAliasDeclarationTarget, transparentConstClassAliasTarget } from '../class-alias.js';
2
4
  import { prepareStructuralRules, structuralDisagreementsEnabled } from './structural-rules.js';
5
+ import { noSloppyAbsence, withAbsences } from './sloppy-absence.js';
6
+ import { emptySuppressedWriteArmCensus } from './suppressed-write-arms.js';
3
7
  import { recordStorageFamilies } from './record-storage-families.js';
8
+ import { emptyRecordStandInArmCensus } from './record-stand-in-arms.js';
9
+ import { emptyRecordLinkFamilyCensus } from './record-link-families.js';
10
+ import { bivariantSlotArrayAliasTypeOf, bivariantSlotBindingTypeOf, bivariantSlotElementTypeOf, bivariantSlotParameterTypeOf, bivariantSlotReadTypeOf } from './bivariant-slot-parameter.js';
4
11
  import { emptyDeclaredMemberCensus } from './structural-declarations.js';
5
12
  import { createLocalUnionResolver } from './structural-local-union.js';
6
13
  import { createMutableMethodResolver } from './structural-mutable-method.js';
@@ -8,23 +15,25 @@ import { structuralArrayReadAt } from './structural-array-read.js';
8
15
  import { enclosingArgumentsFunction, implicitArgumentsSlotOf, isArgumentsObjectIdentifier } from './implicit-arguments.js';
9
16
  import { createStructuralCallResultResolver, createStructuralConstructResultResolver } from './structural-callable.js';
10
17
  import { genericFunctionChoiceMembersOf, genericSourceFunctionDeclarationOf } from './generic-function-choice.js';
11
- import { accessorSignatureOf, constructorImplementationSignatureOf, implementationSignatureOf, modifierOnlyMappedSourceOf, optionalMethodSignatureOf, declaredValueTypeOf, physicalInitializerTypeOf, physicalOverloadTypeAt, physicalStringObjectTypeAt } from './structural-declarations.js';
18
+ import { isPrivateNameKey } from '../model/structural-types.js';
19
+ import { accessorSignatureOf, constructorImplementationSignatureOf, implementationSignatureOf, inheritedConstructSignatureOf, modifierOnlyMappedSourceOf, optionalMethodSignatureOf, declaredValueTypeOf, physicalInitializerTypeOf, physicalOverloadTypeAt, physicalStringObjectTypeAt } from './structural-declarations.js';
12
20
  import { createKeyofResolver } from './keyof.js';
13
21
  import { constructorInstalledMemberDeclarationsOf } from './flow/source-class-data.js';
14
- import { arityAdmittedSignature, arrayPredicateNarrowedElementTypeOf, impliedPatternTargetOf, isGlobalObjectInterface, isStandardInterfaceType, isUnusableEvidence, widestOf } from './derived-expression-type.js';
22
+ import { arityAdmittedSignature, arrayPredicateNarrowedElementTypeOf, functionIntersectionMemberTypeOf, impliedPatternTargetOf, isGlobalObjectInterface, isHostMethodPresenceTest, isStandardInterfaceType, isLibArrayBufferViewType, isUnusableEvidence, widestOf } from './derived-expression-type.js';
15
23
  import { createLeafKeying, literalFor, primitiveFor, symbolKeyDeclarationOf } from './structural-leaves.js';
16
24
  import { unwrapErasedExpression } from './producers/erasure.js';
25
+ import { intrinsicAccessorGetterChainOf } from './intrinsic-accessor-getter.js';
17
26
  import { createStructuralParts, selfReferentialCallableShapeOf } from './structural-parts.js';
18
27
  import { bodyReadsThis, createReceiverResolver } from './structural-receiver.js';
19
28
  import { createMemberRules } from './structural-members.js';
20
29
  import { emptyAbsentGlobalCensus } from './absent-globals.js';
21
30
  import { createLayoutTypeResolver } from './structural-layout-type.js';
22
- import { emptyParameterBindingCensus } from './parameter-bindings.js';
31
+ import { emptyParameterBindingCensus, parameterCensusForCopy } from './parameter-bindings.js';
23
32
  import { emptyCollectionBindingCensus } from './collection-bindings.js';
24
33
  import { bagShapeOfType, bagShapeTypeAt, emptyObjectBagCensus } from './object-bag-bindings.js';
25
34
  import { indexedAccessMemberTypes } from './structural-indexed-access.js';
26
35
  import { joinedCallableOf, joinedIndexUnionOf } from './structural-joins.js';
27
- import { creationOrderedProperties } from './structural-creation-order.js';
36
+ import { creationOrderOf, creationOrderedProperties } from './structural-creation-order.js';
28
37
  import { collectionMemberResultTypeAt, contextualArrayConstructTypeAt, inferredArrayElementAt, statedCollectionTypeAt, inferredCollectionTypeArgumentsAt, unstatedNeverArray } from './structural-array-element.js';
29
38
  import { createDeclaredBodyResolver } from './structural-declared-body.js';
30
39
  import { emptyInstantiationCensus } from './instantiation.js';
@@ -35,8 +44,8 @@ import { rootSpecialization } from './identities.js';
35
44
  import { emptyInterfaceFamilyCensus } from '../interface-families.js';
36
45
  import { createInstantiatedMembers } from './structural-instantiated-member.js';
37
46
  import { createAliasRecurrence, isSelfReferentialSignal, createViewIndependentRecurrence, selfReferentialKeyOf, selfReferentialShapeOf, selfReferentialSignal } from './structural-self-reference.js';
38
- import { restParameterArrayElementAt, restParameterUnionOfTuplesElementAt, censusRestElementAt, impliedPatternArrayElementAt } from './parameter-slot.js';
39
- import { physicalGeneratorOverloadResultAt } from './physical-overload-result.js';
47
+ import { restParameterArrayElementAt, restParameterUnionOfTuplesElementAt, censusRestElementAt, impliedPatternArrayElementAt, isOverloadOmissibleParameter } from './parameter-slot.js';
48
+ import { physicalGeneratorOverloadResultAt, physicalInheritedCallableBindingAt, physicalInheritedCallableResultAt } from './physical-overload-result.js';
40
49
  import { arrayAssignmentPatternSourceExpression, arrayAssignmentTargetOf } from './assignment-patterns.js';
41
50
  import { emptyCommonJsModuleRecordCensus } from './commonjs-module-record.js';
42
51
  /**
@@ -78,7 +87,20 @@ const constraintErasedParameterAt = (checker, node) => {
78
87
  return null;
79
88
  return checker.getBaseConstraintOfType(declared) === checker.getTypeAtLocation(node) ? declared : null;
80
89
  };
81
- export const createStructuralMapper = (checker, identities, table, instantiations = emptyInstantiationCensus, specializations = emptySpecializationCensus, parameters = emptyParameterBindingCensus, absent = emptyAbsentGlobalCensus, collections = emptyCollectionBindingCensus, bags = emptyObjectBagCensus, flow, families = emptyInterfaceFamilyCensus, moduleRecords = emptyCommonJsModuleRecordCensus, declaredMembers = emptyDeclaredMemberCensus, isIntrinsicDescriptorCall = () => false) => {
90
+ /** The standard keyed collections a class can extend natively; their instances are the runtime's own collection objects. */
91
+ const nativeCollectionNames = new Set(['Map', 'Set', 'WeakMap', 'WeakSet']);
92
+ /** The intrinsic `Promise`: a class extending it is a promise whose own fields ride beside the native state. */
93
+ const nativePromiseNames = new Set(['Promise']);
94
+ const nativeErrorNames = new Set([
95
+ 'Error',
96
+ 'EvalError',
97
+ 'RangeError',
98
+ 'ReferenceError',
99
+ 'SyntaxError',
100
+ 'TypeError',
101
+ 'URIError'
102
+ ]);
103
+ export const createStructuralMapper = (checker, identities, table, instantiations = emptyInstantiationCensus, specializations = emptySpecializationCensus, parameters = emptyParameterBindingCensus, absent = emptyAbsentGlobalCensus, collections = emptyCollectionBindingCensus, bags = emptyObjectBagCensus, flow, families = emptyInterfaceFamilyCensus, moduleRecords = emptyCommonJsModuleRecordCensus, declaredMembers = emptyDeclaredMemberCensus, isIntrinsicDescriptorCall = () => false, standIns = emptyRecordStandInArmCensus, linkFamilies = emptyRecordLinkFamilyCensus, sloppyAbsence = noSloppyAbsence, suppressedWrites = emptySuppressedWriteArmCensus) => {
82
104
  const storageTypeOf = recordStorageFamilies(checker, flow, parameters);
83
105
  // One disagreement list for the WHOLE mapper, for the same reason the caches
84
106
  // below are shared: two rules answering for one node is a fact about the rule
@@ -111,14 +133,18 @@ export const createStructuralMapper = (checker, identities, table, instantiation
111
133
  const cached = views.get(key);
112
134
  if (cached)
113
135
  return cached;
114
- const built = buildMapper(checker, identities.forSpecialization(path), table, instantiations, specializations, path, bindingPath, mapperFor, parameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, aliasRecurrence, instantiatedMembersFor(bindingPath), viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements);
136
+ const built = buildMapper(checker, identities.forSpecialization(path), table, instantiations, specializations, path, bindingPath, mapperFor, parameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, standIns, linkFamilies, aliasRecurrence, instantiatedMembersFor(bindingPath), viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements, sloppyAbsence, suppressedWrites);
115
137
  views.set(key, built);
116
138
  return built;
117
139
  };
118
140
  return mapperFor(rootSpecialization);
119
141
  };
120
- const buildMapper = (checker, identities, table, instantiations, specializations, path, bindingPath, mapperFor, parameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, aliasRecurrence, instantiatedMembers, viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements) => {
142
+ const buildMapper = (checker, identities, table, instantiations, specializations, path, bindingPath, mapperFor, programParameters, absent, collections, bags, flow, storageTypeOf, families, moduleRecords, declaredMembers, isIntrinsicDescriptorCall, standIns, linkFamilies, aliasRecurrence, instantiatedMembers, viewIndependentKeyOf, sharedCompleted, classCopyKeys, disagreements, sloppyAbsence, suppressedWrites) => {
121
143
  const { boundByPath, bindingOf: censusBindingOf, substituteTypeParameter } = createTypeParameterSubstitution(identities, instantiations, specializations, bindingPath);
144
+ // What a parameter holds is a fact about the COPY this view describes: a
145
+ // generic body's copies are called with different carriers. Scoped once,
146
+ // here, so the ABI slot and every body read in this view ask one census.
147
+ const parameters = parameterCensusForCopy(programParameters, path);
122
148
  // A type under translation must resolve to its anchor rather than recursing:
123
149
  // `interface Node { next: Node }` would otherwise never terminate.
124
150
  const inProgress = new Map();
@@ -140,7 +166,7 @@ const buildMapper = (checker, identities, table, instantiations, specializations
140
166
  const selfReferentialKeys = new Map();
141
167
  const unresolved = (reason, fallback) => table.intern({ kind: 'unresolved', reason, ...(fallback ? { fallback } : {}) });
142
168
  const { keyOfSymbol } = createLeafKeying(identities, checker);
143
- const { implicitReceiverOf, declaredMemberSignatureOf } = createReceiverResolver(checker, (node) => layoutTypeAt(node), declaredMembers);
169
+ const { implicitReceiverOf, declaredMemberResultOf } = createReceiverResolver(checker, (node) => layoutTypeAt(node), declaredMembers);
144
170
  /**
145
171
  * The object half of a `T[K]`, resolved the way this copy resolves a bare `T`.
146
172
  *
@@ -224,6 +250,55 @@ const buildMapper = (checker, identities, table, instantiations, specializations
224
250
  return typeOf(checker.getNeverType());
225
251
  return arms.length === 1 ? only : table.intern({ kind: 'union', members: arms });
226
252
  };
253
+ /**
254
+ * `reducedIntersectionOf` for a product with no union member, answered only
255
+ * when the reduction leaves a single member (`X & unknown`, `X & {}`) or
256
+ * `never` (`X & undefined`, `number & string`): `null` for `never`,
257
+ * `undefined` when the product still has several members and keeps the
258
+ * checker's own reconciliation instead.
259
+ */
260
+ /**
261
+ * The declared object type an intersection restates exactly: a member is a
262
+ * `Pick`/`Omit` of `D` (`D` is its alias's first type argument) and the
263
+ * intersection's properties are `D`'s, one for one, with identical types
264
+ * and optionality (readonly-ness is no part of a layout). `null` for anything else -- a class is
265
+ * nominal and never restated structurally.
266
+ */
267
+ const restatedDeclaredOf = (type) => {
268
+ for (const part of type.types) {
269
+ const source = part.aliasTypeArguments?.[0];
270
+ if (source === undefined || !source.isClassOrInterface() || (source.symbol.flags & ts.SymbolFlags.Interface) === 0)
271
+ continue;
272
+ const wanted = checker.getPropertiesOfType(source);
273
+ const have = checker.getPropertiesOfType(type);
274
+ if (wanted.length === 0 || wanted.length !== have.length || checker.getIndexInfosOfType(type).length !== 0)
275
+ continue;
276
+ const restates = wanted.every((property) => {
277
+ const other = have.find((candidate) => candidate.name === property.name);
278
+ return (other !== undefined &&
279
+ (property.flags & ts.SymbolFlags.Optional) === (other.flags & ts.SymbolFlags.Optional) &&
280
+ checker.getTypeOfSymbol(property) === checker.getTypeOfSymbol(other));
281
+ });
282
+ if (restates && checker.getIndexInfosOfType(source).length === 0)
283
+ return source;
284
+ }
285
+ return null;
286
+ };
287
+ const collapsedIntersectionOf = (members) => {
288
+ const primitiveMember = members.some((member) => {
289
+ const shape = closedShapeAt(member);
290
+ return (shape !== null &&
291
+ (shape.kind === 'primitive' ||
292
+ shape.kind === 'literal' ||
293
+ (shape.kind === 'object' && shape.members.length === 0 && shape.index.length === 0)));
294
+ });
295
+ if (!primitiveMember)
296
+ return undefined;
297
+ const reduced = reducedIntersectionOf(members);
298
+ if (reduced === null)
299
+ return null;
300
+ return members.includes(reduced) ? reduced : undefined;
301
+ };
227
302
  /** One product of the distribution, reduced as the checker reduces an intersection; `null` is `never`. */
228
303
  const reducedIntersectionOf = (product) => {
229
304
  const isIdentity = (shape) => (shape.kind === 'primitive' && shape.primitive === 'unknown') ||
@@ -358,14 +433,44 @@ const buildMapper = (checker, identities, table, instantiations, specializations
358
433
  // `getMinArgumentCount` is checker-internal. The public answer is the count of
359
434
  // leading parameters the call site must supply: everything before the first
360
435
  // optional, defaulted, or rest parameter.
436
+ // What a suppressed type error stores beyond a cell's declared type is one
437
+ // more native arm of every place its value provably reaches -- see
438
+ // `suppressed-write-arms.ts`. Keyed by node and member, never by the union
439
+ // TYPE: `ClientSession | undefined` is one checker type for every slot in
440
+ // the program, and only this flow holds the foreign value.
441
+ const withForeignArms = (id, arms) => {
442
+ if (arms === null)
443
+ return id;
444
+ const shape = table.isOpen(id) ? null : table.get(id).shape;
445
+ if (shape?.kind === 'primitive' && (shape.primitive === 'any' || shape.primitive === 'unknown'))
446
+ return id;
447
+ const members = shape?.kind === 'union' ? [...shape.members] : [id];
448
+ const before = members.length;
449
+ for (const arm of arms) {
450
+ const armId = typeOf(arm);
451
+ if (!members.includes(armId))
452
+ members.push(armId);
453
+ }
454
+ return members.length === before ? id : table.intern({ kind: 'union', members });
455
+ };
456
+ // The signature side of a followed parameter: its ABI slot and the body's
457
+ // binding (`typeAt` on the same declaration) must name one carrier.
458
+ const suppressedWriteParameterAt = (parameter) => {
459
+ const arms = suppressedWrites.armsAt(parameter);
460
+ return arms === null ? null : withForeignArms(typeOf(checker.getTypeAtLocation(parameter)), arms);
461
+ };
361
462
  const { signatureOf, memberOf, indexesOf, tupleElementsOf } = createStructuralParts({
362
463
  parameters,
363
464
  checker,
364
465
  identities,
365
466
  typeOf: (type) => typeOf(type),
366
- parameterOverrideAt: (parameter) => refusedArrayParameterTypeAt(parameter) ?? prototypeObjectParameterTypeAt(parameter),
467
+ layoutTypeAt: (node) => layoutTypeAt(node),
468
+ parameterOverrideAt: (parameter) => refusedArrayParameterTypeAt(parameter) ??
469
+ prototypeObjectParameterTypeAt(parameter) ??
470
+ bivariantSlotParameterAt(parameter) ??
471
+ suppressedWriteParameterAt(parameter),
367
472
  implicitReceiverOf,
368
- declaredMemberSignatureOf,
473
+ declaredMemberResultOf,
369
474
  declaredMembers,
370
475
  keyOfSymbol,
371
476
  // Same wrap the body-side rest-parameter reference below performs
@@ -381,7 +486,9 @@ const buildMapper = (checker, identities, table, instantiations, specializations
381
486
  table,
382
487
  // The bag census the collection value slot needs -- see
383
488
  // `StructuralPartsInput.bags`.
384
- bags
489
+ bags,
490
+ sloppyAbsence,
491
+ foreignArmsOfMember: (symbol, id) => withForeignArms(id, suppressedWrites.armsOfMember(symbol))
385
492
  });
386
493
  const { keeperFor } = createMemberRules(identities);
387
494
  /**
@@ -530,13 +637,40 @@ const buildMapper = (checker, identities, table, instantiations, specializations
530
637
  }
531
638
  return { kind: 'array', element: typeOf(element), readonly: false, extension };
532
639
  };
533
- const objectShapeOf = (type, location, members = 'all') => {
534
- const properties = creationOrderedProperties(checker, type, parameters);
640
+ const isStandardLibraryOnlyMember = (property) => {
641
+ const declarations = property.getDeclarations() ?? [];
642
+ return declarations.length > 0 && declarations.every((node) => node.getSourceFile().hasNoDefaultLib);
643
+ };
644
+ // `structural-creation-order.ts`'s phantoms: the keys a literal-union
645
+ // computed name creates and the checker's type drops, laid out as optional
646
+ // members at the position the literal creates them.
647
+ const withPhantomMembers = (type, stated) => {
648
+ const creation = creationOrderOf(checker, type, parameters);
649
+ if (creation === null || creation.phantoms.size === 0)
650
+ return stated;
651
+ const byName = new Map(stated.flatMap((member) => (member.key.kind === 'string' ? [[member.key.value, member]] : [])));
652
+ if (byName.size !== stated.length)
653
+ return stated;
654
+ return creation.order.flatMap((name) => {
655
+ const phantom = creation.phantoms.get(name);
656
+ if (phantom === undefined) {
657
+ const member = byName.get(name);
658
+ return member ? [member] : [];
659
+ }
660
+ const own = checker.getTypeAtLocation(phantom);
661
+ const value = own.isLiteral() || (own.flags & ts.TypeFlags.BooleanLiteral) !== 0 ? checker.getBaseTypeOfLiteralType(own) : own;
662
+ return [{ key: { kind: 'string', value: name }, type: typeOf(value), optional: true, readonly: false, accessor: null }];
663
+ });
664
+ };
665
+ const objectShapeOf = (type, location, members = 'all', excluded) => {
666
+ const ordered = creationOrderedProperties(checker, type, parameters);
667
+ const properties = excluded ? ordered.filter((property) => !excluded(property)) : ordered;
535
668
  const kept = members === 'all' ? properties : properties.filter(keeperFor(properties, members));
536
- const mapped = kept.flatMap((property) => {
669
+ const stated = kept.flatMap((property) => {
537
670
  const member = memberOf(property, location);
538
671
  return member ? [member] : [];
539
672
  });
673
+ const mapped = members === 'all' && !excluded ? withPhantomMembers(type, stated) : stated;
540
674
  const indexes = [...indexesOf(type)];
541
675
  if (location && ts.isObjectLiteralExpression(location) && members === 'all') {
542
676
  const runtimeMembers = mapped.filter((member) => {
@@ -593,14 +727,19 @@ const buildMapper = (checker, identities, table, instantiations, specializations
593
727
  * *is* per-instance storage, and the symbol flags are what tell the two apart
594
728
  * -- not the type of the value they hold.
595
729
  */
596
- const classInstanceBodyOf = (type, location) => {
730
+ const classInstanceBodyOf = (type, location, nativeCollection = false) => {
597
731
  // A class declared in a declaration file is enumerated like any other. Its
598
732
  // *fields* are data, and a subclass this program does define inherits them
599
733
  // -- refusing the layout would leave that subclass with no carrier at all.
600
734
  // What the program genuinely cannot do with such a class is construct one or
601
735
  // call one of its methods, and both of those refuse where they happen: the
602
736
  // construction has no body to run, and a method key resolves to no callable.
603
- const shape = objectShapeOf(type, location, 'data-only');
737
+ //
738
+ // A class extending a native collection leaves out every member only the
739
+ // standard library declares: `size` and `[Symbol.toStringTag]` are the
740
+ // native base object's, and a struct field for them would be storage
741
+ // nothing ever writes.
742
+ const shape = objectShapeOf(type, location, 'data-only', nativeCollection ? isStandardLibraryOnlyMember : undefined);
604
743
  // `objectShapeOf` walks `type.getProperties()` -- the checker's OWN
605
744
  // member table -- which is blind to a field installed only through a
606
745
  // `const _this = this` alias (`source-class-data.ts`'s
@@ -683,6 +822,21 @@ const buildMapper = (checker, identities, table, instantiations, specializations
683
822
  const declaration = identities.declarationOfSymbol(symbol);
684
823
  if (!declaration)
685
824
  return null;
825
+ // DOM constructors commonly have an inline object type rather than a
826
+ // named Constructor interface. The ambient variable owns that identity;
827
+ // its overloads describe calls to a host object, not a source closure
828
+ // whose incompatible signatures must share one calling convention.
829
+ if (ts.isTypeLiteralNode(declaration) &&
830
+ ts.isVariableDeclaration(declaration.parent) &&
831
+ declaration.parent.type === declaration &&
832
+ isAmbientDeclaration(declaration.parent) &&
833
+ type.getConstructSignatures().length > 0) {
834
+ return {
835
+ kind: 'class-constructor',
836
+ declaration: identities.declarationIdOf(declaration.parent, rootSpecialization),
837
+ declarationNode: declaration.parent
838
+ };
839
+ }
686
840
  // At the ROOT path, deliberately, and never at the copy this walk happens
687
841
  // to be inside. `identities` is a per-copy VIEW (`identities.ts`'s
688
842
  // `declarationIdOf: (declaration, override) => ... prefixFor(declaration,
@@ -834,6 +988,24 @@ const buildMapper = (checker, identities, table, instantiations, specializations
834
988
  * Declaration`); members of different families are not one object.
835
989
  */
836
990
  const familyFieldNames = new Map();
991
+ const memberFieldNames = new Map();
992
+ /** The keys the family's interface members declare, absorbed partners aside. */
993
+ const familyMemberFieldNames = (family) => {
994
+ let names = memberFieldNames.get(family.key);
995
+ if (!names) {
996
+ const collected = new Set();
997
+ for (const declaration of family.members) {
998
+ const symbol = checker.getSymbolAtLocation(declaration.name);
999
+ if (!symbol)
1000
+ continue;
1001
+ for (const property of checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(symbol)))
1002
+ collected.add(property.getName());
1003
+ }
1004
+ names = collected;
1005
+ memberFieldNames.set(family.key, names);
1006
+ }
1007
+ return names;
1008
+ };
837
1009
  const familyMemberNarrowedBy = (type) => {
838
1010
  const member = narrowedFamilyMemberOf(type);
839
1011
  return member === null ? null : typeOf(member);
@@ -862,14 +1034,10 @@ const buildMapper = (checker, identities, table, instantiations, specializations
862
1034
  return null;
863
1035
  let names = familyFieldNames.get(family.key);
864
1036
  if (!names) {
865
- const collected = new Set();
866
- for (const declaration of family.members) {
867
- const symbol = checker.getSymbolAtLocation(declaration.name);
868
- if (!symbol)
869
- continue;
870
- for (const property of checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(symbol)))
1037
+ const collected = new Set(familyMemberFieldNames(family));
1038
+ for (const absorbed of family.absorbed)
1039
+ for (const property of checker.getPropertiesOfType(absorbed))
871
1040
  collected.add(property.getName());
872
- }
873
1041
  names = collected;
874
1042
  familyFieldNames.set(family.key, names);
875
1043
  }
@@ -881,7 +1049,33 @@ const buildMapper = (checker, identities, table, instantiations, specializations
881
1049
  }
882
1050
  return member;
883
1051
  };
884
- const familyLayoutOf = (family) => {
1052
+ const familyLayoutOf = (family) => mergedLayoutOf([
1053
+ ...family.members.flatMap((member) => {
1054
+ const symbol = checker.getSymbolAtLocation(member.name);
1055
+ return symbol ? [{ type: checker.getDeclaredTypeOfSymbol(symbol), location: member }] : [];
1056
+ }),
1057
+ // Absorbed intersection partners (`& Abortable`): all-optional, and
1058
+ // not counted as views, so every member field keeps its requiredness.
1059
+ // A key a member already declares keeps the member's type: a partner
1060
+ // restating it (`& { writeConcern?: never }`) narrows a view, not the
1061
+ // object.
1062
+ ...family.absorbed.flatMap((type) => {
1063
+ const location = type.getSymbol()?.declarations?.[0];
1064
+ const declared = familyMemberFieldNames(family);
1065
+ return location ? [{ type, location, excluded: (property) => declared.has(property.getName()) }] : [];
1066
+ })
1067
+ ], family.members.length, family.excess);
1068
+ /**
1069
+ * The one object several views of it lay out as: each part enumerated as a
1070
+ * lone declaration's body is, merged by key -- required only where every
1071
+ * one of `count` views requires it, typed as the flattened union of what
1072
+ * they declare. `familyLayoutOf` and the linked-record families share it.
1073
+ */
1074
+ const mergedLayoutOf = (parts, count,
1075
+ // Types stored under a key beyond what any view declares for it
1076
+ // (`interface-families.ts`'s `widenBySpreadExcess`), joined to that
1077
+ // key's union.
1078
+ excess = new Map()) => {
885
1079
  // An open anchor is a family-mate's (or another recursive type's) body
886
1080
  // still being built; it names one member and nothing to flatten.
887
1081
  const flatten = (id) => {
@@ -891,23 +1085,40 @@ const buildMapper = (checker, identities, table, instantiations, specializations
891
1085
  return shape.kind === 'union' ? shape.members.flatMap(flatten) : [id];
892
1086
  };
893
1087
  const merged = new Map();
894
- for (const member of family.members) {
895
- const symbol = checker.getSymbolAtLocation(member.name);
896
- if (!symbol)
897
- continue;
898
- const shape = objectShapeOf(checker.getDeclaredTypeOfSymbol(symbol), member, 'all');
1088
+ for (const view of parts) {
1089
+ const shape = objectShapeOf(view.type, view.location, 'all', view.excluded);
899
1090
  if (shape.kind !== 'object')
900
1091
  continue;
901
- for (const field of shape.members) {
1092
+ // A field left out of this view's types still counts as one it
1093
+ // declares: only its TYPE is stated by the other views.
1094
+ const withheld = view.excluded
1095
+ ? view.type.getProperties().flatMap((property) => {
1096
+ const key = view.excluded(property) ? keyOfSymbol(property) : null;
1097
+ if (!key)
1098
+ return [];
1099
+ const readonly = (property.declarations ?? []).some((declaration) => (ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Readonly) !== 0);
1100
+ return [
1101
+ {
1102
+ key,
1103
+ type: typeOf(checker.getNeverType()),
1104
+ optional: (property.flags & ts.SymbolFlags.Optional) !== 0,
1105
+ readonly,
1106
+ accessor: null
1107
+ }
1108
+ ];
1109
+ })
1110
+ : [];
1111
+ for (const field of [...shape.members, ...withheld]) {
902
1112
  if (field.accessor !== null)
903
1113
  continue;
904
1114
  const keyText = JSON.stringify(field.key);
905
1115
  const slot = merged.get(keyText) ?? { key: field.key, types: [], declaredBy: 0, requiredBy: 0, readonlyBy: 0 };
906
1116
  if (!merged.has(keyText))
907
1117
  merged.set(keyText, slot);
908
- for (const part of flatten(field.type))
909
- if (!slot.types.includes(part))
910
- slot.types.push(part);
1118
+ if (!withheld.includes(field))
1119
+ for (const part of flatten(field.type))
1120
+ if (!slot.types.includes(part))
1121
+ slot.types.push(part);
911
1122
  slot.declaredBy += 1;
912
1123
  if (!field.optional)
913
1124
  slot.requiredBy += 1;
@@ -915,9 +1126,16 @@ const buildMapper = (checker, identities, table, instantiations, specializations
915
1126
  slot.readonlyBy += 1;
916
1127
  }
917
1128
  }
1129
+ for (const slot of merged.values()) {
1130
+ const extra = slot.key.kind === 'string' ? excess.get(String(slot.key.value)) : undefined;
1131
+ for (const type of extra ?? [])
1132
+ for (const part of flatten(typeOf(type)))
1133
+ if (!slot.types.includes(part))
1134
+ slot.types.push(part);
1135
+ }
918
1136
  const undefinedType = typeOf(checker.getUndefinedType());
919
1137
  const members = [...merged.values()].map((slot) => {
920
- const optional = slot.requiredBy < family.members.length;
1138
+ const optional = slot.requiredBy < count;
921
1139
  const types = optional && !slot.types.includes(undefinedType) ? [...slot.types, undefinedType] : slot.types;
922
1140
  const only = types.length === 1 ? types[0] : undefined;
923
1141
  return {
@@ -976,10 +1194,56 @@ const buildMapper = (checker, identities, table, instantiations, specializations
976
1194
  known.set(ordinal, { ordinal, typeArguments, constructor });
977
1195
  classCopyKeys.set(root, known);
978
1196
  };
1197
+ /**
1198
+ * The keys one family member declares, own and inherited -- the `declared`
1199
+ * shape's `familyMemberKeys`. Read from the checker's property table of the
1200
+ * member's DECLARED type, never by interning a member type: the family's
1201
+ * layout may still be open here (a member reached through a family-mate's
1202
+ * field), and the keys are all the answer needs.
1203
+ */
1204
+ const familyMemberKeysOf = (declared) => {
1205
+ if (!ts.isInterfaceDeclaration(declared.declarationNode))
1206
+ return null;
1207
+ const symbol = checker.getSymbolAtLocation(declared.declarationNode.name);
1208
+ if (!symbol)
1209
+ return null;
1210
+ const keys = [];
1211
+ for (const property of checker.getPropertiesOfType(checker.getDeclaredTypeOfSymbol(symbol))) {
1212
+ const key = keyOfSymbol(property);
1213
+ // A property with no key shape is one the layout could not name either;
1214
+ // refusing the whole fact keeps every site that named this member on the
1215
+ // family's full layout, which is the answer before this fact existed.
1216
+ if (!key)
1217
+ return null;
1218
+ keys.push(key);
1219
+ }
1220
+ return keys;
1221
+ };
979
1222
  const buildDeclaredShape = (type, declared, typeArguments) => {
980
1223
  const { kind, declaration } = declared;
981
1224
  if (kind === 'declared') {
982
- return { kind, declaration, typeArguments, body: familyBodyOf(declared) ?? declaredBodyOf(type, declared.declarationNode) };
1225
+ const familyBody = familyBodyOf(declared);
1226
+ const linkMembers = familyBody === null ? linkFamilies.membersOf(type) : null;
1227
+ const body = familyBody ??
1228
+ (linkMembers
1229
+ ? table.intern(mergedLayoutOf(linkMembers.map((member) => ({
1230
+ type: member.type,
1231
+ location: member.declaration,
1232
+ ...(member.links === 'family'
1233
+ ? { excluded: (property) => linkFamilies.isLink(checker.getTypeOfSymbol(property)) }
1234
+ : {})
1235
+ })), linkMembers.length))
1236
+ : declaredBodyOf(type, declared.declarationNode));
1237
+ const nativeError = interfaceNativeErrorBaseOf(type, declared.declarationNode);
1238
+ const familyMemberKeys = familyBody === null ? null : familyMemberKeysOf(declared);
1239
+ return {
1240
+ kind,
1241
+ declaration,
1242
+ typeArguments,
1243
+ body,
1244
+ ...(nativeError ? { nativeError } : {}),
1245
+ ...(familyMemberKeys ? { familyMemberKeys } : {})
1246
+ };
983
1247
  }
984
1248
  if (kind === 'class-constructor') {
985
1249
  // An overloaded constructor's IMPLEMENTATION declares the one frame the
@@ -988,7 +1252,8 @@ const buildMapper = (checker, identities, table, instantiations, specializations
988
1252
  // single convention, exactly as `valueTypeAt` asks
989
1253
  // `implementationSignatureOf` before the symbol-level answer for a
990
1254
  // method's overload set.
991
- const implementation = constructorImplementationSignatureOf(checker, declared.declarationNode);
1255
+ const implementation = constructorImplementationSignatureOf(checker, declared.declarationNode) ??
1256
+ inheritedConstructSignatureOf(checker, declared.declarationNode, type.getConstructSignatures());
992
1257
  const constructSignatures = implementation ? [implementation] : type.getConstructSignatures();
993
1258
  return {
994
1259
  kind,
@@ -1008,12 +1273,158 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1008
1273
  if (type.isClassOrInterface())
1009
1274
  for (const base of checker.getBaseTypes(type))
1010
1275
  typeOf(base);
1011
- return { kind, declaration, typeArguments, body: classInstanceBodyOf(type, declared.declarationNode) };
1276
+ const nativeCollection = nativeCollectionBaseOf(type);
1277
+ const nativeError = kind === 'class-instance' ? nativeErrorBaseOf(type) : null;
1278
+ const nativePromise = kind === 'class-instance' ? nativeCollectionBaseOf(type, nativePromiseNames) : null;
1279
+ return {
1280
+ kind,
1281
+ declaration,
1282
+ typeArguments,
1283
+ body: classInstanceBodyOf(type, declared.declarationNode, nativeCollection !== null || nativePromise !== null),
1284
+ ...(nativeCollection ? { nativeCollection } : {}),
1285
+ ...(nativeError ? { nativeError } : {}),
1286
+ ...(nativePromise ? { nativePromise } : {})
1287
+ };
1012
1288
  };
1289
+ /**
1290
+ * The lib `Error` interface a class extends, directly or through class
1291
+ * bases, or `null`. The error interfaces are not generic, so unlike
1292
+ * `nativeCollectionBaseOf` there is nothing of this instance to substitute.
1293
+ */
1294
+ function nativeErrorBaseOf(type) {
1295
+ const walk = (target, depth) => {
1296
+ if (depth > 32 || !target.isClassOrInterface())
1297
+ return null;
1298
+ for (const base of checker.getBaseTypes(target)) {
1299
+ const symbol = base.getSymbol();
1300
+ const declarations = symbol?.declarations ?? [];
1301
+ if (declarations.some(ts.isClassLike)) {
1302
+ const found = walk(base.target ?? base, depth + 1);
1303
+ if (found)
1304
+ return found;
1305
+ continue;
1306
+ }
1307
+ if (!symbol || !nativeErrorNames.has(symbol.name))
1308
+ continue;
1309
+ if (declarations.length === 0 || !declarations.every((node) => node.getSourceFile().hasNoDefaultLib))
1310
+ continue;
1311
+ return typeOf(base);
1312
+ }
1313
+ return null;
1314
+ };
1315
+ const reference = type.target !== undefined ? type.target : type;
1316
+ return walk(reference, 0);
1317
+ }
1318
+ /**
1319
+ * The lib `Error` interface a PROGRAM interface extends through interface
1320
+ * bases, or `null` -- `structural-types.ts`'s `declared.nativeError`.
1321
+ *
1322
+ * Only interface bases are walked. An interface that extends a CLASS names
1323
+ * that class's instances, whose carrier is the class's own, and an interface
1324
+ * merged with a class declaration is the class; neither is an error the
1325
+ * program merely re-typed. The lib error interfaces themselves are answered
1326
+ * by their own declaration policy and never reach here.
1327
+ */
1328
+ function interfaceNativeErrorBaseOf(type, declarationNode) {
1329
+ if (!ts.isInterfaceDeclaration(declarationNode) || declarationNode.getSourceFile().hasNoDefaultLib)
1330
+ return null;
1331
+ const own = type.getSymbol()?.declarations ?? [];
1332
+ if (own.some((node) => ts.isClassLike(node) || node.getSourceFile().hasNoDefaultLib))
1333
+ return null;
1334
+ const walk = (target, depth) => {
1335
+ if (depth > 32 || !target.isClassOrInterface())
1336
+ return null;
1337
+ for (const base of checker.getBaseTypes(target)) {
1338
+ const symbol = base.getSymbol();
1339
+ const declarations = symbol?.declarations ?? [];
1340
+ if (!symbol || declarations.length === 0 || declarations.some(ts.isClassLike))
1341
+ continue;
1342
+ if (nativeErrorNames.has(symbol.name) && declarations.some((node) => node.getSourceFile().hasNoDefaultLib))
1343
+ return typeOf(base);
1344
+ if (!declarations.every(ts.isInterfaceDeclaration))
1345
+ continue;
1346
+ const found = walk(base.target ?? base, depth + 1);
1347
+ if (found)
1348
+ return found;
1349
+ }
1350
+ return null;
1351
+ };
1352
+ return walk(type.target ?? type, 0);
1353
+ }
1354
+ /**
1355
+ * The standard keyed collection a class extends, directly or through its
1356
+ * class bases, with the collection's type arguments as THIS instance fills
1357
+ * them.
1358
+ *
1359
+ * `getBaseTypes` answers only for the class's own declaration, in terms of
1360
+ * its own type parameters; the public checker cannot instantiate that
1361
+ * answer. A base argument that is exactly one of the class's parameters is
1362
+ * substituted with this instance's argument for it, which is every shape
1363
+ * `extends Map<string, V>` takes. An argument that mentions a parameter
1364
+ * deeper than that stays open, and the collection derives as unresolved
1365
+ * rather than as some other `Map`.
1366
+ */
1367
+ function nativeCollectionBaseOf(type, names = nativeCollectionNames) {
1368
+ const reference = type.target !== undefined ? type : null;
1369
+ const walk = (target, actuals, depth) => {
1370
+ if (depth > 32)
1371
+ return null;
1372
+ const parameters = target.typeParameters ?? [];
1373
+ const substitute = (argument) => {
1374
+ const index = parameters.indexOf(argument);
1375
+ return index >= 0 && actuals[index] !== undefined ? actuals[index] : argument;
1376
+ };
1377
+ for (const base of checker.getBaseTypes(target)) {
1378
+ const symbol = base.getSymbol();
1379
+ const declarations = symbol?.declarations ?? [];
1380
+ const writtenArguments = checker.getTypeArguments(base);
1381
+ const baseArguments = writtenArguments.map(substitute);
1382
+ const classDeclaration = declarations.find(ts.isClassLike);
1383
+ if (classDeclaration) {
1384
+ const baseTarget = base.target ?? base;
1385
+ if (!baseTarget.isClassOrInterface())
1386
+ continue;
1387
+ const found = walk(baseTarget, baseArguments, depth + 1);
1388
+ if (found)
1389
+ return found;
1390
+ continue;
1391
+ }
1392
+ if (!symbol || !names.has(symbol.name))
1393
+ continue;
1394
+ if (declarations.length === 0 || !declarations.every((node) => node.getSourceFile().hasNoDefaultLib))
1395
+ continue;
1396
+ // Written arguments this instance does not rebind are the checker's own
1397
+ // closed type, interned as every other `Map<K, V>` is. A substituted
1398
+ // one has no `ts.Type` to intern, so the collection is stated by its
1399
+ // declaration and arguments alone -- all a collection carrier reads.
1400
+ if (baseArguments.every((argument, index) => argument === writtenArguments[index]))
1401
+ return typeOf(base);
1402
+ const anchor = declaredAnchorOf(base);
1403
+ if (!anchor)
1404
+ continue;
1405
+ return table.intern({
1406
+ kind: 'declared',
1407
+ declaration: anchor.declaration,
1408
+ typeArguments: baseArguments.map((argument) => typeOf(argument)),
1409
+ body: null
1410
+ });
1411
+ }
1412
+ return null;
1413
+ };
1414
+ const target = reference ? reference.target : type;
1415
+ if (!target.isClassOrInterface())
1416
+ return null;
1417
+ return walk(target, reference ? checker.getTypeArguments(reference) : (target.typeParameters ?? []), 0);
1418
+ }
1013
1419
  // `keyof` reads its answer back out of the sealed table, so the table is the
1014
1420
  // only thing it needs from this closure -- which is why it lives on its own.
1015
1421
  const keyofOfShapeId = createKeyofResolver(table);
1016
1422
  function typeOf(type) {
1423
+ // Every view of one linked object lays out as its instance's canonical
1424
+ // member, whose body merges them all -- see `record-link-families.ts`.
1425
+ const linked = linkFamilies.storageOf(type);
1426
+ if (linked !== type)
1427
+ return typeOf(linked);
1017
1428
  // Assignment-connected record views must agree before any layout is
1018
1429
  // interned, including the element reached through an array or tuple.
1019
1430
  const storage = storageTypeOf(type);
@@ -1096,11 +1507,34 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1096
1507
  // reaching this frame first used to cost. The anchor is already
1097
1508
  // reserved, so the element's own walk resolves a mention of `type`
1098
1509
  // through `inProgress` exactly as `buildDeclaredShape`'s does.
1099
- const shape = bagShapeOfType(typeOf, bags, type) ??
1100
- indexedShapeOf(type) ??
1101
- (declared
1102
- ? buildDeclaredShape(type, declared, typeArgumentsOf(type).map(typeOf))
1103
- : selfReferentialShapeOf(checker, type, typeOf, tupleElementsOf, indexesOf, (one) => selfReferentialCallableShapeOf(one, signatureOf)));
1510
+ const bagOrIndexed = bagShapeOfType(typeOf, bags, type) ?? indexedShapeOf(type);
1511
+ const declaredArguments = !bagOrIndexed && declared ? typeArgumentsOf(type).map(typeOf) : null;
1512
+ // The declared path keys this same instantiation by its arguments
1513
+ // (`declared:<decl>:<args>`), and `type Tree = Map<string, Tree>`
1514
+ // reaches it again -- inside its own body walk (`Map`'s members name
1515
+ // `Map<string, Tree>`) and as `new Map()`'s type. Bind that key before
1516
+ // the body is built so every road is this one id. Only a plain
1517
+ // declared name whose arguments that path would key unchanged --
1518
+ // every parameter layout-relevant -- so the key is exactly its own.
1519
+ if (declared?.kind === 'declared' && declaredArguments) {
1520
+ const owner = ts.isClassLike(declared.declarationNode) || ts.isInterfaceDeclaration(declared.declarationNode)
1521
+ ? declared.declarationNode
1522
+ : null;
1523
+ const relevant = owner ? layoutRelevantParameterIndices(checker, owner) : null;
1524
+ if (!relevant || declaredArguments.every((_, index) => relevant.has(index))) {
1525
+ table.bindAnchorKey(`${declared.kind}:${declared.declaration}:${declaredArguments.join(',')}`, anchor);
1526
+ }
1527
+ }
1528
+ const shape = bagOrIndexed ??
1529
+ (declared && declaredArguments
1530
+ ? buildDeclaredShape(type, declared, declaredArguments)
1531
+ : selfReferentialShapeOf(checker, type, typeOf, tupleElementsOf, indexesOf, (one) => selfReferentialCallableShapeOf(one, signatureOf), (one) => {
1532
+ const anchorLocation = one
1533
+ .getProperties()
1534
+ .map((property) => identities.declarationOfSymbol(property))
1535
+ .find((declaration) => declaration !== null) ?? null;
1536
+ return objectShapeOf(one, anchorLocation);
1537
+ }));
1104
1538
  completedShape = shape ?? completedShape;
1105
1539
  table.complete(anchor, completedShape);
1106
1540
  settled = true;
@@ -1201,6 +1635,17 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1201
1635
  * answered.
1202
1636
  */
1203
1637
  const typeArgumentsOf = (type) => {
1638
+ // A generic alias of an object-literal type (`type Cell<T> = { value: T }`)
1639
+ // anchors on the ALIAS (`declaredAnchorOf`), and its anonymous object type
1640
+ // carries no type arguments of its own. Its instantiation is the alias's
1641
+ // arguments; without them `Cell<string>` and `Cell<number>` keyed one
1642
+ // anchor and the first to complete it laid out both.
1643
+ if (type.aliasTypeArguments !== undefined && (type.getFlags() & ts.TypeFlags.Object) !== 0) {
1644
+ const own = type.getSymbol();
1645
+ const ownDeclaration = own ? identities.declarationOfSymbol(own) : null;
1646
+ if (ownDeclaration !== null && (ts.isTypeLiteralNode(ownDeclaration) || ts.isJSDocTypeLiteral(ownDeclaration)))
1647
+ return type.aliasTypeArguments;
1648
+ }
1204
1649
  const reference = type;
1205
1650
  const args = checker.getTypeArguments(reference) ?? [];
1206
1651
  const declared = reference.target?.typeParameters?.length;
@@ -1307,6 +1752,84 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1307
1752
  }
1308
1753
  return null;
1309
1754
  };
1755
+ /**
1756
+ * A DEFERRED `Parameters<F>`, laid out as the tuple of the parameters the
1757
+ * closed `F` declares.
1758
+ *
1759
+ * mongodb's `TypedEventEmitter<Events>` declares its logging helpers as
1760
+ * `emitAndLog<EventKey extends keyof Events>(event: EventKey | symbol,
1761
+ * ...args: Parameters<Events[EventKey]>)`. Each call site's copy binds both
1762
+ * `Events` (the subclass's event map) and `EventKey` (the literal event
1763
+ * name), so the rest parameter is closed in every copy -- but the checker
1764
+ * deferred it while both were open, and no copy can ask it to evaluate the
1765
+ * conditional again: the public checker has no instantiation and, unlike
1766
+ * `Awaited` and `NonNullable`, no operator for this one.
1767
+ *
1768
+ * It does not need either. The tuple `Parameters` produces is exactly the
1769
+ * closed callee's parameter list, which the checker reports signature by
1770
+ * signature, so the layout is built from those facts rather than from a
1771
+ * type nobody can spell. The callee closes the way an indexed access
1772
+ * anywhere else in this mapper does -- the copy's binding, then the
1773
+ * parameter's declared default -- and only a callee with ONE non-generic
1774
+ * signature whose rest parameter, if any, is a plain array answers;
1775
+ * anything else stays deferred and is refused below exactly as before.
1776
+ */
1777
+ const closedCallee = (type) => {
1778
+ if (type.flags & ts.TypeFlags.IndexedAccess) {
1779
+ const access = type;
1780
+ const object = closedForm(access.objectType) ?? resolvedObjectType(access.objectType);
1781
+ const index = resolvedIndexType(access.indexType);
1782
+ if (object.flags & ts.TypeFlags.Instantiable || !index.isStringLiteral())
1783
+ return null;
1784
+ const property = object.getProperty(index.value);
1785
+ return property ? checker.getTypeOfSymbol(property) : null;
1786
+ }
1787
+ const closed = closedForm(type) ?? type;
1788
+ return closed.flags & ts.TypeFlags.Instantiable ? null : closed;
1789
+ };
1790
+ const parametersOperatorShape = (type) => {
1791
+ const argument = operatorArgument(type, 'Parameters');
1792
+ const callee = argument ? closedCallee(argument) : null;
1793
+ const signatures = callee?.getCallSignatures() ?? [];
1794
+ const signature = signatures[0];
1795
+ if (signatures.length !== 1 || !signature || (signature.typeParameters?.length ?? 0) > 0)
1796
+ return null;
1797
+ const elements = [];
1798
+ for (const parameter of signature.getParameters()) {
1799
+ const declaration = parameter.valueDeclaration;
1800
+ const declared = checker.getTypeOfSymbol(parameter);
1801
+ if (declaration && ts.isParameter(declaration) && declaration.dotDotDotToken) {
1802
+ if (!checker.isArrayType(declared))
1803
+ return null;
1804
+ const element = checker.getTypeArguments(declared)[0];
1805
+ if (!element)
1806
+ return null;
1807
+ elements.push({ type: typeOf(element), optional: false, rest: true, variadic: false });
1808
+ continue;
1809
+ }
1810
+ const optional = declaration !== undefined && ts.isParameter(declaration) && checker.isOptionalParameter(declaration);
1811
+ elements.push({ type: typeOf(optional ? checker.getNonNullableType(declared) : declared), optional, rest: false, variadic: false });
1812
+ }
1813
+ return table.intern({ kind: 'tuple', elements, readonly: false });
1814
+ };
1815
+ /**
1816
+ * The stand-in record arms (`record-stand-in-arms.ts`) as the shapes that
1817
+ * admit only themselves, or `null` when one is not a plain record -- then
1818
+ * nothing is added and certification keeps its refusal.
1819
+ */
1820
+ function standInArmIdsOf(records) {
1821
+ if (records === null)
1822
+ return null;
1823
+ const ids = [];
1824
+ for (const record of records) {
1825
+ const id = typeOf(record);
1826
+ const shape = table.get(id).shape;
1827
+ if (shape.kind !== 'object')
1828
+ return null;
1829
+ ids.push(shape.standIn ? id : table.intern({ ...shape, standIn: true }));
1830
+ }
1831
+ return ids;
1832
+ }
1310
1833
  function translate(type) {
1311
1834
  // Asked BEFORE anything else, because it answers about the very type that
1312
1835
  // was handed in rather than about its parts: an open member type of a
@@ -1343,6 +1866,9 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1343
1866
  const awaited = reducedOperator(type);
1344
1867
  if (awaited)
1345
1868
  return remember(type, typeOf(awaited));
1869
+ const parameterList = parametersOperatorShape(type);
1870
+ if (parameterList !== null)
1871
+ return remember(type, parameterList);
1346
1872
  // A conditional that still exists after this copy's instantiated-member
1347
1873
  // image was asked for, and that neither operator above could reduce, is
1348
1874
  // unresolved.
@@ -1351,7 +1877,7 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1351
1877
  const primitive = primitiveFor(type);
1352
1878
  if (primitive)
1353
1879
  return remember(type, table.intern(primitive));
1354
- const literal = literalFor(type);
1880
+ const literal = literalFor(checker, type);
1355
1881
  if (literal)
1356
1882
  return remember(type, table.intern(literal));
1357
1883
  const bag = bagShapeOfType(typeOf, bags, type);
@@ -1580,6 +2106,19 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1580
2106
  // dynamism: it IS the declared-any the program already carries.
1581
2107
  if ((objectType.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0)
1582
2108
  return remember(type, typeOf(objectType));
2109
+ // `args[0]` where `...args: Parameters<Events[K]>`: the object is the
2110
+ // deferred operator this copy closes to a tuple (`parametersOperatorShape`),
2111
+ // so a literal position reads that element -- possibly absent where the
2112
+ // element is optional or past a rest, as a tuple read anywhere else is.
2113
+ const parameterList = indexType.isNumberLiteral() ? parametersOperatorShape(access.objectType) : null;
2114
+ const listShape = parameterList === null ? null : table.get(parameterList).shape;
2115
+ if (listShape?.kind === 'tuple' && indexType.isNumberLiteral()) {
2116
+ const element = listShape.elements[indexType.value];
2117
+ const absent = typeOf(checker.getUndefinedType());
2118
+ if (!element)
2119
+ return remember(type, absent);
2120
+ return remember(type, element.optional || element.rest ? table.intern({ kind: 'union', members: [element.type, absent] }) : element.type);
2121
+ }
1583
2122
  const substituted = objectType === access.objectType && indexType === access.indexType ? null : indexedAccessMemberTypes(checker, objectType, indexType);
1584
2123
  // The bound of the type the PROGRAM WROTE is asked before the bound of
1585
2124
  // what this copy substituted into it, and the two disagree in hono's
@@ -1684,6 +2223,12 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1684
2223
  if (sole)
1685
2224
  return remember(type, typeOf(absent.substituteAbsentType(sole)));
1686
2225
  const present = arms.map((member) => absent.substituteAbsentType(member));
2226
+ // A record the program stores where this union names only its class --
2227
+ // `record-stand-in-arms.ts` -- is one more arm of the one carrier this
2228
+ // union type is, wherever it appears.
2229
+ const standInArms = standInArmIdsOf(standIns.armsOf(type));
2230
+ if (standInArms)
2231
+ return remember(type, table.intern({ kind: 'union', members: [...present.map(typeOf), ...standInArms] }));
1687
2232
  // A union of pure INDEX-SIGNATURE objects is one table whose values are
1688
2233
  // the union. `Record<string, string> | Record<string, string[]>` (hono's
1689
2234
  // `_getQueryParam`, `utils/url.ts:255`) describes one object either way:
@@ -1697,6 +2242,13 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1697
2242
  const table_ = joinedIndexUnionOf(checker, table, typeOf, present);
1698
2243
  return remember(type, table_ ?? table.intern({ kind: 'union', members: present.map(typeOf) }));
1699
2244
  }
2245
+ // A family view that is not a member -- an object literal the family
2246
+ // adopted, or a member through `Omit` and its kin (`interface-families.ts`'s
2247
+ // `viewMemberOf`) -- is the family's one layout, so handing it to the
2248
+ // family's other views moves nothing.
2249
+ const viewMember = families.viewMemberOf?.(type) ?? null;
2250
+ if (viewMember !== null)
2251
+ return remember(type, typeOf(viewMember));
1700
2252
  if (type.isIntersection()) {
1701
2253
  // The alias's own anchor, recorded beside the members rather than instead
1702
2254
  // of them: a branded alias (`type Rgb565 = number & { readonly
@@ -1724,6 +2276,29 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1724
2276
  const distributed = declaration === null ? distributedIntersectionOf(members) : null;
1725
2277
  if (distributed !== null)
1726
2278
  return remember(type, distributed);
2279
+ // The same reduction for a product with no union member, taken only
2280
+ // where it closes the product to ONE member or to `never`. Narrowing a
2281
+ // copy's `TSchema | null` away from null gives `Awaited<TSchema> & ({} |
2282
+ // undefined)`, and the checker cannot reduce it while `TSchema` is open;
2283
+ // after substitution `WithId<GridFSChunk> & {}` stood as an intersection
2284
+ // with an `unknown` member and derived a SECOND record for the one
2285
+ // filling. The yield slot of mongodb's `AbstractCursor`
2286
+ // `[Symbol.asyncIterator]` held that record while the narrowed read held
2287
+ // the filling's own, and no conversion joins two records of one type.
2288
+ const collapsed = declaration === null ? collapsedIntersectionOf(members) : undefined;
2289
+ if (collapsed !== undefined)
2290
+ return remember(type, collapsed ?? typeOf(checker.getNeverType()));
2291
+ // `Pick<D, Exclude<keyof D, K>> & { [k in K]: D[k] }` restores `D`
2292
+ // field for field -- mongodb's `WithId<GridFSFile>`, whose `_id` the
2293
+ // omit drops and the intersection puts back with the same type. It is
2294
+ // `D` to the language (identical properties), and a separately laid-out
2295
+ // record for it would give `FindCursor<WithId<GridFSFile>>` and
2296
+ // `FindCursor<GridFSFile>` two layouts that no conversion may join
2297
+ // without breaking the objects' aliasing. Asked for a named alias too:
2298
+ // `WithId` is one, and its name states no host carrier.
2299
+ const restated = restatedDeclaredOf(type);
2300
+ if (restated !== null)
2301
+ return remember(type, typeOf(restated));
1727
2302
  // The checker's own reconciliation of the members, interned beside them.
1728
2303
  // See the `resolved` field's doc comment (`model/structural-types.ts`):
1729
2304
  // reading `A & B`'s members off the intersection TYPE is asking the one
@@ -1737,7 +2312,16 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1737
2312
  // supplied an instantiated image. This lets recursive generic APIs fold
1738
2313
  // on their physical member layout instead of expanding type-only fluent
1739
2314
  // history indefinitely.
1740
- const resolved = carriesDeferredForm(type) ? null : table.intern(objectShapeOf(type, null, 'interface'));
2315
+ //
2316
+ // A TYPE-PARAMETER member is the same hole seen from the other side: the
2317
+ // checker reconciles `{ waitMS: number } & T` through `T`'s CONSTRAINT,
2318
+ // while `members` above carry the copy's own filling of `T`. Reading
2319
+ // the reconciliation there drops every member the filling has beyond
2320
+ // its bound (mongodb's `resolveTimeoutOptions` lost `name` off a
2321
+ // `Named & Timeouts` filling), so the substituted members stand alone.
2322
+ const resolved = carriesDeferredForm(type) || type.types.some((part) => (part.flags & ts.TypeFlags.TypeParameter) !== 0)
2323
+ ? null
2324
+ : table.intern(objectShapeOf(type, null, 'interface'));
1741
2325
  return remember(type, table.intern({ kind: 'intersection', members, declaration, resolved }));
1742
2326
  }
1743
2327
  const indexed = indexedShapeOf(type);
@@ -1808,6 +2392,25 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1808
2392
  return erasedTypeArgument();
1809
2393
  return typeOf(canonical?.[index] ?? argument);
1810
2394
  });
2395
+ // A REINTERPRETED class (`specialization.ts`'s `reinterpretedClasses`)
2396
+ // has one layout, its `any` copy, and every concrete instantiation is
2397
+ // only a view of it. That copy may have no checker spelling at all, so
2398
+ // its body is built from the class's own declared type read through
2399
+ // the copy's bindings -- `transform: (doc: TSchema) => any` as
2400
+ // `(doc: any) => any` -- and never from the concrete view that happened
2401
+ // to reach the anchor first, which would store one view's filling.
2402
+ const reinterpretedOrdinal = declared.kind === 'class-instance' && genericOwner && ts.isClassLike(genericOwner)
2403
+ ? specializations.reinterpretedCopyOf(genericOwner)
2404
+ : null;
2405
+ if (reinterpretedOrdinal !== null && genericOwner) {
2406
+ const ownerSymbol = type.target?.getSymbol() ?? type.getSymbol();
2407
+ const generic = ownerSymbol ? checker.getDeclaredTypeOfSymbol(ownerSymbol) : null;
2408
+ if (generic && generic !== type) {
2409
+ const folded = mapperFor(copyPathOf({ declaration: genericOwner, ordinal: reinterpretedOrdinal })).typeOf(generic);
2410
+ remember(type, folded);
2411
+ return folded;
2412
+ }
2413
+ }
1811
2414
  // Reserved before the body is built, because building it walks members and
1812
2415
  // a member can reach this same anchor through a second checker type
1813
2416
  // object. `fresh` says which of the two this call is: the reserver
@@ -1854,6 +2457,9 @@ const buildMapper = (checker, identities, table, instantiations, specializations
1854
2457
  // implementation's `T` is substituted exactly as its body's would be.
1855
2458
  // `valueTypeAt` gives the DECLARATION the same answer.
1856
2459
  const implementation = sourceOverloadImplementationOf(callSignatures, constructSignatures);
2460
+ const receiverCopy = implementation ? receiverCopyOfOverloadedMember(type, implementation) : null;
2461
+ if (receiverCopy !== null)
2462
+ return remember(type, mapperFor(copyPathOf(receiverCopy)).typeOf(type));
1857
2463
  const generic = genericSourceFunctionOf(type, callSignatures, constructSignatures, implementation);
1858
2464
  return remember(type, table.intern({
1859
2465
  kind: 'signature',
@@ -2118,9 +2724,36 @@ const buildMapper = (checker, identities, table, instantiations, specializations
2118
2724
  const receiver = absentSubstitutedTypeAt(node.expression);
2119
2725
  return (receiver.flags & ts.TypeFlags.Never) !== 0 ? receiver : own;
2120
2726
  };
2727
+ /**
2728
+ * The bare `object` keyword, alone or beside `null`/`undefined`. The
2729
+ * checker narrows an `unknown` by `typeof value === 'object'` to
2730
+ * `object | null`, and that union is where the boundary below was missed:
2731
+ * the operand of the `value != null` that follows was converted to the
2732
+ * zero-field record `object` lowers to -- an `adoptProduct` that allocates
2733
+ * a struct and migrates the document into an alias view -- only to test
2734
+ * the optional for presence. bson's `isAnyArrayBuffer` asked that of every
2735
+ * object it serialized; on the mongodb driver benchmark it was 4.5% of the
2736
+ * client's CPU.
2737
+ */
2738
+ const narrowedOnlyToObject = (type) => {
2739
+ if ((type.flags & ts.TypeFlags.NonPrimitive) !== 0)
2740
+ return true;
2741
+ if (!type.isUnion())
2742
+ return false;
2743
+ let object = false;
2744
+ for (const member of type.types) {
2745
+ if ((member.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) !== 0)
2746
+ continue;
2747
+ if ((member.flags & ts.TypeFlags.NonPrimitive) === 0)
2748
+ return false;
2749
+ object = true;
2750
+ }
2751
+ return object;
2752
+ };
2121
2753
  /**
2122
2754
  * A value declared `any`/`unknown` and narrowed only to the bare `object`
2123
- * type is still a dynamic boundary. `typeof value === 'object'` proves that
2755
+ * type (or to `object | null`, see `narrowedOnlyToObject`) is still a
2756
+ * dynamic boundary. `typeof value === 'object'` proves that
2124
2757
  * property operations are permitted; it does not discover a field layout
2125
2758
  * or turn the value into a closed empty record. Keeping the declaration's
2126
2759
  * carrier here lets `key in value` and later dynamic reads consult the real
@@ -2131,7 +2764,7 @@ const buildMapper = (checker, identities, table, instantiations, specializations
2131
2764
  const dynamicObjectBoundaryAt = (node) => {
2132
2765
  if (!ts.isIdentifier(node))
2133
2766
  return null;
2134
- if ((absentSubstitutedTypeAt(node).flags & ts.TypeFlags.NonPrimitive) === 0)
2767
+ if (!narrowedOnlyToObject(absentSubstitutedTypeAt(node)))
2135
2768
  return null;
2136
2769
  const symbol = checker.getSymbolAtLocation(node);
2137
2770
  const declaration = symbol?.valueDeclaration ?? symbol?.declarations?.[0];
@@ -2450,6 +3083,38 @@ const buildMapper = (checker, identities, table, instantiations, specializations
2450
3083
  return null;
2451
3084
  return identities.declarationIdOf(declaration, rootSpecialization);
2452
3085
  };
3086
+ /**
3087
+ * The class copy an overloaded method's value was read off, when this view
3088
+ * does not already bind that class's parameters.
3089
+ *
3090
+ * The overloads of `Collection<DataKey>.find` arrive instantiated, but the
3091
+ * one IMPLEMENTATION signature the value physically carries is read off the
3092
+ * open declaration, so a read from outside the class (mongodb's
3093
+ * `db.collection<DataKey>(c).find(filter, options)`) left `WithId<TSchema>`
3094
+ * and its conditionals naked. The copy whose instantiated class has this
3095
+ * very member type is the receiver's; reading the value under it binds the
3096
+ * implementation's class parameters exactly as the method's own body is.
3097
+ */
3098
+ const receiverCopyOfOverloadedMember = (type, implementation) => {
3099
+ const method = implementation.declaration;
3100
+ if (!method || !ts.isMethodDeclaration(method) || !ts.isClassLike(method.parent))
3101
+ return null;
3102
+ const owner = method.parent;
3103
+ const parameters = owner.typeParameters;
3104
+ if (!parameters || parameters.length === 0 || parameters.some((parameter) => boundByPath(parameter) !== null))
3105
+ return null;
3106
+ const name = ts.isIdentifier(method.name) || ts.isStringLiteral(method.name) ? method.name.text : null;
3107
+ if (name === null)
3108
+ return null;
3109
+ const copies = specializations.specializationsOf(owner);
3110
+ for (const [ordinal, copy] of copies.entries()) {
3111
+ const closed = copy.instantiated;
3112
+ const member = closed ? checker.getPropertyOfType(closed, name) : undefined;
3113
+ if (member && checker.getTypeOfSymbol(member) === type)
3114
+ return { declaration: owner, ordinal };
3115
+ }
3116
+ return null;
3117
+ };
2453
3118
  const copyPathOf = (site) => {
2454
3119
  const enclosing = identities.prefixFor(site.declaration, path);
2455
3120
  const last = enclosing[enclosing.length - 1];
@@ -2675,6 +3340,15 @@ const buildMapper = (checker, identities, table, instantiations, specializations
2675
3340
  if ((shape.kind === 'declared' || shape.kind === 'class-instance') && shape.body !== null)
2676
3341
  return valueIdOfShape(table.get(shape.body).shape);
2677
3342
  if (shape.kind === 'object' && !shape.membersDropped) {
3343
+ // An accessor member's descriptor is an ACCESSOR descriptor: `get` and
3344
+ // `set`, no `value`. The data-descriptor record minted below has no
3345
+ // field for either, so a shape that may answer with one keeps the
3346
+ // ambient `PropertyDescriptor`, which states both halves.
3347
+ const accessorMayAnswer = literalKey !== null
3348
+ ? shape.members.some((member) => member.accessor !== null && member.key.kind === 'string' && member.key.value === literalKey)
3349
+ : shape.members.some((member) => member.accessor !== null);
3350
+ if (accessorMayAnswer)
3351
+ return null;
2678
3352
  if (literalKey !== null) {
2679
3353
  // A literal key that names no member this record's own structural
2680
3354
  // type declares is not proof the key is absent: `Object.defineProperty(o,
@@ -3001,6 +3675,42 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3001
3675
  return null;
3002
3676
  return prototypeObjectMemberTypeAt(initializer) ?? prototypeObjectTypeAt(initializer);
3003
3677
  };
3678
+ // An authenticated intrinsic accessor getter (`intrinsic-accessor-getter.ts`)
3679
+ // is the builtin function itself, not the ambient `PropertyDescriptor.get():
3680
+ // any` the checker reports: a receiver-taking getter, `this: any` as every
3681
+ // prototype method read as a value states it (`prototypeMethodBodyOf`),
3682
+ // answering the tag or `undefined` (23.2.3.38). A local initialized to it
3683
+ // and never re-bound holds that same function, so the cell, its reads and
3684
+ // the initializer agree (`prototypeObjectLocalTypeAt`'s rule).
3685
+ const intrinsicAccessorGetterTypeAt = (node) => {
3686
+ const declaration = ts.isVariableDeclaration(node)
3687
+ ? node
3688
+ : ts.isIdentifier(node) && !ts.isVariableDeclaration(node.parent)
3689
+ ? (checker.getSymbolAtLocation(node)?.valueDeclaration ?? null)
3690
+ : null;
3691
+ let root = node;
3692
+ if (declaration !== null) {
3693
+ if (!ts.isVariableDeclaration(declaration) || !declaration.initializer || !ts.isIdentifier(declaration.name))
3694
+ return null;
3695
+ const initializer = declaration.initializer;
3696
+ const writes = flow?.writesToDeclaration(declaration) ?? null;
3697
+ if (writes === null || writes.some((write) => write.slot === 'whole' && write.value !== initializer))
3698
+ return null;
3699
+ root = unwrapErasedExpression(initializer);
3700
+ }
3701
+ if (intrinsicAccessorGetterChainOf(checker, root) === null)
3702
+ return null;
3703
+ const receiver = table.intern({ kind: 'primitive', primitive: 'any' });
3704
+ const tag = table.intern({
3705
+ kind: 'union',
3706
+ members: [table.intern({ kind: 'primitive', primitive: 'string' }), table.intern({ kind: 'primitive', primitive: 'undefined' })]
3707
+ });
3708
+ return table.intern({
3709
+ kind: 'signature',
3710
+ call: [{ parameters: [], minimumArity: 0, thisParameter: receiver, result: tag }],
3711
+ construct: []
3712
+ });
3713
+ };
3004
3714
  // A parameter every call site hands `X.prototype` to, and every read of it:
3005
3715
  // the census bound it to the checker's image of the argument (the instance
3006
3716
  // type), so it is re-asked here from the argument expressions themselves.
@@ -3038,6 +3748,12 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3038
3748
  // body's binding reads that box while the ABI still declares the checker's
3039
3749
  // image of the parameter, and `projection/abi.ts` refuses the convention
3040
3750
  // with "parameter N is bound as X but the ABI declares Y".
3751
+ // The SIGNATURE side of the `bivariant-slot-parameter` rule: the slot's
3752
+ // parameter is the physical one, so the ABI publishes it.
3753
+ const bivariantSlotParameterAt = (parameter) => {
3754
+ const slot = bivariantSlotParameterTypeOf(checker, parameter);
3755
+ return slot === null ? null : typeOf(slot);
3756
+ };
3041
3757
  const refusedArrayParameterTypeAt = (parameter) => {
3042
3758
  if (!unstatedNeverArray(checker, collections, layoutTypeAt, parameter))
3043
3759
  return null;
@@ -3148,6 +3864,255 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3148
3864
  const source = mapper.typeAt(erased);
3149
3865
  return table.get(source).shape.kind === 'array' ? source : mapper.typeAt(initializer);
3150
3866
  };
3867
+ /**
3868
+ * The object a literal with spreads builds, member by member, or `null` when
3869
+ * some part has no single closed shape here. A written key is its
3870
+ * initializer's widened type; a spread contributes the source's own data
3871
+ * members -- a class instance's fields, never its prototype's accessors --
3872
+ * optional throughout when the source may be `undefined`/`null`, which copy
3873
+ * nothing. A later key overwrites an earlier one in place, as the object's
3874
+ * property order does; an optional spread member can leave the earlier
3875
+ * value standing, so the two join.
3876
+ */
3877
+ const spreadLiteralShapeOf = (node) => {
3878
+ const members = [];
3879
+ const place = (member) => {
3880
+ const at = members.findIndex((held) => sameKey(held.key, member.key));
3881
+ if (at < 0) {
3882
+ members.push(member);
3883
+ return;
3884
+ }
3885
+ const held = members[at];
3886
+ members[at] = member.optional
3887
+ ? { ...member, type: table.intern({ kind: 'union', members: [held.type, member.type] }), optional: held.optional }
3888
+ : member;
3889
+ };
3890
+ for (const property of node.properties) {
3891
+ if (ts.isSpreadAssignment(property)) {
3892
+ const spread = spreadMembersOf(typeAt(property.expression));
3893
+ if (spread === null)
3894
+ return null;
3895
+ for (const member of spread)
3896
+ place(member);
3897
+ continue;
3898
+ }
3899
+ if (ts.isShorthandPropertyAssignment(property)) {
3900
+ if (property.objectAssignmentInitializer)
3901
+ return null;
3902
+ place({
3903
+ key: { kind: 'string', value: property.name.text },
3904
+ type: typeAt(property.name),
3905
+ optional: false,
3906
+ readonly: false,
3907
+ accessor: null
3908
+ });
3909
+ continue;
3910
+ }
3911
+ if (!ts.isPropertyAssignment(property))
3912
+ return null;
3913
+ const name = property.name;
3914
+ if (!ts.isIdentifier(name) && !ts.isStringLiteral(name))
3915
+ return null;
3916
+ const written = checker.getTypeAtLocation(property.initializer);
3917
+ const type = written.flags & ts.TypeFlags.Literal ? typeOf(checker.getBaseTypeOfLiteralType(written)) : typeAt(property.initializer);
3918
+ place({ key: { kind: 'string', value: name.text }, type, optional: false, readonly: false, accessor: null });
3919
+ }
3920
+ const own = table.intern({ kind: 'object', members, index: [], membersDropped: false });
3921
+ // In the copy whose record IS one of the seed's stand-ins, the literal
3922
+ // builds that very arm, so the binding holds it as itself.
3923
+ const standIn = standIns.recordsOf(node)?.find((record) => typeOf(record) === own);
3924
+ return standIn === undefined ? own : table.intern({ kind: 'object', members, index: [], membersDropped: false, standIn: true });
3925
+ };
3926
+ /**
3927
+ * The object a literal builds when one of its spreads copies an OPEN source
3928
+ * -- a type with an index signature -- or `null` when no spread does.
3929
+ *
3930
+ * TypeScript's spread type drops the source's index signatures once the
3931
+ * literal writes a key of its own (`{ ...handshakeDoc, speculativeAuthenticate
3932
+ * }` over mongodb's `HandshakeDocument extends Document` is a closed object
3933
+ * to the checker), but `CopyDataProperties` (ECMA-262 7.3.25) copies every
3934
+ * own enumerable key the source holds, so the value carries keys that closed
3935
+ * type does not list. A carrier derived from that type has nowhere to put
3936
+ * them. The literal is the written and named members, in order, over the
3937
+ * sources' index signatures: the checker's type with the open half restored.
3938
+ * Two open sources must agree on each key domain's value type; anything
3939
+ * this cannot state exactly declines to the checker's answer.
3940
+ */
3941
+ const openSpreadLiteralShapeOf = (node) => {
3942
+ const members = [];
3943
+ const index = [];
3944
+ const place = (member) => {
3945
+ const at = members.findIndex((held) => sameKey(held.key, member.key));
3946
+ if (at < 0) {
3947
+ members.push(member);
3948
+ return;
3949
+ }
3950
+ const held = members[at];
3951
+ members[at] = member.optional
3952
+ ? { ...member, type: table.intern({ kind: 'union', members: [held.type, member.type] }), optional: held.optional }
3953
+ : member;
3954
+ };
3955
+ for (const property of node.properties) {
3956
+ if (ts.isSpreadAssignment(property)) {
3957
+ const source = typeAt(property.expression);
3958
+ const sourceShape = table.get(source).shape;
3959
+ const present = sourceShape.kind === 'union'
3960
+ ? sourceShape.members.filter((member) => {
3961
+ const arm = table.get(member).shape;
3962
+ return !(arm.kind === 'primitive' && (arm.primitive === 'undefined' || arm.primitive === 'null'));
3963
+ })
3964
+ : [source];
3965
+ if (present.length !== 1)
3966
+ return null;
3967
+ const armShape = table.get(present[0]).shape;
3968
+ const body = armShape.kind === 'declared' ? armShape.body : armShape.kind === 'class-instance' ? null : present[0];
3969
+ const object = body === null ? null : table.get(body).shape;
3970
+ if (object?.kind !== 'object' || object.membersDropped)
3971
+ return null;
3972
+ const optional = sourceShape.kind === 'union';
3973
+ for (const member of object.members)
3974
+ place({ ...member, readonly: false, accessor: null, ...(optional ? { optional: true } : {}) });
3975
+ for (const entry of object.index) {
3976
+ if (entry.runtimeMembers !== undefined || entry.finite === true)
3977
+ return null;
3978
+ const held = index.find((existing) => existing.key === entry.key);
3979
+ if (held === undefined)
3980
+ index.push({ key: entry.key, value: entry.value, readonly: false });
3981
+ else if (held.value !== entry.value)
3982
+ return null;
3983
+ }
3984
+ continue;
3985
+ }
3986
+ if (ts.isShorthandPropertyAssignment(property)) {
3987
+ if (property.objectAssignmentInitializer)
3988
+ return null;
3989
+ place({
3990
+ key: { kind: 'string', value: property.name.text },
3991
+ type: typeAt(property.name),
3992
+ optional: false,
3993
+ readonly: false,
3994
+ accessor: null
3995
+ });
3996
+ continue;
3997
+ }
3998
+ if (!ts.isPropertyAssignment(property))
3999
+ return null;
4000
+ const name = property.name;
4001
+ if (!ts.isIdentifier(name) && !ts.isStringLiteral(name))
4002
+ return null;
4003
+ const written = checker.getTypeAtLocation(property.initializer);
4004
+ const type = written.flags & ts.TypeFlags.Literal ? typeOf(checker.getBaseTypeOfLiteralType(written)) : typeAt(property.initializer);
4005
+ place({ key: { kind: 'string', value: name.text }, type, optional: false, readonly: false, accessor: null });
4006
+ }
4007
+ if (index.length === 0)
4008
+ return null;
4009
+ return table.intern({ kind: 'object', members, index, membersDropped: false });
4010
+ };
4011
+ /**
4012
+ * The names each file declares with a spreading object literal, so a read
4013
+ * of any other name -- nearly every identifier -- is answered without a
4014
+ * symbol lookup.
4015
+ */
4016
+ const spreadLiteralCellNames = new Map();
4017
+ const spreadLiteralCellNamesOf = (file) => {
4018
+ const known = spreadLiteralCellNames.get(file);
4019
+ if (known !== undefined)
4020
+ return known;
4021
+ const names = new Set();
4022
+ const visit = (node) => {
4023
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer !== undefined) {
4024
+ let initializer = node.initializer;
4025
+ while (ts.isParenthesizedExpression(initializer))
4026
+ initializer = initializer.expression;
4027
+ if (ts.isObjectLiteralExpression(initializer) && initializer.properties.some(ts.isSpreadAssignment))
4028
+ names.add(node.name.text);
4029
+ }
4030
+ ts.forEachChild(node, visit);
4031
+ };
4032
+ visit(file);
4033
+ spreadLiteralCellNames.set(file, names);
4034
+ return names;
4035
+ };
4036
+ /** `object-literal-spreading-an-open-source`'s answer for a spreading literal, a `const` it initializes, or a read of that `const`. */
4037
+ const openSpreadResolutionOf = (node) => {
4038
+ const literal = ts.isObjectLiteralExpression(node) ? node : openSpreadCellInitializerOf(node);
4039
+ if (literal === null || !literal.properties.some(ts.isSpreadAssignment))
4040
+ return null;
4041
+ const checked = checker.getTypeAtLocation(literal);
4042
+ if ((checked.flags & ts.TypeFlags.Any) !== 0 || checker.getIndexInfosOfType(checked).length > 0)
4043
+ return null;
4044
+ return openSpreadLiteralShapeOf(literal);
4045
+ };
4046
+ /** The object literal a `const` with no written type is initialized with, for the declaration or a read of it. */
4047
+ const openSpreadCellInitializerOf = (node) => {
4048
+ if (ts.isIdentifier(node) && !spreadLiteralCellNamesOf(node.getSourceFile()).has(node.text))
4049
+ return null;
4050
+ const declaration = ts.isVariableDeclaration(node)
4051
+ ? node
4052
+ : ts.isIdentifier(node) && ts.isShorthandPropertyAssignment(node.parent) && node.parent.name === node
4053
+ ? checker.getShorthandAssignmentValueSymbol(node.parent)?.valueDeclaration
4054
+ : ts.isIdentifier(node) && !ts.isVariableDeclaration(node.parent)
4055
+ ? checker.getSymbolAtLocation(node)?.valueDeclaration
4056
+ : undefined;
4057
+ if (!declaration || !ts.isVariableDeclaration(declaration) || declaration.type !== undefined || !declaration.initializer)
4058
+ return null;
4059
+ if (!ts.isIdentifier(declaration.name) || (ts.getCombinedNodeFlags(declaration) & ts.NodeFlags.Const) === 0)
4060
+ return null;
4061
+ let initializer = declaration.initializer;
4062
+ while (ts.isParenthesizedExpression(initializer))
4063
+ initializer = initializer.expression;
4064
+ return ts.isObjectLiteralExpression(initializer) ? initializer : null;
4065
+ };
4066
+ const sameKey = (left, right) => left.kind === right.kind &&
4067
+ (left.kind === 'symbol' ? left.declaration === right.declaration : left.value === right.value);
4068
+ const spreadMembersOf = (source) => {
4069
+ const shape = table.get(source).shape;
4070
+ if (shape.kind === 'union') {
4071
+ const present = shape.members.filter((member) => {
4072
+ const arm = table.get(member).shape;
4073
+ return !(arm.kind === 'primitive' && (arm.primitive === 'undefined' || arm.primitive === 'null'));
4074
+ });
4075
+ if (present.length !== 1)
4076
+ return null;
4077
+ const members = spreadMembersOf(present[0]);
4078
+ return members === null ? null : members.map((member) => ({ ...member, optional: true }));
4079
+ }
4080
+ const classInstance = shape.kind === 'class-instance';
4081
+ const body = shape.kind === 'class-instance' || shape.kind === 'declared' ? shape.body : source;
4082
+ const object = body === null ? null : table.get(body).shape;
4083
+ // A class body is enumerated data-only, so its dropped members are the
4084
+ // prototype's methods, which a spread never copies; anywhere else a
4085
+ // dropped member is an own property this shape does not list.
4086
+ if (object?.kind !== 'object' || (object.membersDropped && !classInstance) || object.index.length > 0)
4087
+ return null;
4088
+ // A private name is a PrivateElement, not an own property, so
4089
+ // CopyDataProperties never sees it.
4090
+ return object.members
4091
+ .filter((member) => !classInstance || (member.accessor === null && !(member.key.kind === 'string' && isPrivateNameKey(member.key.value))))
4092
+ .map((member) => ({ ...member, readonly: false, accessor: null }));
4093
+ };
4094
+ /**
4095
+ * Whether a literal spreads a class instance declaring a TypeScript
4096
+ * `private`/`protected` instance field.
4097
+ *
4098
+ * The checker's spread type drops those members -- the modifier is an
4099
+ * access check, and outside the class the copy may not name them -- but the
4100
+ * modifier is erased: the field is an ordinary own enumerable property, and
4101
+ * CopyDataProperties copies it. A carrier derived from the checker's type
4102
+ * would have nowhere to put it, and `JSON.stringify({ ...instance })` or
4103
+ * `Object.keys` over the copy would silently lose it.
4104
+ */
4105
+ const spreadsNonPublicClassField = (node) => node.properties.some((property) => {
4106
+ if (!ts.isSpreadAssignment(property))
4107
+ return false;
4108
+ const source = checker.getNonNullableType(checker.getTypeAtLocation(property.expression));
4109
+ return source
4110
+ .getProperties()
4111
+ .some((member) => (member.declarations ?? []).some((declaration) => (ts.isPropertyDeclaration(declaration) || ts.isParameter(declaration)) &&
4112
+ !ts.isPrivateIdentifier(declaration.name) &&
4113
+ (ts.getCombinedModifierFlags(declaration) & (ts.ModifierFlags.Private | ts.ModifierFlags.Protected)) !== 0 &&
4114
+ (ts.getCombinedModifierFlags(declaration) & ts.ModifierFlags.Static) === 0));
4115
+ });
3151
4116
  /**
3152
4117
  * Every step of `typeAt`, in the order the chain asked them.
3153
4118
  *
@@ -3166,8 +4131,142 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3166
4131
  * one is a row this phase owes a form, and the count of them is the honest
3167
4132
  * measure of how far the port has got.
3168
4133
  */
4134
+ /**
4135
+ * A reference `x instanceof Map` narrowed out of a declared union whose one
4136
+ * map arm is a `ReadonlyMap<K, V>` -- mongodb's `isMap(t: Sort)` is `t
4137
+ * instanceof Map && t.size > 0`. `ReadonlyMap` is not a subtype of `Map`
4138
+ * (it has no `set`), so the checker narrows to a synthesized `Map<any, any>`
4139
+ * that no arm of the union is, and reading the arm as that would ask for a
4140
+ * boxing view of a typed map. The only arm whose runtime value can pass the
4141
+ * test IS that map arm -- every other arm's carrier cannot hold a Map -- so
4142
+ * the read is that arm, exactly as a narrowing to a named arm would be.
4143
+ */
4144
+ const instanceofMapArmAt = (node) => {
4145
+ if (!ts.isIdentifier(node))
4146
+ return null;
4147
+ const narrowed = checker.getTypeAtLocation(node);
4148
+ if (!isStandardInterfaceType(checker, node, 'Map', narrowed))
4149
+ return null;
4150
+ if ((narrowed.objectFlags & ts.ObjectFlags.Reference) === 0)
4151
+ return null;
4152
+ const typeArguments = checker.getTypeArguments(narrowed);
4153
+ if (typeArguments.length !== 2 || !typeArguments.every((argument) => (argument.flags & ts.TypeFlags.Any) !== 0))
4154
+ return null;
4155
+ const symbol = checker.getSymbolAtLocation(node);
4156
+ if (!symbol)
4157
+ return null;
4158
+ const declared = checker.getTypeOfSymbol(symbol);
4159
+ if (!declared.isUnion())
4160
+ return null;
4161
+ const maps = declared.types.filter((member) => isStandardInterfaceType(checker, node, 'Map', member) || isStandardInterfaceType(checker, node, 'ReadonlyMap', member));
4162
+ return maps.length === 1 && maps[0] !== narrowed ? maps[0] : null;
4163
+ };
4164
+ /**
4165
+ * An `any` binding read where a guard narrowed it to lib's `ArrayBufferView`
4166
+ * -- bson's `ArrayBuffer.isView(value) || value instanceof ArrayBuffer` over
4167
+ * `value: any`, then `value.byteLength`. The interface leaves open WHICH view
4168
+ * sits behind it, so its generated record is a carrier no typed array or
4169
+ * DataView reaches: converting the box into it admits nothing and stops the
4170
+ * program. The value the guard tested is the box itself, whose payload keeps
4171
+ * its exact view identity, so the read stays the binding's own dynamic
4172
+ * carrier and a member read goes through the box's property protocol. Only a
4173
+ * binding whose own type is still `any` after the census qualifies -- a
4174
+ * binding the call graph proved concrete keeps that answer.
4175
+ */
4176
+ const anyReadNarrowedToOpenViewAt = (node) => {
4177
+ if (!ts.isIdentifier(node))
4178
+ return null;
4179
+ const narrowed = checker.getTypeAtLocation(node);
4180
+ if (!(narrowed.isUnion() ? narrowed.types : [narrowed]).some(isLibArrayBufferViewType))
4181
+ return null;
4182
+ const declaration = checker.getSymbolAtLocation(node)?.valueDeclaration;
4183
+ if (!declaration || !(ts.isParameter(declaration) || ts.isVariableDeclaration(declaration)) || !ts.isIdentifier(declaration.name))
4184
+ return null;
4185
+ if ((checker.getTypeAtLocation(declaration.name).flags & ts.TypeFlags.Any) === 0)
4186
+ return null;
4187
+ const own = mapper.typeAt(declaration.name);
4188
+ const shape = table.get(own).shape;
4189
+ return shape.kind === 'primitive' && shape.primitive === 'any' ? own : null;
4190
+ };
4191
+ /**
4192
+ * A binding of, or an un-narrowed read of, an overload implementation's
4193
+ * parameter some overload lets callers omit: it holds `undefined` whatever
4194
+ * the implementation's annotation says (`isOverloadOmissibleParameter`), so
4195
+ * the binding, its reads and the callable's slot all admit it. A read the
4196
+ * checker narrowed keeps its narrowed type; the conversion from the binding
4197
+ * then states the check.
4198
+ */
4199
+ const overloadOmissibleParameterAt = (node) => {
4200
+ if (ts.isParameter(node)) {
4201
+ if (!isOverloadOmissibleParameter(node))
4202
+ return null;
4203
+ return typeOf(checker.getNullableType(absentSubstitutedTypeAt(node), ts.TypeFlags.Undefined));
4204
+ }
4205
+ if (!ts.isIdentifier(node))
4206
+ return null;
4207
+ const symbol = checker.getSymbolAtLocation(node);
4208
+ const declaration = symbol?.valueDeclaration;
4209
+ if (!symbol || !declaration || !ts.isParameter(declaration) || declaration.name === node)
4210
+ return null;
4211
+ if (!isOverloadOmissibleParameter(declaration))
4212
+ return null;
4213
+ const read = absentSubstitutedTypeAt(node);
4214
+ if (read !== checker.getTypeOfSymbol(symbol))
4215
+ return null;
4216
+ return typeOf(checker.getNullableType(read, ts.TypeFlags.Undefined));
4217
+ };
3169
4218
  const mutableMethods = createMutableMethodResolver(checker, table, flow, signatureOf, (node) => mapper.typeAt(node), (node) => mapper.rawTypeAt(node));
3170
4219
  const structuralRules = [
4220
+ {
4221
+ // A read the checker narrowed to a bare class that may hold a record
4222
+ // spread from it -- see `record-stand-in-arms.ts`.
4223
+ name: 'record-stand-in-read',
4224
+ forms: [
4225
+ ts.SyntaxKind.Identifier,
4226
+ ts.SyntaxKind.AsExpression,
4227
+ ts.SyntaxKind.TypeAssertionExpression,
4228
+ ts.SyntaxKind.SatisfiesExpression,
4229
+ ts.SyntaxKind.NonNullExpression,
4230
+ ts.SyntaxKind.ConditionalExpression,
4231
+ ts.SyntaxKind.BinaryExpression
4232
+ ],
4233
+ resolve: (node) => {
4234
+ const arms = standIns.armsAt(node);
4235
+ if (arms === null)
4236
+ return null;
4237
+ const [standIn, ...records] = arms;
4238
+ const recordIds = standInArmIdsOf(records);
4239
+ return standIn === undefined || recordIds === null
4240
+ ? null
4241
+ : table.intern({ kind: 'union', members: [typeOf(standIn), ...recordIds] });
4242
+ }
4243
+ },
4244
+ {
4245
+ // `buf.equals && buf.equals(x)`: see `isHostMethodPresenceTest`.
4246
+ name: 'host-method-presence-test',
4247
+ forms: [ts.SyntaxKind.PropertyAccessExpression],
4248
+ resolve: (node) => ts.isPropertyAccessExpression(node) && isHostMethodPresenceTest(checker, node, absentSubstitutedTypeAt(node.expression))
4249
+ ? typeOf(checker.getBooleanType())
4250
+ : null
4251
+ },
4252
+ {
4253
+ name: 'overload-omissible-parameter',
4254
+ forms: [ts.SyntaxKind.Parameter, ts.SyntaxKind.Identifier],
4255
+ resolve: overloadOmissibleParameterAt
4256
+ },
4257
+ {
4258
+ name: 'any-read-narrowed-to-open-view',
4259
+ forms: [ts.SyntaxKind.Identifier],
4260
+ resolve: anyReadNarrowedToOpenViewAt
4261
+ },
4262
+ {
4263
+ name: 'instanceof-map-arm',
4264
+ forms: [ts.SyntaxKind.Identifier],
4265
+ resolve: (node) => {
4266
+ const arm = instanceofMapArmAt(node);
4267
+ return arm === null ? null : typeOf(arm);
4268
+ }
4269
+ },
3171
4270
  {
3172
4271
  name: 'mutable-method-storage',
3173
4272
  forms: [ts.SyntaxKind.PropertyAccessExpression, ts.SyntaxKind.ElementAccessExpression],
@@ -3248,6 +4347,28 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3248
4347
  return null;
3249
4348
  }
3250
4349
  },
4350
+ {
4351
+ // `JSON.stringify(value)` returns `undefined`, not a string, when the
4352
+ // value has no JSON form -- `undefined` itself, a function, a symbol
4353
+ // (ECMA-262 25.5.2.1 step 12, SerializeJSONProperty's final
4354
+ // `return undefined`). lib.d.ts declares `string` regardless, so a value
4355
+ // that may be one of those is typed here as it really behaves. The
4356
+ // MongoDB driver's handshake is the measured case:
4357
+ // `JSON.stringify(hello.maxWireVersion) ?? 0`, whose `?? 0` TypeScript
4358
+ // considers dead is the arm an old server's reply takes.
4359
+ name: 'json-stringify-may-be-undefined',
4360
+ forms: [ts.SyntaxKind.CallExpression],
4361
+ resolve: (node) => {
4362
+ if (!ts.isCallExpression(node) || !jsonStringifyMayHaveNoJsonForm(checker, node))
4363
+ return null;
4364
+ if (node.arguments[0] === undefined)
4365
+ return typeOf(checker.getUndefinedType());
4366
+ return table.intern({
4367
+ kind: 'union',
4368
+ members: [typeOf(checker.getStringType()), table.intern({ kind: 'primitive', primitive: 'undefined' })]
4369
+ });
4370
+ }
4371
+ },
3251
4372
  {
3252
4373
  // A `for (const key in object)` head, and every read of it. The language
3253
4374
  // answers outright and without reference to the object: for-in enumerates
@@ -3361,6 +4482,54 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3361
4482
  return null;
3362
4483
  }
3363
4484
  },
4485
+ {
4486
+ // A parameter stated narrower than the callable slot its function value
4487
+ // is written into, a name its object pattern binds, and a read of
4488
+ // either: the slot's storage, with the statement realized as checked
4489
+ // reads. See `bivariant-slot-parameter.ts`.
4490
+ name: 'bivariant-slot-parameter',
4491
+ forms: [ts.SyntaxKind.Parameter, ts.SyntaxKind.BindingElement, ts.SyntaxKind.Identifier],
4492
+ resolve: (node) => {
4493
+ const slot = ts.isParameter(node)
4494
+ ? bivariantSlotParameterTypeOf(checker, node)
4495
+ : ts.isBindingElement(node)
4496
+ ? bivariantSlotBindingTypeOf(checker, node)
4497
+ : bivariantSlotReadTypeOf(checker, node);
4498
+ return slot === null ? null : typeOf(slot);
4499
+ }
4500
+ },
4501
+ {
4502
+ // An element of such an array read as its stated element: the box.
4503
+ // See `bivariantSlotElementTypeOf`.
4504
+ name: 'bivariant-slot-element',
4505
+ forms: [ts.SyntaxKind.ElementAccessExpression, ts.SyntaxKind.VariableDeclaration, ts.SyntaxKind.Identifier],
4506
+ resolve: (node) => {
4507
+ const element = bivariantSlotElementTypeOf(checker, node);
4508
+ return element === null ? null : typeOf(element);
4509
+ }
4510
+ },
4511
+ {
4512
+ // A value that IS such a parameter's boxed-element array by identity,
4513
+ // whatever narrower array type the checker reads it as. See
4514
+ // `bivariantSlotArrayAliasTypeOf`.
4515
+ name: 'bivariant-slot-array-alias',
4516
+ forms: [
4517
+ ts.SyntaxKind.Identifier,
4518
+ ts.SyntaxKind.VariableDeclaration,
4519
+ ts.SyntaxKind.ParenthesizedExpression,
4520
+ ts.SyntaxKind.NonNullExpression,
4521
+ ts.SyntaxKind.SatisfiesExpression,
4522
+ ts.SyntaxKind.AsExpression,
4523
+ ts.SyntaxKind.TypeAssertionExpression,
4524
+ ts.SyntaxKind.ConditionalExpression,
4525
+ ts.SyntaxKind.BinaryExpression,
4526
+ ts.SyntaxKind.ElementAccessExpression
4527
+ ],
4528
+ resolve: (node) => {
4529
+ const alias = bivariantSlotArrayAliasTypeOf(checker, node);
4530
+ return alias === null ? null : typeOf(alias);
4531
+ }
4532
+ },
3364
4533
  {
3365
4534
  // `Function.prototype.bind`, read as the callee of its own call. The
3366
4535
  // ambient declaration is FIVE overloads -- one per bound-argument arity --
@@ -3429,6 +4598,11 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3429
4598
  return null;
3430
4599
  }
3431
4600
  },
4601
+ {
4602
+ name: 'intrinsic-accessor-getter',
4603
+ forms: [ts.SyntaxKind.PropertyAccessExpression, ts.SyntaxKind.VariableDeclaration, ts.SyntaxKind.Identifier],
4604
+ resolve: intrinsicAccessorGetterTypeAt
4605
+ },
3432
4606
  {
3433
4607
  name: 'array-pattern-rest',
3434
4608
  // The identifier arm resolves a SYMBOL to its declaration, so what that
@@ -3546,6 +4720,14 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3546
4720
  return null;
3547
4721
  }
3548
4722
  },
4723
+ {
4724
+ name: 'function-intersection-member',
4725
+ forms: [ts.SyntaxKind.PropertyAccessExpression],
4726
+ resolve: (node) => {
4727
+ const member = functionIntersectionMemberTypeOf(checker, node);
4728
+ return member === null ? null : typeOf(member);
4729
+ }
4730
+ },
3549
4731
  {
3550
4732
  name: 'prototype-object',
3551
4733
  // The union of the three resolvers this rule ORs: two answer for a
@@ -3602,6 +4784,26 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3602
4784
  return null;
3603
4785
  }
3604
4786
  },
4787
+ {
4788
+ // The merged-interface half of the same fact: a member only an
4789
+ // interface re-declares runs the base body, and where the interface's
4790
+ // view is a callable union the stored callable cannot be placed into,
4791
+ // the result is the body's. See `physicalInheritedCallableResultAt`.
4792
+ name: 'physical-inherited-callable-result',
4793
+ forms: [ts.SyntaxKind.CallExpression],
4794
+ resolve: (node) => {
4795
+ const physicalResult = physicalInheritedCallableResultAt(checker, node);
4796
+ return physicalResult ? typeOf(physicalResult) : null;
4797
+ }
4798
+ },
4799
+ {
4800
+ name: 'physical-inherited-callable-binding',
4801
+ forms: [ts.SyntaxKind.VariableDeclaration, ts.SyntaxKind.Identifier],
4802
+ resolve: (node) => {
4803
+ const physicalBinding = physicalInheritedCallableBindingAt(checker, node);
4804
+ return physicalBinding ? typeOf(physicalBinding) : null;
4805
+ }
4806
+ },
3605
4807
  {
3606
4808
  name: 'constructor-choice-result',
3607
4809
  forms: [ts.SyntaxKind.NewExpression],
@@ -3640,6 +4842,32 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3640
4842
  forms: [ts.SyntaxKind.BinaryExpression],
3641
4843
  resolve: (node) => ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken ? mapper.typeAt(node.right) : null
3642
4844
  },
4845
+ {
4846
+ // `JSON.stringify(v) ?? fallback` / `|| fallback` over a value that may
4847
+ // have no JSON form: the checker reads the left as `string`, so it keeps
4848
+ // only `string` and drops the fallback arm it thinks is dead. The rule
4849
+ // above widens the call to `string | undefined`; the logical result is
4850
+ // that call's kept `string` plus the fallback it can actually evaluate.
4851
+ name: 'json-stringify-fallback',
4852
+ forms: [ts.SyntaxKind.BinaryExpression],
4853
+ resolve: (node) => {
4854
+ if (!ts.isBinaryExpression(node))
4855
+ return null;
4856
+ const operator = node.operatorToken.kind;
4857
+ if (operator !== ts.SyntaxKind.QuestionQuestionToken && operator !== ts.SyntaxKind.BarBarToken)
4858
+ return null;
4859
+ const left = unwrapErasedExpression(node.left);
4860
+ if (!ts.isCallExpression(left) || left.arguments.length === 0 || !jsonStringifyMayHaveNoJsonForm(checker, left))
4861
+ return null;
4862
+ const right = mapper.typeAt(node.right);
4863
+ const rightShape = table.get(right).shape;
4864
+ if (rightShape.kind === 'primitive' && rightShape.primitive === 'any')
4865
+ return right;
4866
+ const string = typeOf(checker.getStringType());
4867
+ const members = [...new Set([string, ...(rightShape.kind === 'union' ? rightShape.members : [right])])];
4868
+ return members.length === 1 ? string : table.intern({ kind: 'union', members });
4869
+ }
4870
+ },
3643
4871
  {
3644
4872
  // A read off a type guard's narrowed family view publishes the FAMILY's
3645
4873
  // field, not the guard's restatement of it. `node.arguments` after
@@ -3656,7 +4884,16 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3656
4884
  if (ts.isPropertyAccessExpression(node)) {
3657
4885
  const receiver = checker.getTypeAtLocation(node.expression);
3658
4886
  const narrowedMember = receiver.isIntersection() ? narrowedFamilyMemberOf(receiver) : null;
3659
- const property = narrowedMember ? checker.getPropertyOfType(narrowedMember, node.name.text) : undefined;
4887
+ // Only a property the intersection's other parts RESTATE: one the
4888
+ // family member alone names keeps the checker's flow-sensitive
4889
+ // answer. mongodb's `options: CommandOptions & Abortable` (an
4890
+ // absorbed partner, `interface-families.ts`) reads
4891
+ // `options.documentsReturnedIn` after a `== null` guard, and the
4892
+ // declared `string | undefined` refused it as a computed key.
4893
+ const restated = narrowedMember !== null &&
4894
+ receiver.isIntersection() &&
4895
+ receiver.types.some((part) => part !== narrowedMember && checker.getPropertyOfType(part, node.name.text) !== undefined);
4896
+ const property = restated ? checker.getPropertyOfType(narrowedMember, node.name.text) : undefined;
3660
4897
  if (property)
3661
4898
  return typeOf(checker.getTypeOfSymbolAtLocation(property, node));
3662
4899
  }
@@ -3693,6 +4930,71 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3693
4930
  return null;
3694
4931
  }
3695
4932
  },
4933
+ {
4934
+ // A literal whose spread copies an open source keeps that source's
4935
+ // index signatures -- see `openSpreadLiteralShapeOf`. Only where the
4936
+ // checker's own type dropped them: a literal it already typed open, or
4937
+ // typed `any`, is answered by the checker or by the rule below.
4938
+ // A `const` the literal initializes, and every read of it, holds that
4939
+ // same open object: the checker types the cell from the closed literal
4940
+ // type, which is the hole this closes.
4941
+ name: 'object-literal-spreading-an-open-source',
4942
+ forms: [ts.SyntaxKind.ObjectLiteralExpression, ts.SyntaxKind.VariableDeclaration, ts.SyntaxKind.Identifier],
4943
+ resolve: (node) => {
4944
+ const open = openSpreadResolutionOf(node);
4945
+ if (open !== null || !ts.isObjectLiteralExpression(node) || node.properties.some(ts.isSpreadAssignment))
4946
+ return open;
4947
+ // A literal holding such an object as a member value -- mongodb's
4948
+ // Azure `prepareRequest` returns `{ headers, url }` where `headers`
4949
+ // is `{ ...options.headers, 'Content-Type': ..., Metadata: true }`.
4950
+ // The checker types the member by the same closed spread type, so the
4951
+ // literal is rebuilt from its members, each asked here in turn.
4952
+ const holdsOpen = node.properties.some((property) => {
4953
+ const value = ts.isShorthandPropertyAssignment(property)
4954
+ ? property.name
4955
+ : ts.isPropertyAssignment(property)
4956
+ ? property.initializer
4957
+ : null;
4958
+ if (value === null)
4959
+ return false;
4960
+ let unwrapped = value;
4961
+ while (ts.isParenthesizedExpression(unwrapped))
4962
+ unwrapped = unwrapped.expression;
4963
+ return openSpreadResolutionOf(unwrapped) !== null;
4964
+ });
4965
+ if (!holdsOpen || (checker.getTypeAtLocation(node).flags & ts.TypeFlags.Any) !== 0)
4966
+ return null;
4967
+ return spreadLiteralShapeOf(node);
4968
+ }
4969
+ },
4970
+ {
4971
+ name: 'object-literal-spreading-a-non-public-class-field',
4972
+ // The cell a `const` literal initializes is the literal's own object,
4973
+ // exactly as for an open source.
4974
+ forms: [ts.SyntaxKind.ObjectLiteralExpression, ts.SyntaxKind.VariableDeclaration, ts.SyntaxKind.Identifier],
4975
+ resolve: (node) => {
4976
+ const literal = ts.isObjectLiteralExpression(node) ? node : openSpreadCellInitializerOf(node);
4977
+ return literal !== null && spreadsNonPublicClassField(literal) ? spreadLiteralShapeOf(literal) : null;
4978
+ }
4979
+ },
4980
+ {
4981
+ // A literal the checker typed `any` only because it spreads a source it
4982
+ // could not close: mongodb's `emitAndLogHeartbeat<EventKey>` builds
4983
+ // `{ topologyId, serverConnectionId, ...args[0] }` with `args:
4984
+ // Parameters<Events[EventKey]>`, whose element is `any` to the checker in
4985
+ // the generic body -- and a spread of `any` makes the whole literal
4986
+ // `any`. Every copy knows `args[0]` (the rest tuple closes per copy), so
4987
+ // the literal's shape is its written members and the source's own data
4988
+ // members, in `CopyDataProperties` order. Boxing it was a typed value
4989
+ // lowered to the dynamic carrier for want of this answer.
4990
+ name: 'object-literal-spreading-a-deferred-source',
4991
+ forms: [ts.SyntaxKind.ObjectLiteralExpression],
4992
+ resolve: (node) => ts.isObjectLiteralExpression(node) &&
4993
+ (checker.getTypeAtLocation(node).flags & ts.TypeFlags.Any) !== 0 &&
4994
+ node.properties.some(ts.isSpreadAssignment)
4995
+ ? spreadLiteralShapeOf(node)
4996
+ : null
4997
+ },
3696
4998
  {
3697
4999
  // A name in callee position whose call instantiates a generic is typed by
3698
5000
  // the copy that call reaches, not by the generic it was written against:
@@ -3835,7 +5137,11 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3835
5137
  ts.SyntaxKind.VariableDeclaration,
3836
5138
  ts.SyntaxKind.PropertyDeclaration,
3837
5139
  ts.SyntaxKind.Identifier,
3838
- ts.SyntaxKind.PropertyAccessExpression
5140
+ ts.SyntaxKind.PropertyAccessExpression,
5141
+ ts.SyntaxKind.Parameter,
5142
+ ts.SyntaxKind.AsExpression,
5143
+ ts.SyntaxKind.TypeAssertionExpression,
5144
+ ts.SyntaxKind.CallExpression
3839
5145
  ],
3840
5146
  resolve: (node) => {
3841
5147
  const inferredCollection = inferredCollectionTypeArgumentsAt(collections, table, typeOf, bags, layoutTypeAt(node), node);
@@ -3991,6 +5297,22 @@ const buildMapper = (checker, identities, table, instantiations, specializations
3991
5297
  return null;
3992
5298
  }
3993
5299
  },
5300
+ {
5301
+ // `const Alias: CtorType = Cls as unknown as CtorType` holds `Cls`'s own
5302
+ // constructor: the assertions allocate nothing, heritage and `super()`
5303
+ // already read through them (`transparentConstClassAliasTarget`), and
5304
+ // the cell answering the annotation instead asked for a conversion of a
5305
+ // class constructor into a structural construct signature no class
5306
+ // constructor has (bson's `LongWithoutOverridesClass`).
5307
+ name: 'physical-class-alias',
5308
+ forms: [ts.SyntaxKind.VariableDeclaration, ts.SyntaxKind.Identifier],
5309
+ resolve: (node) => {
5310
+ const target = ts.isVariableDeclaration(node)
5311
+ ? transparentClassAliasDeclarationTarget(checker, node)
5312
+ : transparentConstClassAliasTarget(checker, node);
5313
+ return target ? typeOf(checker.getTypeAtLocation(target)) : null;
5314
+ }
5315
+ },
3994
5316
  {
3995
5317
  // The checker's constraint erasure over this copy's own binding. Guarded
3996
5318
  // on the substitution actually resolving: a generic whose copy binds
@@ -4031,8 +5353,15 @@ const buildMapper = (checker, identities, table, instantiations, specializations
4031
5353
  ],
4032
5354
  resolve: (node) => {
4033
5355
  const unionArms = parameters.unionArmsAt(node);
5356
+ // A map arm the collection census bound for this cell is that map, not
5357
+ // the checker's `Map<any, any>` (`inferredCollectionTypeArgumentsAt`).
5358
+ const armType = (arm) => inferredCollectionTypeArgumentsAt(collections, table, typeOf, bags, arm, node) ?? typeOf(arm);
5359
+ // One arm is a read the checker's flow narrowed to that arm of the
5360
+ // cell (`parameter-bindings.ts`'s `flowArmOf`): the arm, not a union.
5361
+ if (unionArms && unionArms.length === 1)
5362
+ return armType(unionArms[0]);
4034
5363
  if (unionArms)
4035
- return table.intern({ kind: 'union', members: unionArms.map((arm) => typeOf(arm)) });
5364
+ return table.intern({ kind: 'union', members: unionArms.map(armType) });
4036
5365
  return null;
4037
5366
  }
4038
5367
  },
@@ -4066,7 +5395,12 @@ const buildMapper = (checker, identities, table, instantiations, specializations
4066
5395
  disagreements.push(disagreement);
4067
5396
  }
4068
5397
  : undefined;
4069
- const typeAt = (node) => preparedRules.resolve(node, recordDisagreement) ?? typeOf(absentSubstitutedTypeAt(node));
5398
+ // Without `strictNullChecks` the checker's type states nothing about
5399
+ // absence, so a field or local whose writers store `null`/`undefined` holds
5400
+ // them beside that type -- see `sloppy-absence.ts`. Every mention of the
5401
+ // cell asks here, so its declaration and its reads stay one carrier.
5402
+ const withSloppyAbsence = (node, id) => withAbsences(table, id, sloppyAbsence.absencesAt(node));
5403
+ const typeAt = (node) => withForeignArms(withSloppyAbsence(node, preparedRules.resolve(node, recordDisagreement) ?? typeOf(absentSubstitutedTypeAt(node))), suppressedWrites.armsAt(node));
4070
5404
  const rawTypeAt = (node) => {
4071
5405
  // A binding pattern is the reference half of binding its source and has no
4072
5406
  // independent value type. TypeScript does not support every direct
@@ -4214,5 +5548,38 @@ const buildMapper = (checker, identities, table, instantiations, specializations
4214
5548
  structuralFormViolations: preparedRules.formViolations,
4215
5549
  classCopies: () => new Map([...classCopyKeys].map(([root, copies]) => [root, [...copies.values()].sort((a, b) => a.ordinal - b.ordinal)]))
4216
5550
  };
4217
- return mapper;
5551
+ // A declaration's value type gets the same absence its mentions do (`typeAt`
5552
+ // above); only a build without `strictNullChecks` supplies a census at all.
5553
+ if (sloppyAbsence === noSloppyAbsence && suppressedWrites === emptySuppressedWriteArmCensus)
5554
+ return mapper;
5555
+ return {
5556
+ ...mapper,
5557
+ valueTypeAt: (node) => withForeignArms(withSloppyAbsence(node, mapper.valueTypeAt(node)), suppressedWrites.armsAt(node))
5558
+ };
5559
+ };
5560
+ /**
5561
+ * `JSON.stringify(value)` from the default lib over a value that may have no
5562
+ * JSON form, so the call may return `undefined` although the lib declares
5563
+ * `string`. One predicate for the structural rule that publishes the wider
5564
+ * type and the invocation producer that licenses it.
5565
+ */
5566
+ export const jsonStringifyMayHaveNoJsonForm = (checker, node) => {
5567
+ const callee = unwrapErasedExpression(node.expression);
5568
+ if (!ts.isPropertyAccessExpression(callee) || callee.name.text !== 'stringify')
5569
+ return false;
5570
+ const owner = unwrapErasedExpression(callee.expression);
5571
+ if (!ts.isIdentifier(owner) || owner.text !== 'JSON')
5572
+ return false;
5573
+ const declarations = checker.getSymbolAtLocation(owner)?.declarations ?? [];
5574
+ if (declarations.length === 0 || !declarations.every((declaration) => declaration.getSourceFile().hasNoDefaultLib))
5575
+ return false;
5576
+ const argument = node.arguments[0];
5577
+ if (argument === undefined)
5578
+ return true;
5579
+ const mayHaveNoJsonForm = (type) => type.isUnion()
5580
+ ? type.types.some(mayHaveNoJsonForm)
5581
+ : (type.flags &
5582
+ (ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Undefined | ts.TypeFlags.Void | ts.TypeFlags.ESSymbolLike)) !==
5583
+ 0 || type.getCallSignatures().length > 0;
5584
+ return mayHaveNoJsonForm(checker.getTypeAtLocation(argument));
4218
5585
  };