funkscript 0.0.0-stage → 0.2.3

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 (631) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +204 -2
  3. package/dist/Widget.tsx +9 -0
  4. package/dist/ast/types.d.ts +513 -0
  5. package/dist/ast/types.d.ts.map +1 -0
  6. package/dist/ast/types.js +5 -0
  7. package/dist/ast/types.js.map +1 -0
  8. package/dist/ast/walk.d.ts +8 -0
  9. package/dist/ast/walk.d.ts.map +1 -0
  10. package/dist/ast/walk.js +23 -0
  11. package/dist/ast/walk.js.map +1 -0
  12. package/dist/cli/build-bun.d.ts +24 -0
  13. package/dist/cli/build-bun.d.ts.map +1 -0
  14. package/dist/cli/build-bun.js +190 -0
  15. package/dist/cli/build-bun.js.map +1 -0
  16. package/dist/cli/build-watch.d.ts +21 -0
  17. package/dist/cli/build-watch.d.ts.map +1 -0
  18. package/dist/cli/build-watch.js +244 -0
  19. package/dist/cli/build-watch.js.map +1 -0
  20. package/dist/cli/build.d.ts +4 -0
  21. package/dist/cli/build.d.ts.map +1 -0
  22. package/dist/cli/build.js +338 -0
  23. package/dist/cli/build.js.map +1 -0
  24. package/dist/cli/check.d.ts +4 -0
  25. package/dist/cli/check.d.ts.map +1 -0
  26. package/dist/cli/check.js +278 -0
  27. package/dist/cli/check.js.map +1 -0
  28. package/dist/cli/commands.d.ts +13 -0
  29. package/dist/cli/commands.d.ts.map +1 -0
  30. package/dist/cli/commands.js +262 -0
  31. package/dist/cli/commands.js.map +1 -0
  32. package/dist/cli/doc.d.ts +3 -0
  33. package/dist/cli/doc.d.ts.map +1 -0
  34. package/dist/cli/doc.js +71 -0
  35. package/dist/cli/doc.js.map +1 -0
  36. package/dist/cli/doctor.d.ts +3 -0
  37. package/dist/cli/doctor.d.ts.map +1 -0
  38. package/dist/cli/doctor.js +121 -0
  39. package/dist/cli/doctor.js.map +1 -0
  40. package/dist/cli/emit.d.ts +4 -0
  41. package/dist/cli/emit.d.ts.map +1 -0
  42. package/dist/cli/emit.js +87 -0
  43. package/dist/cli/emit.js.map +1 -0
  44. package/dist/cli/explain.d.ts +3 -0
  45. package/dist/cli/explain.d.ts.map +1 -0
  46. package/dist/cli/explain.js +103 -0
  47. package/dist/cli/explain.js.map +1 -0
  48. package/dist/cli/fmt.d.ts +3 -0
  49. package/dist/cli/fmt.d.ts.map +1 -0
  50. package/dist/cli/fmt.js +146 -0
  51. package/dist/cli/fmt.js.map +1 -0
  52. package/dist/cli/index.d.ts +3 -0
  53. package/dist/cli/index.d.ts.map +1 -0
  54. package/dist/cli/index.js +186 -0
  55. package/dist/cli/index.js.map +1 -0
  56. package/dist/cli/init.d.ts +10 -0
  57. package/dist/cli/init.d.ts.map +1 -0
  58. package/dist/cli/init.js +412 -0
  59. package/dist/cli/init.js.map +1 -0
  60. package/dist/cli/io.d.ts +9 -0
  61. package/dist/cli/io.d.ts.map +1 -0
  62. package/dist/cli/io.js +113 -0
  63. package/dist/cli/io.js.map +1 -0
  64. package/dist/cli/output-collisions.d.ts +2 -0
  65. package/dist/cli/output-collisions.d.ts.map +1 -0
  66. package/dist/cli/output-collisions.js +39 -0
  67. package/dist/cli/output-collisions.js.map +1 -0
  68. package/dist/cli/pipeline-style.d.ts +3 -0
  69. package/dist/cli/pipeline-style.d.ts.map +1 -0
  70. package/dist/cli/pipeline-style.js +45 -0
  71. package/dist/cli/pipeline-style.js.map +1 -0
  72. package/dist/cli/repl.d.ts +37 -0
  73. package/dist/cli/repl.d.ts.map +1 -0
  74. package/dist/cli/repl.js +334 -0
  75. package/dist/cli/repl.js.map +1 -0
  76. package/dist/cli/run.d.ts +4 -0
  77. package/dist/cli/run.d.ts.map +1 -0
  78. package/dist/cli/run.js +185 -0
  79. package/dist/cli/run.js.map +1 -0
  80. package/dist/cli/test.d.ts +3 -0
  81. package/dist/cli/test.d.ts.map +1 -0
  82. package/dist/cli/test.js +124 -0
  83. package/dist/cli/test.js.map +1 -0
  84. package/dist/cli/tsc.d.ts +3 -0
  85. package/dist/cli/tsc.d.ts.map +1 -0
  86. package/dist/cli/tsc.js +143 -0
  87. package/dist/cli/tsc.js.map +1 -0
  88. package/dist/cli/typecheck.d.ts +23 -0
  89. package/dist/cli/typecheck.d.ts.map +1 -0
  90. package/dist/cli/typecheck.js +65 -0
  91. package/dist/cli/typecheck.js.map +1 -0
  92. package/dist/compiler/ast-inspection.d.ts +18 -0
  93. package/dist/compiler/ast-inspection.d.ts.map +1 -0
  94. package/dist/compiler/ast-inspection.js +96 -0
  95. package/dist/compiler/ast-inspection.js.map +1 -0
  96. package/dist/compiler/boolean-operators.d.ts +8 -0
  97. package/dist/compiler/boolean-operators.d.ts.map +1 -0
  98. package/dist/compiler/boolean-operators.js +84 -0
  99. package/dist/compiler/boolean-operators.js.map +1 -0
  100. package/dist/compiler/check.d.ts +87 -0
  101. package/dist/compiler/check.d.ts.map +1 -0
  102. package/dist/compiler/check.js +1830 -0
  103. package/dist/compiler/check.js.map +1 -0
  104. package/dist/compiler/diagnostics.d.ts +6 -0
  105. package/dist/compiler/diagnostics.d.ts.map +1 -0
  106. package/dist/compiler/diagnostics.js +136 -0
  107. package/dist/compiler/diagnostics.js.map +1 -0
  108. package/dist/compiler/effect-mutation-rule.d.ts +4 -0
  109. package/dist/compiler/effect-mutation-rule.d.ts.map +1 -0
  110. package/dist/compiler/effect-mutation-rule.js +348 -0
  111. package/dist/compiler/effect-mutation-rule.js.map +1 -0
  112. package/dist/compiler/entry-rules.d.ts +5 -0
  113. package/dist/compiler/entry-rules.d.ts.map +1 -0
  114. package/dist/compiler/entry-rules.js +89 -0
  115. package/dist/compiler/entry-rules.js.map +1 -0
  116. package/dist/compiler/imported-record-functions.d.ts +4 -0
  117. package/dist/compiler/imported-record-functions.d.ts.map +1 -0
  118. package/dist/compiler/imported-record-functions.js +706 -0
  119. package/dist/compiler/imported-record-functions.js.map +1 -0
  120. package/dist/compiler/imported-schemas.d.ts +21 -0
  121. package/dist/compiler/imported-schemas.d.ts.map +1 -0
  122. package/dist/compiler/imported-schemas.js +461 -0
  123. package/dist/compiler/imported-schemas.js.map +1 -0
  124. package/dist/compiler/incremental-build.d.ts +23 -0
  125. package/dist/compiler/incremental-build.d.ts.map +1 -0
  126. package/dist/compiler/incremental-build.js +90 -0
  127. package/dist/compiler/incremental-build.js.map +1 -0
  128. package/dist/compiler/incremental-dependencies.d.ts +7 -0
  129. package/dist/compiler/incremental-dependencies.d.ts.map +1 -0
  130. package/dist/compiler/incremental-dependencies.js +190 -0
  131. package/dist/compiler/incremental-dependencies.js.map +1 -0
  132. package/dist/compiler/js-interop-nullability.d.ts +9 -0
  133. package/dist/compiler/js-interop-nullability.d.ts.map +1 -0
  134. package/dist/compiler/js-interop-nullability.js +57 -0
  135. package/dist/compiler/js-interop-nullability.js.map +1 -0
  136. package/dist/compiler/module-resolution.d.ts +6 -0
  137. package/dist/compiler/module-resolution.d.ts.map +1 -0
  138. package/dist/compiler/module-resolution.js +44 -0
  139. package/dist/compiler/module-resolution.js.map +1 -0
  140. package/dist/compiler/modules/output-collisions.d.ts +2 -0
  141. package/dist/compiler/modules/output-collisions.d.ts.map +1 -0
  142. package/dist/compiler/modules/output-collisions.js +39 -0
  143. package/dist/compiler/modules/output-collisions.js.map +1 -0
  144. package/dist/compiler/modules/output-plan.d.ts +7 -0
  145. package/dist/compiler/modules/output-plan.d.ts.map +1 -0
  146. package/dist/compiler/modules/output-plan.js +37 -0
  147. package/dist/compiler/modules/output-plan.js.map +1 -0
  148. package/dist/compiler/modules/resolution.d.ts +8 -0
  149. package/dist/compiler/modules/resolution.d.ts.map +1 -0
  150. package/dist/compiler/modules/resolution.js +48 -0
  151. package/dist/compiler/modules/resolution.js.map +1 -0
  152. package/dist/compiler/numeric-comparisons.d.ts +9 -0
  153. package/dist/compiler/numeric-comparisons.d.ts.map +1 -0
  154. package/dist/compiler/numeric-comparisons.js +153 -0
  155. package/dist/compiler/numeric-comparisons.js.map +1 -0
  156. package/dist/compiler/optional-arguments.d.ts +11 -0
  157. package/dist/compiler/optional-arguments.d.ts.map +1 -0
  158. package/dist/compiler/optional-arguments.js +246 -0
  159. package/dist/compiler/optional-arguments.js.map +1 -0
  160. package/dist/compiler/package-fingerprint.d.ts +7 -0
  161. package/dist/compiler/package-fingerprint.d.ts.map +1 -0
  162. package/dist/compiler/package-fingerprint.js +178 -0
  163. package/dist/compiler/package-fingerprint.js.map +1 -0
  164. package/dist/compiler/package-record-contracts.d.ts +5 -0
  165. package/dist/compiler/package-record-contracts.d.ts.map +1 -0
  166. package/dist/compiler/package-record-contracts.js +126 -0
  167. package/dist/compiler/package-record-contracts.js.map +1 -0
  168. package/dist/compiler/pipeline-companions.d.ts +18 -0
  169. package/dist/compiler/pipeline-companions.d.ts.map +1 -0
  170. package/dist/compiler/pipeline-companions.js +1042 -0
  171. package/dist/compiler/pipeline-companions.js.map +1 -0
  172. package/dist/compiler/pipelines/catalog.d.ts +15 -0
  173. package/dist/compiler/pipelines/catalog.d.ts.map +1 -0
  174. package/dist/compiler/pipelines/catalog.js +55 -0
  175. package/dist/compiler/pipelines/catalog.js.map +1 -0
  176. package/dist/compiler/pipelines/companions.d.ts +18 -0
  177. package/dist/compiler/pipelines/companions.d.ts.map +1 -0
  178. package/dist/compiler/pipelines/companions.js +1042 -0
  179. package/dist/compiler/pipelines/companions.js.map +1 -0
  180. package/dist/compiler/pipelines/resolution.d.ts +38 -0
  181. package/dist/compiler/pipelines/resolution.d.ts.map +1 -0
  182. package/dist/compiler/pipelines/resolution.js +571 -0
  183. package/dist/compiler/pipelines/resolution.js.map +1 -0
  184. package/dist/compiler/project-config.d.ts +28 -0
  185. package/dist/compiler/project-config.d.ts.map +1 -0
  186. package/dist/compiler/project-config.js +155 -0
  187. package/dist/compiler/project-config.js.map +1 -0
  188. package/dist/compiler/providers.d.ts +4 -0
  189. package/dist/compiler/providers.d.ts.map +1 -0
  190. package/dist/compiler/providers.js +101 -0
  191. package/dist/compiler/providers.js.map +1 -0
  192. package/dist/compiler/record-contracts.d.ts +6 -0
  193. package/dist/compiler/record-contracts.d.ts.map +1 -0
  194. package/dist/compiler/record-contracts.js +41 -0
  195. package/dist/compiler/record-contracts.js.map +1 -0
  196. package/dist/compiler/rules/control-flow.d.ts +10 -0
  197. package/dist/compiler/rules/control-flow.d.ts.map +1 -0
  198. package/dist/compiler/rules/control-flow.js +19 -0
  199. package/dist/compiler/rules/control-flow.js.map +1 -0
  200. package/dist/compiler/rules/diagnostic.d.ts +4 -0
  201. package/dist/compiler/rules/diagnostic.d.ts.map +1 -0
  202. package/dist/compiler/rules/diagnostic.js +2 -0
  203. package/dist/compiler/rules/diagnostic.js.map +1 -0
  204. package/dist/compiler/rules/module-scope-refs.d.ts +5 -0
  205. package/dist/compiler/rules/module-scope-refs.d.ts.map +1 -0
  206. package/dist/compiler/rules/module-scope-refs.js +47 -0
  207. package/dist/compiler/rules/module-scope-refs.js.map +1 -0
  208. package/dist/compiler/schemas/analysis.d.ts +13 -0
  209. package/dist/compiler/schemas/analysis.d.ts.map +1 -0
  210. package/dist/compiler/schemas/analysis.js +24 -0
  211. package/dist/compiler/schemas/analysis.js.map +1 -0
  212. package/dist/compiler/schemas/imported-record-functions.d.ts +4 -0
  213. package/dist/compiler/schemas/imported-record-functions.d.ts.map +1 -0
  214. package/dist/compiler/schemas/imported-record-functions.js +706 -0
  215. package/dist/compiler/schemas/imported-record-functions.js.map +1 -0
  216. package/dist/compiler/schemas/imported-schemas.d.ts +21 -0
  217. package/dist/compiler/schemas/imported-schemas.d.ts.map +1 -0
  218. package/dist/compiler/schemas/imported-schemas.js +461 -0
  219. package/dist/compiler/schemas/imported-schemas.js.map +1 -0
  220. package/dist/compiler/source-map.d.ts +6 -0
  221. package/dist/compiler/source-map.d.ts.map +1 -0
  222. package/dist/compiler/source-map.js +127 -0
  223. package/dist/compiler/source-map.js.map +1 -0
  224. package/dist/compiler/typescript-context.d.ts +33 -0
  225. package/dist/compiler/typescript-context.d.ts.map +1 -0
  226. package/dist/compiler/typescript-context.js +200 -0
  227. package/dist/compiler/typescript-context.js.map +1 -0
  228. package/dist/compiler.d.ts +77 -0
  229. package/dist/compiler.d.ts.map +1 -0
  230. package/dist/compiler.js +497 -0
  231. package/dist/compiler.js.map +1 -0
  232. package/dist/emitter/assemblyscript.d.ts +5 -0
  233. package/dist/emitter/assemblyscript.d.ts.map +1 -0
  234. package/dist/emitter/assemblyscript.js +979 -0
  235. package/dist/emitter/assemblyscript.js.map +1 -0
  236. package/dist/emitter/declarations.d.ts +46 -0
  237. package/dist/emitter/declarations.d.ts.map +1 -0
  238. package/dist/emitter/declarations.js +739 -0
  239. package/dist/emitter/declarations.js.map +1 -0
  240. package/dist/emitter/emitter.d.ts +165 -0
  241. package/dist/emitter/emitter.d.ts.map +1 -0
  242. package/dist/emitter/emitter.js +2448 -0
  243. package/dist/emitter/emitter.js.map +1 -0
  244. package/dist/emitter/imports.d.ts +6 -0
  245. package/dist/emitter/imports.d.ts.map +1 -0
  246. package/dist/emitter/imports.js +73 -0
  247. package/dist/emitter/imports.js.map +1 -0
  248. package/dist/emitter/indent.d.ts +3 -0
  249. package/dist/emitter/indent.d.ts.map +1 -0
  250. package/dist/emitter/indent.js +31 -0
  251. package/dist/emitter/indent.js.map +1 -0
  252. package/dist/emitter/jsx.d.ts +20 -0
  253. package/dist/emitter/jsx.d.ts.map +1 -0
  254. package/dist/emitter/jsx.js +82 -0
  255. package/dist/emitter/jsx.js.map +1 -0
  256. package/dist/emitter/local-bindings.d.ts +6 -0
  257. package/dist/emitter/local-bindings.d.ts.map +1 -0
  258. package/dist/emitter/local-bindings.js +32 -0
  259. package/dist/emitter/local-bindings.js.map +1 -0
  260. package/dist/emitter/match.d.ts +56 -0
  261. package/dist/emitter/match.d.ts.map +1 -0
  262. package/dist/emitter/match.js +1287 -0
  263. package/dist/emitter/match.js.map +1 -0
  264. package/dist/emitter/pipeline-catalog.d.ts +15 -0
  265. package/dist/emitter/pipeline-catalog.d.ts.map +1 -0
  266. package/dist/emitter/pipeline-catalog.js +55 -0
  267. package/dist/emitter/pipeline-catalog.js.map +1 -0
  268. package/dist/emitter/pipeline-resolution.d.ts +38 -0
  269. package/dist/emitter/pipeline-resolution.d.ts.map +1 -0
  270. package/dist/emitter/pipeline-resolution.js +571 -0
  271. package/dist/emitter/pipeline-resolution.js.map +1 -0
  272. package/dist/emitter/runtime-helpers.d.ts +10 -0
  273. package/dist/emitter/runtime-helpers.d.ts.map +1 -0
  274. package/dist/emitter/runtime-helpers.js +22 -0
  275. package/dist/emitter/runtime-helpers.js.map +1 -0
  276. package/dist/emitter/schemas.d.ts +36 -0
  277. package/dist/emitter/schemas.d.ts.map +1 -0
  278. package/dist/emitter/schemas.js +766 -0
  279. package/dist/emitter/schemas.js.map +1 -0
  280. package/dist/emitter/statements.d.ts +23 -0
  281. package/dist/emitter/statements.d.ts.map +1 -0
  282. package/dist/emitter/statements.js +216 -0
  283. package/dist/emitter/statements.js.map +1 -0
  284. package/dist/emitter/tagged-match.d.ts +23 -0
  285. package/dist/emitter/tagged-match.d.ts.map +1 -0
  286. package/dist/emitter/tagged-match.js +109 -0
  287. package/dist/emitter/tagged-match.js.map +1 -0
  288. package/dist/emitter/types.d.ts +22 -0
  289. package/dist/emitter/types.d.ts.map +1 -0
  290. package/dist/emitter/types.js +231 -0
  291. package/dist/emitter/types.js.map +1 -0
  292. package/dist/errors.d.ts +39 -0
  293. package/dist/errors.d.ts.map +1 -0
  294. package/dist/errors.js +98 -0
  295. package/dist/errors.js.map +1 -0
  296. package/dist/formatter/comments.d.ts +25 -0
  297. package/dist/formatter/comments.d.ts.map +1 -0
  298. package/dist/formatter/comments.js +283 -0
  299. package/dist/formatter/comments.js.map +1 -0
  300. package/dist/formatter/index.d.ts +71 -0
  301. package/dist/formatter/index.d.ts.map +1 -0
  302. package/dist/formatter/index.js +1113 -0
  303. package/dist/formatter/index.js.map +1 -0
  304. package/dist/formatter/operator-precedence.d.ts +3 -0
  305. package/dist/formatter/operator-precedence.d.ts.map +1 -0
  306. package/dist/formatter/operator-precedence.js +27 -0
  307. package/dist/formatter/operator-precedence.js.map +1 -0
  308. package/dist/formatter/prettier.d.ts +7 -0
  309. package/dist/formatter/prettier.d.ts.map +1 -0
  310. package/dist/formatter/prettier.js +51 -0
  311. package/dist/formatter/prettier.js.map +1 -0
  312. package/dist/index.d.ts +17 -0
  313. package/dist/index.d.ts.map +1 -0
  314. package/dist/index.js +17 -0
  315. package/dist/index.js.map +1 -0
  316. package/dist/interop/callback.d.ts +38 -0
  317. package/dist/interop/callback.d.ts.map +1 -0
  318. package/dist/interop/callback.js +130 -0
  319. package/dist/interop/callback.js.map +1 -0
  320. package/dist/interop/index.d.ts +6 -0
  321. package/dist/interop/index.d.ts.map +1 -0
  322. package/dist/interop/index.js +6 -0
  323. package/dist/interop/index.js.map +1 -0
  324. package/dist/interop/js.d.ts +16 -0
  325. package/dist/interop/js.d.ts.map +1 -0
  326. package/dist/interop/js.js +35 -0
  327. package/dist/interop/js.js.map +1 -0
  328. package/dist/interop/record.d.ts +9 -0
  329. package/dist/interop/record.d.ts.map +1 -0
  330. package/dist/interop/record.js +18 -0
  331. package/dist/interop/record.js.map +1 -0
  332. package/dist/interop/valibot.d.ts +9 -0
  333. package/dist/interop/valibot.d.ts.map +1 -0
  334. package/dist/interop/valibot.js +94 -0
  335. package/dist/interop/valibot.js.map +1 -0
  336. package/dist/interop/zod.d.ts +45 -0
  337. package/dist/interop/zod.d.ts.map +1 -0
  338. package/dist/interop/zod.js +143 -0
  339. package/dist/interop/zod.js.map +1 -0
  340. package/dist/lexer/lexer.d.ts +65 -0
  341. package/dist/lexer/lexer.d.ts.map +1 -0
  342. package/dist/lexer/lexer.js +1335 -0
  343. package/dist/lexer/lexer.js.map +1 -0
  344. package/dist/lexer/tokens.d.ts +96 -0
  345. package/dist/lexer/tokens.d.ts.map +1 -0
  346. package/dist/lexer/tokens.js +150 -0
  347. package/dist/lexer/tokens.js.map +1 -0
  348. package/dist/lsp/code-action-worker.d.ts +2 -0
  349. package/dist/lsp/code-action-worker.d.ts.map +1 -0
  350. package/dist/lsp/code-action-worker.js +17 -0
  351. package/dist/lsp/code-action-worker.js.map +1 -0
  352. package/dist/lsp/completion.d.ts +11 -0
  353. package/dist/lsp/completion.d.ts.map +1 -0
  354. package/dist/lsp/completion.js +260 -0
  355. package/dist/lsp/completion.js.map +1 -0
  356. package/dist/lsp/definition.d.ts +42 -0
  357. package/dist/lsp/definition.d.ts.map +1 -0
  358. package/dist/lsp/definition.js +1074 -0
  359. package/dist/lsp/definition.js.map +1 -0
  360. package/dist/lsp/diagnostics-worker.d.ts +2 -0
  361. package/dist/lsp/diagnostics-worker.d.ts.map +1 -0
  362. package/dist/lsp/diagnostics-worker.js +169 -0
  363. package/dist/lsp/diagnostics-worker.js.map +1 -0
  364. package/dist/lsp/docs.d.ts +37 -0
  365. package/dist/lsp/docs.d.ts.map +1 -0
  366. package/dist/lsp/docs.js +830 -0
  367. package/dist/lsp/docs.js.map +1 -0
  368. package/dist/lsp/error-channel.d.ts +3 -0
  369. package/dist/lsp/error-channel.d.ts.map +1 -0
  370. package/dist/lsp/error-channel.js +48 -0
  371. package/dist/lsp/error-channel.js.map +1 -0
  372. package/dist/lsp/hover.d.ts +5 -0
  373. package/dist/lsp/hover.d.ts.map +1 -0
  374. package/dist/lsp/hover.js +651 -0
  375. package/dist/lsp/hover.js.map +1 -0
  376. package/dist/lsp/imports.d.ts +5 -0
  377. package/dist/lsp/imports.d.ts.map +1 -0
  378. package/dist/lsp/imports.js +317 -0
  379. package/dist/lsp/imports.js.map +1 -0
  380. package/dist/lsp/index.d.ts +16 -0
  381. package/dist/lsp/index.d.ts.map +1 -0
  382. package/dist/lsp/index.js +17 -0
  383. package/dist/lsp/index.js.map +1 -0
  384. package/dist/lsp/inlay-hints.d.ts +3 -0
  385. package/dist/lsp/inlay-hints.d.ts.map +1 -0
  386. package/dist/lsp/inlay-hints.js +236 -0
  387. package/dist/lsp/inlay-hints.js.map +1 -0
  388. package/dist/lsp/interop-rename.d.ts +26 -0
  389. package/dist/lsp/interop-rename.d.ts.map +1 -0
  390. package/dist/lsp/interop-rename.js +346 -0
  391. package/dist/lsp/interop-rename.js.map +1 -0
  392. package/dist/lsp/match-arms.d.ts +3 -0
  393. package/dist/lsp/match-arms.d.ts.map +1 -0
  394. package/dist/lsp/match-arms.js +341 -0
  395. package/dist/lsp/match-arms.js.map +1 -0
  396. package/dist/lsp/navigation.d.ts +23 -0
  397. package/dist/lsp/navigation.d.ts.map +1 -0
  398. package/dist/lsp/navigation.js +430 -0
  399. package/dist/lsp/navigation.js.map +1 -0
  400. package/dist/lsp/parsed-documents.d.ts +25 -0
  401. package/dist/lsp/parsed-documents.d.ts.map +1 -0
  402. package/dist/lsp/parsed-documents.js +47 -0
  403. package/dist/lsp/parsed-documents.js.map +1 -0
  404. package/dist/lsp/rename-worker.d.ts +2 -0
  405. package/dist/lsp/rename-worker.d.ts.map +1 -0
  406. package/dist/lsp/rename-worker.js +27 -0
  407. package/dist/lsp/rename-worker.js.map +1 -0
  408. package/dist/lsp/server.d.ts +78 -0
  409. package/dist/lsp/server.d.ts.map +1 -0
  410. package/dist/lsp/server.js +1098 -0
  411. package/dist/lsp/server.js.map +1 -0
  412. package/dist/lsp/thunk-pipeline.d.ts +4 -0
  413. package/dist/lsp/thunk-pipeline.d.ts.map +1 -0
  414. package/dist/lsp/thunk-pipeline.js +95 -0
  415. package/dist/lsp/thunk-pipeline.js.map +1 -0
  416. package/dist/lsp/validation.d.ts +8 -0
  417. package/dist/lsp/validation.d.ts.map +1 -0
  418. package/dist/lsp/validation.js +124 -0
  419. package/dist/lsp/validation.js.map +1 -0
  420. package/dist/lsp/workspace.d.ts +8 -0
  421. package/dist/lsp/workspace.d.ts.map +1 -0
  422. package/dist/lsp/workspace.js +70 -0
  423. package/dist/lsp/workspace.js.map +1 -0
  424. package/dist/math.ts +1 -0
  425. package/dist/parser/declarations.d.ts +21 -0
  426. package/dist/parser/declarations.d.ts.map +1 -0
  427. package/dist/parser/declarations.js +626 -0
  428. package/dist/parser/declarations.js.map +1 -0
  429. package/dist/parser/errors.d.ts +9 -0
  430. package/dist/parser/errors.d.ts.map +1 -0
  431. package/dist/parser/errors.js +11 -0
  432. package/dist/parser/errors.js.map +1 -0
  433. package/dist/parser/index.d.ts +9 -0
  434. package/dist/parser/index.d.ts.map +1 -0
  435. package/dist/parser/index.js +9 -0
  436. package/dist/parser/index.js.map +1 -0
  437. package/dist/parser/jsx.d.ts +5 -0
  438. package/dist/parser/jsx.d.ts.map +1 -0
  439. package/dist/parser/jsx.js +188 -0
  440. package/dist/parser/jsx.js.map +1 -0
  441. package/dist/parser/operator-expressions.d.ts +16 -0
  442. package/dist/parser/operator-expressions.d.ts.map +1 -0
  443. package/dist/parser/operator-expressions.js +146 -0
  444. package/dist/parser/operator-expressions.js.map +1 -0
  445. package/dist/parser/parser.d.ts +104 -0
  446. package/dist/parser/parser.d.ts.map +1 -0
  447. package/dist/parser/parser.js +1216 -0
  448. package/dist/parser/parser.js.map +1 -0
  449. package/dist/parser/patterns.d.ts +9 -0
  450. package/dist/parser/patterns.d.ts.map +1 -0
  451. package/dist/parser/patterns.js +292 -0
  452. package/dist/parser/patterns.js.map +1 -0
  453. package/dist/parser/pipeline-expressions.d.ts +10 -0
  454. package/dist/parser/pipeline-expressions.d.ts.map +1 -0
  455. package/dist/parser/pipeline-expressions.js +57 -0
  456. package/dist/parser/pipeline-expressions.js.map +1 -0
  457. package/dist/parser/scope.d.ts +17 -0
  458. package/dist/parser/scope.d.ts.map +1 -0
  459. package/dist/parser/scope.js +56 -0
  460. package/dist/parser/scope.js.map +1 -0
  461. package/dist/parser/statements.d.ts +13 -0
  462. package/dist/parser/statements.d.ts.map +1 -0
  463. package/dist/parser/statements.js +737 -0
  464. package/dist/parser/statements.js.map +1 -0
  465. package/dist/parser/types.d.ts +13 -0
  466. package/dist/parser/types.d.ts.map +1 -0
  467. package/dist/parser/types.js +371 -0
  468. package/dist/parser/types.js.map +1 -0
  469. package/dist/plugins/bun-preload.d.ts +4 -0
  470. package/dist/plugins/bun-preload.d.ts.map +1 -0
  471. package/dist/plugins/bun-preload.js +18 -0
  472. package/dist/plugins/bun-preload.js.map +1 -0
  473. package/dist/plugins/bun.d.ts +115 -0
  474. package/dist/plugins/bun.d.ts.map +1 -0
  475. package/dist/plugins/bun.js +240 -0
  476. package/dist/plugins/bun.js.map +1 -0
  477. package/dist/plugins/esbuild.d.ts +45 -0
  478. package/dist/plugins/esbuild.d.ts.map +1 -0
  479. package/dist/plugins/esbuild.js +184 -0
  480. package/dist/plugins/esbuild.js.map +1 -0
  481. package/dist/plugins/type-view.d.ts +30 -0
  482. package/dist/plugins/type-view.d.ts.map +1 -0
  483. package/dist/plugins/type-view.js +245 -0
  484. package/dist/plugins/type-view.js.map +1 -0
  485. package/dist/plugins/vite.d.ts +56 -0
  486. package/dist/plugins/vite.d.ts.map +1 -0
  487. package/dist/plugins/vite.js +182 -0
  488. package/dist/plugins/vite.js.map +1 -0
  489. package/dist/service.ts +3 -0
  490. package/dist/service.ts.map +1 -0
  491. package/dist/testing/index.d.ts +24 -0
  492. package/dist/testing/index.d.ts.map +1 -0
  493. package/dist/testing/index.js +56 -0
  494. package/dist/testing/index.js.map +1 -0
  495. package/dist/tooling/doc.d.ts +82 -0
  496. package/dist/tooling/doc.d.ts.map +1 -0
  497. package/dist/tooling/doc.js +624 -0
  498. package/dist/tooling/doc.js.map +1 -0
  499. package/dist/tooling/idiomatic.d.ts +20 -0
  500. package/dist/tooling/idiomatic.d.ts.map +1 -0
  501. package/dist/tooling/idiomatic.js +154 -0
  502. package/dist/tooling/idiomatic.js.map +1 -0
  503. package/dist/tooling/migrate.d.ts +62 -0
  504. package/dist/tooling/migrate.d.ts.map +1 -0
  505. package/dist/tooling/migrate.js +608 -0
  506. package/dist/tooling/migrate.js.map +1 -0
  507. package/dist/tooling/pipeline-style.d.ts +12 -0
  508. package/dist/tooling/pipeline-style.d.ts.map +1 -0
  509. package/dist/tooling/pipeline-style.js +208 -0
  510. package/dist/tooling/pipeline-style.js.map +1 -0
  511. package/dist/version.d.ts +2 -0
  512. package/dist/version.d.ts.map +1 -0
  513. package/dist/version.js +25 -0
  514. package/dist/version.js.map +1 -0
  515. package/package.json +128 -4
  516. package/src/ast/types.ts +753 -0
  517. package/src/ast/walk.ts +35 -0
  518. package/src/cli/build-bun.ts +249 -0
  519. package/src/cli/build-watch.ts +299 -0
  520. package/src/cli/build.ts +450 -0
  521. package/src/cli/check.ts +342 -0
  522. package/src/cli/commands.ts +301 -0
  523. package/src/cli/doc.ts +81 -0
  524. package/src/cli/doctor.ts +173 -0
  525. package/src/cli/emit.ts +138 -0
  526. package/src/cli/explain.ts +127 -0
  527. package/src/cli/fmt.ts +170 -0
  528. package/src/cli/index.ts +227 -0
  529. package/src/cli/init.ts +491 -0
  530. package/src/cli/io.ts +150 -0
  531. package/src/cli/pipeline-style.ts +55 -0
  532. package/src/cli/repl.ts +443 -0
  533. package/src/cli/run.ts +238 -0
  534. package/src/cli/test.ts +148 -0
  535. package/src/cli/tsc.ts +207 -0
  536. package/src/cli/typecheck.ts +100 -0
  537. package/src/compiler/ast-inspection.ts +121 -0
  538. package/src/compiler/boolean-operators.ts +108 -0
  539. package/src/compiler/check.ts +2763 -0
  540. package/src/compiler/diagnostics.ts +179 -0
  541. package/src/compiler/effect-mutation-rule.ts +407 -0
  542. package/src/compiler/entry-rules.ts +116 -0
  543. package/src/compiler/incremental-build.ts +131 -0
  544. package/src/compiler/incremental-dependencies.ts +200 -0
  545. package/src/compiler/js-interop-nullability.ts +67 -0
  546. package/src/compiler/modules/output-collisions.ts +48 -0
  547. package/src/compiler/modules/output-plan.ts +46 -0
  548. package/src/compiler/modules/resolution.ts +56 -0
  549. package/src/compiler/numeric-comparisons.ts +213 -0
  550. package/src/compiler/optional-arguments.ts +335 -0
  551. package/src/compiler/package-fingerprint.ts +216 -0
  552. package/src/compiler/package-record-contracts.ts +156 -0
  553. package/src/compiler/pipelines/catalog.ts +1128 -0
  554. package/src/compiler/pipelines/companions.ts +1279 -0
  555. package/src/compiler/pipelines/resolution.ts +684 -0
  556. package/src/compiler/project-config.ts +221 -0
  557. package/src/compiler/record-contracts.ts +46 -0
  558. package/src/compiler/rules/control-flow.ts +57 -0
  559. package/src/compiler/rules/diagnostic.ts +11 -0
  560. package/src/compiler/rules/module-scope-refs.ts +63 -0
  561. package/src/compiler/schemas/analysis.ts +45 -0
  562. package/src/compiler/schemas/imported-record-functions.ts +984 -0
  563. package/src/compiler/schemas/imported-schemas.ts +761 -0
  564. package/src/compiler/source-map.ts +165 -0
  565. package/src/compiler/typescript-context.ts +250 -0
  566. package/src/compiler.ts +865 -0
  567. package/src/emitter/assemblyscript.ts +1220 -0
  568. package/src/emitter/declarations.ts +916 -0
  569. package/src/emitter/emitter.ts +3128 -0
  570. package/src/emitter/imports.ts +89 -0
  571. package/src/emitter/indent.ts +39 -0
  572. package/src/emitter/jsx.ts +122 -0
  573. package/src/emitter/local-bindings.ts +40 -0
  574. package/src/emitter/match.ts +1631 -0
  575. package/src/emitter/runtime-helpers.ts +31 -0
  576. package/src/emitter/schemas.ts +969 -0
  577. package/src/emitter/statements.ts +310 -0
  578. package/src/emitter/tagged-match.ts +171 -0
  579. package/src/emitter/types.ts +289 -0
  580. package/src/errors.ts +115 -0
  581. package/src/formatter/comments.ts +350 -0
  582. package/src/formatter/index.ts +1457 -0
  583. package/src/formatter/operator-precedence.ts +36 -0
  584. package/src/formatter/prettier.ts +61 -0
  585. package/src/index.ts +16 -0
  586. package/src/interop/callback.ts +188 -0
  587. package/src/interop/js.ts +66 -0
  588. package/src/interop/record.ts +36 -0
  589. package/src/interop/valibot.ts +141 -0
  590. package/src/interop/zod.ts +219 -0
  591. package/src/lexer/lexer.ts +1521 -0
  592. package/src/lexer/tokens.ts +174 -0
  593. package/src/lsp/code-action-worker.ts +31 -0
  594. package/src/lsp/completion.ts +343 -0
  595. package/src/lsp/definition.ts +1165 -0
  596. package/src/lsp/diagnostics-worker.ts +198 -0
  597. package/src/lsp/docs.ts +864 -0
  598. package/src/lsp/error-channel.ts +63 -0
  599. package/src/lsp/hover.ts +803 -0
  600. package/src/lsp/imports.ts +380 -0
  601. package/src/lsp/index.ts +55 -0
  602. package/src/lsp/inlay-hints.ts +308 -0
  603. package/src/lsp/interop-rename.ts +454 -0
  604. package/src/lsp/match-arms.ts +400 -0
  605. package/src/lsp/navigation.ts +553 -0
  606. package/src/lsp/parsed-documents.ts +64 -0
  607. package/src/lsp/rename-worker.ts +40 -0
  608. package/src/lsp/server.ts +1437 -0
  609. package/src/lsp/thunk-pipeline.ts +117 -0
  610. package/src/lsp/validation.ts +147 -0
  611. package/src/lsp/workspace.ts +74 -0
  612. package/src/parser/declarations.ts +808 -0
  613. package/src/parser/errors.ts +18 -0
  614. package/src/parser/jsx.ts +253 -0
  615. package/src/parser/operator-expressions.ts +170 -0
  616. package/src/parser/parser.ts +1565 -0
  617. package/src/parser/patterns.ts +342 -0
  618. package/src/parser/pipeline-expressions.ts +77 -0
  619. package/src/parser/scope.ts +69 -0
  620. package/src/parser/statements.ts +831 -0
  621. package/src/parser/types.ts +453 -0
  622. package/src/plugins/bun-preload.ts +25 -0
  623. package/src/plugins/bun.ts +448 -0
  624. package/src/plugins/esbuild.ts +308 -0
  625. package/src/plugins/type-view.ts +326 -0
  626. package/src/plugins/vite.ts +294 -0
  627. package/src/testing/index.ts +72 -0
  628. package/src/tooling/doc.ts +786 -0
  629. package/src/tooling/idiomatic.ts +202 -0
  630. package/src/tooling/pipeline-style.ts +248 -0
  631. package/src/version.ts +27 -0
@@ -0,0 +1,1631 @@
1
+ import type {
2
+ BindingTarget,
3
+ BooleanLiteral,
4
+ ConstructorPattern,
5
+ Expression,
6
+ FunctionBody,
7
+ LiteralPattern,
8
+ MatchArm,
9
+ MatchExpression,
10
+ Pattern,
11
+ RecordPattern,
12
+ RecordTypeNode,
13
+ StringLiteral,
14
+ TypeNode,
15
+ } from "../ast/types.js";
16
+ import { FunScriptError } from "../errors.js";
17
+ import { indentContinuation } from "./indent.js";
18
+ import {
19
+ emitUnpackedRecordPattern,
20
+ patternHasOptionalField,
21
+ } from "./declarations.js";
22
+
23
+ const JS_ERROR_NAMES = new Set([
24
+ "Error",
25
+ "TypeError",
26
+ "RangeError",
27
+ "SyntaxError",
28
+ "ReferenceError",
29
+ "URIError",
30
+ "EvalError",
31
+ ]);
32
+
33
+ export type RecordFieldInfo = {
34
+ optional: boolean;
35
+ defaultBinding?: string;
36
+ fields?: Map<string, RecordFieldInfo>;
37
+ };
38
+
39
+ interface MatchEmitterContext {
40
+ emitExpression(expression: Expression): string;
41
+ emitFunctionBody(body: FunctionBody): string;
42
+ emitArrowExpression(expression: Expression): string;
43
+ emitBindingTarget(target: BindingTarget | Pattern): string;
44
+ emitStringLiteral(literal: StringLiteral): string;
45
+ recordField(expression: Expression): RecordFieldInfo | undefined;
46
+ recordFields?(name: string): Map<string, RecordFieldInfo> | undefined;
47
+ getRecordTypeNode?(name: string): RecordTypeNode | undefined;
48
+ getVariantFields?(name: string): string[] | undefined;
49
+ isTaggedUnionVariant?(type: string, variant: string): boolean;
50
+ recordContracts?: Map<string, RecordTypeNode>;
51
+ getTypeNodeForExpression?(expression: Expression): TypeNode | undefined;
52
+ emitTaggedMatch?(
53
+ expression: Expression | undefined,
54
+ arms: MatchArm[],
55
+ inputType?: TypeNode,
56
+ pipelineSource?: Expression,
57
+ ): string | undefined;
58
+ isOptionalParameter(name: string): boolean;
59
+ isOptionalValue(expression: Expression): boolean;
60
+ requireTsPattern(): void;
61
+ addEffectImport?(name: string): void;
62
+ enterOptionalPayload(
63
+ name: string,
64
+ fields: Map<string, RecordFieldInfo>,
65
+ arm: MatchArm,
66
+ payloadType?: TypeNode,
67
+ ): void;
68
+ leaveOptionalPayload(): void;
69
+ enterOptionalRecordPattern?(
70
+ pattern: RecordPattern,
71
+ fields: Map<string, RecordFieldInfo>,
72
+ arm: MatchArm,
73
+ payloadType?: TypeNode,
74
+ ): void;
75
+ leaveOptionalRecordPattern?(): void;
76
+ }
77
+
78
+ /** Renders match expressions and their patterns using the enclosing emitter's scope. */
79
+ export class MatchEmitter {
80
+ constructor(private readonly context: MatchEmitterContext) {}
81
+
82
+ public emitMatchExpression(
83
+ expr: MatchExpression,
84
+ pipelineScrutineeType?: TypeNode,
85
+ pipelineSource?: Expression,
86
+ ): string {
87
+ if (expr.isCatch) {
88
+ return this.emitCatchExpression(expr);
89
+ }
90
+ if (!expr.scrutinee && !expr.isPipeline) {
91
+ return this.emitIfElseMatch(expr.arms, (arm) =>
92
+ this.emitPatternAsCondition(arm.pattern),
93
+ );
94
+ }
95
+
96
+ const scrutineeId =
97
+ expr.scrutinee?.kind === "Identifier" ? expr.scrutinee.name : undefined;
98
+ const isGuardOnlyNarrowingMatch =
99
+ Boolean(expr.scrutinee) &&
100
+ !expr.isPipeline &&
101
+ expr.arms.some((a) => Boolean(a.guard)) &&
102
+ expr.arms.every(
103
+ (a) =>
104
+ a.pattern.kind === "WildcardPattern" ||
105
+ (scrutineeId !== undefined &&
106
+ a.pattern.kind === "VariablePattern" &&
107
+ a.pattern.name.name === scrutineeId),
108
+ );
109
+
110
+ if (isGuardOnlyNarrowingMatch) {
111
+ return this.emitIfElseMatch(expr.arms, (arm) =>
112
+ arm.guard ? this.context.emitExpression(arm.guard) : "true",
113
+ );
114
+ }
115
+
116
+ const scrutineeType =
117
+ expr.scrutinee && !expr.isPipeline
118
+ ? this.context.getTypeNodeForExpression?.(expr.scrutinee)
119
+ : pipelineScrutineeType;
120
+ if (
121
+ scrutineeType?.kind === "TypeReferenceNode" &&
122
+ scrutineeType.name.name === "JSNullish"
123
+ ) {
124
+ return this.emitJSNullishMatch(expr.scrutinee, expr.arms);
125
+ }
126
+ const hasNullishFailurePattern = expr.arms.some((arm) => {
127
+ const p = arm.pattern;
128
+ return (
129
+ p.kind === "ConstructorPattern" &&
130
+ p.constructorName.name === "Failure" &&
131
+ p.args.some(
132
+ (arg) =>
133
+ arg.kind === "ConstructorPattern" &&
134
+ (arg.constructorName.name === "Null" ||
135
+ arg.constructorName.name === "Undefined"),
136
+ )
137
+ );
138
+ });
139
+ const isKnownTaggedFailure =
140
+ scrutineeType?.kind === "TypeReferenceNode" &&
141
+ (scrutineeType.name.name === "Result" ||
142
+ (this.context.isTaggedUnionVariant?.(
143
+ scrutineeType.name.name,
144
+ "Failure",
145
+ ) ??
146
+ false));
147
+ if (hasNullishFailurePattern && !isKnownTaggedFailure) {
148
+ throw new FunScriptError(
149
+ "Failure(Null) and Failure(Undefined) require a statically known JSNullish<T> scrutinee; add a JSNullish annotation before matching",
150
+ expr.span,
151
+ );
152
+ }
153
+ if (
154
+ scrutineeType?.kind === "TypeReferenceNode" &&
155
+ scrutineeType.name.name === "JSOptional"
156
+ ) {
157
+ return this.emitJSOptionalMatch(expr.scrutinee!, expr.arms);
158
+ }
159
+
160
+ // Scrutinee match or pipeline match => ts-pattern
161
+ this.context.requireTsPattern();
162
+ const isPipe = Boolean(expr.isPipeline);
163
+ let code = isPipe
164
+ ? `(($v) => ${this.context.emitTaggedMatch?.(undefined, expr.arms, pipelineScrutineeType, pipelineSource) ?? "match($v)"}`
165
+ : (this.context.emitTaggedMatch?.(expr.scrutinee, expr.arms) ??
166
+ `match(${this.context.emitExpression(expr.scrutinee!)})`);
167
+ const optionalRecord = expr.scrutinee
168
+ ? this.context.recordField(expr.scrutinee)
169
+ : undefined;
170
+ const payloadFields = optionalRecord?.optional
171
+ ? optionalRecord.fields
172
+ : undefined;
173
+ const isOptional = expr.scrutinee
174
+ ? this.context.isOptionalValue(expr.scrutinee)
175
+ : false;
176
+
177
+ const hasWildcard = expr.arms.some(
178
+ (a) => a.pattern.kind === "WildcardPattern",
179
+ );
180
+ const lastArm = expr.arms[expr.arms.length - 1];
181
+ const isBooleanLiteralPattern = (
182
+ p: Pattern,
183
+ ): p is LiteralPattern & { literal: BooleanLiteral } =>
184
+ p.kind === "LiteralPattern" && p.literal.kind === "BooleanLiteral";
185
+ const lastArmIsUnguardedBool = Boolean(
186
+ lastArm && !lastArm.guard && isBooleanLiteralPattern(lastArm.pattern),
187
+ );
188
+ const oppositeBoolValue =
189
+ lastArmIsUnguardedBool &&
190
+ lastArm &&
191
+ isBooleanLiteralPattern(lastArm.pattern)
192
+ ? !lastArm.pattern.literal.value
193
+ : undefined;
194
+ const hasOppositeUnguarded =
195
+ oppositeBoolValue !== undefined &&
196
+ expr.arms
197
+ .slice(0, -1)
198
+ .some(
199
+ (a) =>
200
+ !a.guard &&
201
+ isBooleanLiteralPattern(a.pattern) &&
202
+ a.pattern.literal.value === oppositeBoolValue,
203
+ );
204
+ const isExhaustiveBooleanMatch =
205
+ !hasWildcard && lastArmIsUnguardedBool && hasOppositeUnguarded;
206
+
207
+ for (let i = 0; i < expr.arms.length; i++) {
208
+ const arm = expr.arms[i];
209
+ const isLastArm = i === expr.arms.length - 1;
210
+ let payloadName: string | undefined;
211
+ let recordPattern: RecordPattern | undefined;
212
+ if (payloadFields) {
213
+ const pat = arm.pattern;
214
+ if (
215
+ pat.kind === "ConstructorPattern" &&
216
+ pat.constructorName.name === "Some" &&
217
+ pat.args.length === 1 &&
218
+ pat.args[0].kind === "VariablePattern"
219
+ ) {
220
+ payloadName = pat.args[0].name.name;
221
+ } else if (
222
+ pat.kind === "ConstructorPattern" &&
223
+ pat.constructorName.name === "Some" &&
224
+ pat.args.length === 1 &&
225
+ pat.args[0].kind === "RecordPattern"
226
+ ) {
227
+ recordPattern = pat.args[0];
228
+ } else if (
229
+ pat.kind === "ConstructorPattern" &&
230
+ pat.constructorName.name === "Some" &&
231
+ pat.args.length === 1
232
+ ) {
233
+ // Allowed: Some(...) with any pattern
234
+ } else if (!(
235
+ pat.kind === "WildcardPattern" ||
236
+ (pat.kind === "ConstructorPattern" &&
237
+ pat.constructorName.name === "None" &&
238
+ pat.args.length === 0)
239
+ )) {
240
+ throw new FunScriptError(
241
+ "Match an optional record with Some(name), Some({...}), None, or _",
242
+ pat.span,
243
+ );
244
+ }
245
+ }
246
+ let payloadType: TypeNode | undefined;
247
+ if (expr.scrutinee && this.context.getTypeNodeForExpression) {
248
+ const scrutineeType = this.context.getTypeNodeForExpression(
249
+ expr.scrutinee,
250
+ );
251
+ if (
252
+ scrutineeType?.kind === "TypeReferenceNode" &&
253
+ scrutineeType.name.name === "Option" &&
254
+ scrutineeType.typeArgs?.length === 1
255
+ ) {
256
+ payloadType = scrutineeType.typeArgs[0];
257
+ } else {
258
+ payloadType = scrutineeType;
259
+ }
260
+ }
261
+ if (payloadName && payloadFields) {
262
+ this.context.enterOptionalPayload(
263
+ payloadName,
264
+ payloadFields,
265
+ arm,
266
+ payloadType,
267
+ );
268
+ } else if (recordPattern && payloadFields) {
269
+ this.context.enterOptionalRecordPattern?.(
270
+ recordPattern,
271
+ payloadFields,
272
+ arm,
273
+ payloadType,
274
+ );
275
+ }
276
+ try {
277
+ if (
278
+ (arm.pattern.kind === "WildcardPattern" && !arm.guard) ||
279
+ (isExhaustiveBooleanMatch && isLastArm)
280
+ ) {
281
+ const body = this.emitArmHandler(
282
+ arm.body,
283
+ arm.pattern,
284
+ expr.scrutinee,
285
+ payloadFields,
286
+ );
287
+ code += `\n .otherwise(${body})`;
288
+ } else {
289
+ const pat = this.emitPattern(arm.pattern);
290
+ const body = this.emitArmHandler(
291
+ arm.body,
292
+ arm.pattern,
293
+ expr.scrutinee,
294
+ payloadFields,
295
+ );
296
+ if (arm.guard) {
297
+ let guardFn: string;
298
+ if (arm.pattern.kind === "RecordPattern") {
299
+ const scrutineeName =
300
+ expr.scrutinee?.kind === "Identifier"
301
+ ? expr.scrutinee.name
302
+ : undefined;
303
+ const unpackLines = this.emitRecordPatternUnpack(
304
+ arm.pattern,
305
+ "$matched",
306
+ );
307
+ if (unpackLines.length > 0) {
308
+ const lines = [
309
+ ...(scrutineeName
310
+ ? [`const ${scrutineeName} = $matched;`]
311
+ : []),
312
+ ...unpackLines,
313
+ `return ${indentContinuation(this.context.emitExpression(arm.guard), 4)};`,
314
+ ];
315
+ guardFn = `($matched) => {\n ${lines.join("\n ")}\n }`;
316
+ } else if (scrutineeName) {
317
+ guardFn = `(${scrutineeName}) => ${this.context.emitExpression(arm.guard)}`;
318
+ } else {
319
+ guardFn = `($matched) => ${this.context.emitExpression(arm.guard)}`;
320
+ }
321
+ } else if (
322
+ arm.pattern.kind === "OrPattern" &&
323
+ arm.pattern.patterns.every((p) => p.kind === "RecordPattern")
324
+ ) {
325
+ const scrutineeName =
326
+ expr.scrutinee?.kind === "Identifier"
327
+ ? expr.scrutinee.name
328
+ : undefined;
329
+ const unpackLines = this.emitPatternUnpackLines(
330
+ arm.pattern,
331
+ "$matched",
332
+ );
333
+ if (unpackLines.length > 0) {
334
+ const lines = [
335
+ ...(scrutineeName
336
+ ? [`const ${scrutineeName} = $matched;`]
337
+ : []),
338
+ ...unpackLines,
339
+ `return ${indentContinuation(this.context.emitExpression(arm.guard), 4)};`,
340
+ ];
341
+ guardFn = `($matched) => {\n ${lines.join("\n ")}\n }`;
342
+ } else if (scrutineeName) {
343
+ guardFn = `(${scrutineeName}) => ${this.context.emitExpression(arm.guard)}`;
344
+ } else {
345
+ guardFn = `($matched) => ${this.context.emitExpression(arm.guard)}`;
346
+ }
347
+ } else {
348
+ const vars = this.collectPatternVariables(arm.pattern);
349
+ if (vars.length > 0) {
350
+ const some =
351
+ arm.pattern.kind === "ConstructorPattern" &&
352
+ arm.pattern.constructorName.name === "Some" &&
353
+ arm.pattern.args.length === 1 &&
354
+ (arm.pattern.args[0].kind === "VariablePattern" ||
355
+ (arm.pattern.args[0].kind === "ArrayPattern" &&
356
+ this.isSimpleBindingPattern(arm.pattern.args[0])));
357
+ const someRecord =
358
+ arm.pattern.kind === "ConstructorPattern" &&
359
+ arm.pattern.constructorName.name === "Some" &&
360
+ arm.pattern.args.length === 1 &&
361
+ arm.pattern.args[0].kind === "RecordPattern" &&
362
+ (this.isSimpleBindingPattern(arm.pattern.args[0]) ||
363
+ patternHasOptionalField(
364
+ arm.pattern.args[0],
365
+ payloadFields,
366
+ ));
367
+ const directOptional =
368
+ expr.scrutinee?.kind === "Identifier" &&
369
+ this.context.isOptionalParameter(expr.scrutinee.name);
370
+ let unpack: string;
371
+ if (someRecord) {
372
+ unpack = this.emitSomeRecordUnpack(
373
+ (arm.pattern as ConstructorPattern)
374
+ .args[0] as RecordPattern,
375
+ payloadFields,
376
+ directOptional || isOptional,
377
+ );
378
+ } else if (arm.pattern.kind === "VariablePattern") {
379
+ unpack = `const ${vars[0]} = $matched;`;
380
+ } else if (some) {
381
+ const target = this.context.emitBindingTarget(
382
+ (arm.pattern as ConstructorPattern).args[0],
383
+ );
384
+ unpack = `const { value: ${target} } = $matched;`;
385
+ } else if (
386
+ arm.pattern.kind === "ConstructorPattern" &&
387
+ JS_ERROR_NAMES.has(arm.pattern.constructorName.name)
388
+ ) {
389
+ unpack = `const { ${vars.join(", ")} } = $matched;`;
390
+ } else {
391
+ unpack = this.emitPatternUnpackLines(
392
+ arm.pattern,
393
+ "$matched",
394
+ {
395
+ isOptionalScrutinee: directOptional || isOptional,
396
+ payloadFields,
397
+ },
398
+ ).join("\n ");
399
+ }
400
+ guardFn = `($matched) => {\n ${unpack}\n return ${indentContinuation(this.context.emitExpression(arm.guard), 4)};\n }`;
401
+ } else {
402
+ guardFn = `() => ${this.context.emitExpression(arm.guard)}`;
403
+ }
404
+ }
405
+ code += `\n .with(${pat}, ${guardFn}, ${body})`;
406
+ } else {
407
+ code += `\n .with(${pat}, ${body})`;
408
+ }
409
+ }
410
+ } finally {
411
+ if (payloadName && payloadFields) {
412
+ this.context.leaveOptionalPayload();
413
+ } else if (recordPattern && payloadFields) {
414
+ this.context.leaveOptionalRecordPattern?.();
415
+ }
416
+ }
417
+ }
418
+
419
+ if (!hasWildcard && !isExhaustiveBooleanMatch) {
420
+ code += `\n .exhaustive()`;
421
+ }
422
+
423
+ if (isPipe) {
424
+ code += `)`;
425
+ }
426
+
427
+ return code;
428
+ }
429
+
430
+ private emitPatternAsCondition(pattern: Pattern): string {
431
+ if (pattern.kind === "LiteralPattern") {
432
+ if (
433
+ pattern.literal.kind === "BooleanLiteral" &&
434
+ pattern.literal.rawExpr
435
+ ) {
436
+ return this.context.emitExpression(pattern.literal.rawExpr);
437
+ }
438
+ if (pattern.literal.kind === "BooleanLiteral") {
439
+ return pattern.literal.value ? "true" : "false";
440
+ }
441
+ if (pattern.literal.kind === "NumberLiteral") {
442
+ return `${pattern.literal.value}`;
443
+ }
444
+ return this.context.emitStringLiteral(pattern.literal);
445
+ }
446
+ return "true";
447
+ }
448
+
449
+ private isFilteringPattern(pat: Pattern | undefined): boolean {
450
+ if (!pat) return false;
451
+ if (pat.kind === "VariablePattern" || pat.kind === "WildcardPattern") {
452
+ return false;
453
+ }
454
+ return true;
455
+ }
456
+
457
+ private emitPattern(pat: Pattern): string {
458
+ if (pat.kind === "WildcardPattern") return "P._";
459
+ if (pat.kind === "LiteralPattern") {
460
+ if (pat.literal.kind === "BooleanLiteral")
461
+ return pat.literal.value ? "true" : "false";
462
+ if (pat.literal.kind === "NumberLiteral") return `${pat.literal.value}`;
463
+ return this.context.emitStringLiteral(pat.literal);
464
+ }
465
+ if (pat.kind === "VariablePattern") return `P.select("${pat.name.name}")`;
466
+ if (pat.kind === "ConstructorPattern") {
467
+ if (JS_ERROR_NAMES.has(pat.constructorName.name)) {
468
+ if (pat.args.length === 0) {
469
+ return `P.instanceOf(${pat.constructorName.name})`;
470
+ }
471
+ if (pat.args.length === 1) {
472
+ return `P.intersection(P.instanceOf(${pat.constructorName.name}), { message: ${this.emitPattern(pat.args[0])} })`;
473
+ }
474
+ }
475
+ if (pat.args.length === 0) {
476
+ return `{ _tag: "${pat.constructorName.name}" }`;
477
+ }
478
+ if (pat.constructorName.name === "Some" && pat.args.length === 1) {
479
+ const arg = pat.args[0];
480
+ if (
481
+ arg.kind === "ArrayPattern" ||
482
+ arg.kind === "LiteralPattern" ||
483
+ arg.kind === "OrPattern" ||
484
+ arg.kind === "ConstructorPattern"
485
+ ) {
486
+ return `{ _tag: "Some", value: ${this.emitPattern(arg)} }`;
487
+ }
488
+ if (arg.kind === "RecordPattern") {
489
+ const filteringFields = arg.fields.filter(
490
+ (f) => !f.isRest && this.isFilteringPattern(f.pattern),
491
+ );
492
+ if (filteringFields.length > 0) {
493
+ const fieldsStr = filteringFields
494
+ .map((f) => `${f.key.name}: ${this.emitPattern(f.pattern!)}`)
495
+ .join(", ");
496
+ return `{ _tag: "Some", value: { ${fieldsStr} } }`;
497
+ }
498
+ }
499
+ }
500
+ const fieldNames = this.context.getVariantFields?.(
501
+ pat.constructorName.name,
502
+ );
503
+ if (fieldNames && fieldNames.length === pat.args.length) {
504
+ const filteringFields: string[] = [];
505
+ for (let i = 0; i < fieldNames.length; i++) {
506
+ const arg = pat.args[i];
507
+ if (this.isFilteringPattern(arg)) {
508
+ filteringFields.push(`${fieldNames[i]}: ${this.emitPattern(arg)}`);
509
+ }
510
+ }
511
+ if (filteringFields.length > 0) {
512
+ return `{ _tag: "${pat.constructorName.name}", ${filteringFields.join(", ")} }`;
513
+ }
514
+ }
515
+ // Tagged union positional pattern matches fields
516
+ return `{ _tag: "${pat.constructorName.name}" }`;
517
+ }
518
+ if (pat.kind === "OrPattern") {
519
+ const sub = pat.patterns.map((p) => this.emitPattern(p)).join(", ");
520
+ return `P.union(${sub})`;
521
+ }
522
+ if (pat.kind === "RecordPattern") {
523
+ const fields = pat.fields
524
+ .filter((f) => !f.isRest)
525
+ .map((f) => {
526
+ if (!f.pattern || f.pattern.kind === "VariablePattern") {
527
+ return `${f.key.name}: P._`;
528
+ }
529
+ return `${f.key.name}: ${this.emitPattern(f.pattern)}`;
530
+ })
531
+ .join(", ");
532
+ return `{ ${fields} }`;
533
+ }
534
+ if (pat.kind === "ArrayPattern") {
535
+ const elements: string[] = [];
536
+ for (const el of pat.elements) {
537
+ if (el.kind === "RestPattern") {
538
+ elements.push("...P.array()");
539
+ } else if (
540
+ el.kind === "VariablePattern" ||
541
+ el.kind === "WildcardPattern"
542
+ ) {
543
+ elements.push("P._");
544
+ } else {
545
+ elements.push(this.emitPattern(el));
546
+ }
547
+ }
548
+ return `[${elements.join(", ")}]`;
549
+ }
550
+ return "P._";
551
+ }
552
+
553
+ private collectRecordDestructuring(pat: RecordPattern): string[] {
554
+ const parts: string[] = [];
555
+ const hasRest = pat.fields.some((f) => f.isRest);
556
+
557
+ for (const f of pat.fields) {
558
+ if (f.isRest) continue;
559
+ if (!f.pattern) {
560
+ parts.push(f.key.name);
561
+ } else if (f.pattern.kind === "VariablePattern") {
562
+ parts.push(`${f.key.name}: ${f.pattern.name.name}`);
563
+ } else if (f.pattern.kind === "RecordPattern") {
564
+ const sub = this.collectRecordDestructuring(f.pattern);
565
+ if (sub.length > 0) {
566
+ parts.push(`${f.key.name}: { ${sub.join(", ")} }`);
567
+ } else if (hasRest) {
568
+ parts.push(`${f.key.name}: _${f.key.name}`);
569
+ }
570
+ } else if (f.pattern.kind === "ArrayPattern") {
571
+ parts.push(
572
+ `${f.key.name}: ${this.context.emitBindingTarget(f.pattern)}`,
573
+ );
574
+ } else if (hasRest) {
575
+ parts.push(`${f.key.name}: _${f.key.name}`);
576
+ }
577
+ }
578
+
579
+ if (hasRest) {
580
+ const restField = pat.fields.find((f) => f.isRest)!;
581
+ parts.push(`...${restField.key.name}`);
582
+ }
583
+
584
+ return parts;
585
+ }
586
+
587
+ private emitSomeRecordUnpack(
588
+ pat: RecordPattern,
589
+ payloadFields?: Map<string, RecordFieldInfo>,
590
+ _isOptional?: boolean,
591
+ ): string {
592
+ if (patternHasOptionalField(pat, payloadFields)) {
593
+ this.context.addEffectImport?.("Option");
594
+ const cast = "";
595
+ const lines: string[] = [
596
+ `const { value: $funscriptSomeInner } = $matched${cast};`,
597
+ ...emitUnpackedRecordPattern({
598
+ pat,
599
+ basePath: "$funscriptSomeInner",
600
+ fieldsMap: payloadFields,
601
+ emitBindingTarget: (target) => this.context.emitBindingTarget(target),
602
+ addEffectImport: (name) => this.context.addEffectImport?.(name),
603
+ }),
604
+ ];
605
+ return lines.join("\n ");
606
+ }
607
+ const destructParts = this.collectRecordDestructuring(pat);
608
+ if (destructParts.length === 0) return "";
609
+ const cast = "";
610
+ return `const { value: { ${destructParts.join(", ")} } } = $matched${cast};`;
611
+ }
612
+
613
+ private emitArmHandler(
614
+ body: FunctionBody,
615
+ pat?: Pattern,
616
+ scrutinee?: Expression,
617
+ payloadFields?: Map<string, RecordFieldInfo>,
618
+ ): string {
619
+ if (
620
+ pat?.kind === "ConstructorPattern" &&
621
+ pat.args.some((arg) => arg.kind === "VariablePattern") &&
622
+ pat.args.every((arg) =>
623
+ ["VariablePattern", "WildcardPattern", "LiteralPattern"].includes(
624
+ arg.kind,
625
+ ),
626
+ ) &&
627
+ !JS_ERROR_NAMES.has(pat.constructorName.name)
628
+ ) {
629
+ const fields =
630
+ pat.constructorName.name === "Some" && pat.args.length === 1
631
+ ? ["value"]
632
+ : this.context.getVariantFields?.(pat.constructorName.name);
633
+ if (fields?.length === pat.args.length) {
634
+ const bindings = pat.args.flatMap((arg, index) =>
635
+ arg.kind === "VariablePattern"
636
+ ? [`${fields[index]}: ${arg.name.name}`]
637
+ : [],
638
+ );
639
+ const parameter = `({ ${bindings.join(", ")} })`;
640
+ return body.kind === "BlockStatement"
641
+ ? `${parameter} => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`
642
+ : `${parameter} => ${this.context.emitArrowExpression(body)}`;
643
+ }
644
+ }
645
+ if (pat?.kind === "RecordPattern") {
646
+ const scrutineeName =
647
+ scrutinee?.kind === "Identifier" ? scrutinee.name : undefined;
648
+ const unpackLines = this.emitRecordPatternUnpack(pat, "$matched");
649
+
650
+ if (unpackLines.length > 0) {
651
+ const lines: string[] = [];
652
+ if (scrutineeName) {
653
+ lines.push(`const ${scrutineeName} = $matched;`);
654
+ }
655
+ lines.push(...unpackLines);
656
+ if (body.kind === "BlockStatement") {
657
+ return `($matched) => {\n ${lines.join("\n ")}\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
658
+ }
659
+ return `($matched) => {\n ${lines.join("\n ")}\n return ${indentContinuation(this.context.emitExpression(body), 4)};\n }`;
660
+ }
661
+
662
+ if (scrutineeName) {
663
+ if (body.kind === "BlockStatement") {
664
+ return `(${scrutineeName}) => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
665
+ }
666
+ return `(${scrutineeName}) => ${this.context.emitArrowExpression(body)}`;
667
+ }
668
+
669
+ if (body.kind === "BlockStatement") {
670
+ return `($matched) => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
671
+ }
672
+ return `($matched) => ${this.context.emitArrowExpression(body)}`;
673
+ }
674
+
675
+ if (pat?.kind === "ArrayPattern") {
676
+ const scrutineeName =
677
+ scrutinee?.kind === "Identifier" ? scrutinee.name : undefined;
678
+ const names = this.collectPatternVariables(pat);
679
+ if (
680
+ names.length > 0 &&
681
+ new Set(names).size === names.length &&
682
+ (!scrutineeName || !names.includes(scrutineeName)) &&
683
+ pat.elements.every(
684
+ (element) =>
685
+ element.kind === "VariablePattern" ||
686
+ element.kind === "WildcardPattern",
687
+ )
688
+ ) {
689
+ const bindings = pat.elements.flatMap((element, index) =>
690
+ element.kind === "VariablePattern"
691
+ ? [`${index}: ${element.name.name}`]
692
+ : [],
693
+ );
694
+ const parameter = `({ ${bindings.join(", ")} }${scrutineeName ? `, ${scrutineeName}` : ""})`;
695
+ return body.kind === "BlockStatement"
696
+ ? `${parameter} => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`
697
+ : `${parameter} => ${this.context.emitArrowExpression(body)}`;
698
+ }
699
+ const lines: string[] = [];
700
+ if (scrutineeName) {
701
+ lines.push(`const ${scrutineeName} = $matched;`);
702
+ }
703
+ lines.push(...this.emitPatternUnpackLines(pat, "$matched"));
704
+ if (lines.length > 0) {
705
+ if (body.kind === "BlockStatement") {
706
+ return `($matched) => {\n ${lines.join("\n ")}\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
707
+ }
708
+ return `($matched) => {\n ${lines.join("\n ")}\n return ${indentContinuation(this.context.emitExpression(body), 4)};\n }`;
709
+ }
710
+ if (body.kind === "BlockStatement") {
711
+ return `() => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
712
+ }
713
+ return `() => ${this.context.emitArrowExpression(body)}`;
714
+ }
715
+
716
+ if (
717
+ pat?.kind === "OrPattern" &&
718
+ pat.patterns.every((p) => p.kind === "RecordPattern")
719
+ ) {
720
+ const scrutineeName =
721
+ scrutinee?.kind === "Identifier" ? scrutinee.name : undefined;
722
+ const first = pat.patterns[0];
723
+ if (first?.kind === "RecordPattern") {
724
+ const signature = this.patternBindingSignature(first);
725
+ const names = this.collectPatternVariables(first);
726
+ const safe =
727
+ names.length > 0 &&
728
+ new Set(names).size === names.length &&
729
+ (!scrutineeName || !names.includes(scrutineeName)) &&
730
+ pat.patterns.every(
731
+ (alternative) =>
732
+ alternative.kind === "RecordPattern" &&
733
+ this.patternBindingSignature(alternative) === signature &&
734
+ alternative.fields.every(
735
+ (field) =>
736
+ !field.isRest &&
737
+ (!field.pattern ||
738
+ [
739
+ "VariablePattern",
740
+ "WildcardPattern",
741
+ "LiteralPattern",
742
+ ].includes(field.pattern.kind)),
743
+ ),
744
+ );
745
+ if (safe) {
746
+ const bindings = this.collectRecordDestructuring(first);
747
+ const parameter = `({ ${bindings.join(", ")} }${scrutineeName ? `, ${scrutineeName}` : ""})`;
748
+ return body.kind === "BlockStatement"
749
+ ? `${parameter} => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`
750
+ : `${parameter} => ${this.context.emitArrowExpression(body)}`;
751
+ }
752
+ }
753
+ const unpackLines = this.emitPatternUnpackLines(pat, "$matched");
754
+ if (unpackLines.length > 0) {
755
+ const lines: string[] = [];
756
+ if (scrutineeName) {
757
+ lines.push(`const ${scrutineeName} = $matched;`);
758
+ }
759
+ lines.push(...unpackLines);
760
+ if (body.kind === "BlockStatement") {
761
+ return `($matched) => {\n ${lines.join("\n ")}\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
762
+ }
763
+ return `($matched) => {\n ${lines.join("\n ")}\n return ${indentContinuation(this.context.emitExpression(body), 4)};\n }`;
764
+ }
765
+ if (scrutineeName) {
766
+ if (body.kind === "BlockStatement") {
767
+ return `(${scrutineeName}) => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
768
+ }
769
+ return `(${scrutineeName}) => ${this.context.emitArrowExpression(body)}`;
770
+ }
771
+ if (body.kind === "BlockStatement") {
772
+ return `($matched) => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
773
+ }
774
+ return `($matched) => ${this.context.emitArrowExpression(body)}`;
775
+ }
776
+
777
+ const vars = pat ? this.collectPatternVariables(pat) : [];
778
+ const isOptional = scrutinee
779
+ ? this.context.isOptionalValue(scrutinee)
780
+ : false;
781
+ if (
782
+ pat?.kind === "ConstructorPattern" &&
783
+ JS_ERROR_NAMES.has(pat.constructorName.name)
784
+ ) {
785
+ if (vars.length > 0) {
786
+ const unpack = `const { ${vars.join(", ")} } = $matched;`;
787
+ if (body.kind === "BlockStatement") {
788
+ return `($matched) => {\n ${unpack}\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
789
+ }
790
+ return `($matched) => {\n ${unpack}\n return ${indentContinuation(this.context.emitExpression(body), 4)};\n }`;
791
+ }
792
+ if (body.kind === "BlockStatement") {
793
+ return `() => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
794
+ }
795
+ return `() => ${this.context.emitArrowExpression(body)}`;
796
+ }
797
+ if (
798
+ pat?.kind === "ConstructorPattern" &&
799
+ pat.constructorName.name === "Some" &&
800
+ pat.args.length === 1
801
+ ) {
802
+ const arg = pat.args[0];
803
+ if (
804
+ arg.kind === "RecordPattern" &&
805
+ (this.isSimpleBindingPattern(arg) ||
806
+ patternHasOptionalField(arg, payloadFields))
807
+ ) {
808
+ if (!patternHasOptionalField(arg, payloadFields)) {
809
+ const fields = this.collectRecordDestructuring(arg);
810
+ if (fields.length) {
811
+ const parameter = `({ value: { ${fields.join(", ")} } })`;
812
+ return body.kind === "BlockStatement"
813
+ ? `${parameter} => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`
814
+ : `${parameter} => ${this.context.emitArrowExpression(body)}`;
815
+ }
816
+ }
817
+ const unpack = this.emitSomeRecordUnpack(
818
+ arg,
819
+ payloadFields,
820
+ isOptional,
821
+ );
822
+ if (unpack) {
823
+ if (body.kind === "BlockStatement")
824
+ return `($matched) => {\n ${unpack}\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
825
+ return `($matched) => {\n ${unpack}\n return ${indentContinuation(this.context.emitExpression(body), 4)};\n }`;
826
+ }
827
+ if (body.kind === "BlockStatement")
828
+ return `() => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
829
+ return `() => ${this.context.emitArrowExpression(body)}`;
830
+ }
831
+ if (arg.kind === "LiteralPattern") {
832
+ if (body.kind === "BlockStatement")
833
+ return `() => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
834
+ return `() => ${this.context.emitArrowExpression(body)}`;
835
+ }
836
+ if (arg.kind === "ArrayPattern" && this.isSimpleBindingPattern(arg)) {
837
+ const bindingTarget = this.context.emitBindingTarget(arg);
838
+ if (bindingTarget && bindingTarget !== "[]" && bindingTarget !== "{}") {
839
+ const parameter = `({ value: ${bindingTarget} })`;
840
+ if (body.kind === "BlockStatement")
841
+ return `${parameter} => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
842
+ return `${parameter} => ${this.context.emitArrowExpression(body)}`;
843
+ }
844
+ } else if (vars.length > 0) {
845
+ const unpack = this.emitPatternUnpackLines(pat, "$matched", {
846
+ isOptionalScrutinee: isOptional,
847
+ payloadFields,
848
+ }).join("\n ");
849
+ if (body.kind === "BlockStatement")
850
+ return `($matched) => {\n ${unpack}\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
851
+ return `($matched) => {\n ${unpack}\n return ${indentContinuation(this.context.emitExpression(body), 4)};\n }`;
852
+ }
853
+ if (body.kind === "BlockStatement")
854
+ return `() => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
855
+ return `() => ${this.context.emitArrowExpression(body)}`;
856
+ }
857
+ if (vars.length > 0 && pat) {
858
+ const unpack =
859
+ pat.kind === "VariablePattern"
860
+ ? `const { ${vars[0]} } = $matched;`
861
+ : this.emitPatternUnpackLines(pat, "$matched", {
862
+ isOptionalScrutinee: isOptional,
863
+ payloadFields,
864
+ }).join("\n ");
865
+ if (body.kind === "BlockStatement") {
866
+ return `($matched) => {\n ${unpack}\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
867
+ }
868
+ return `($matched) => {\n ${unpack}\n return ${indentContinuation(this.context.emitExpression(body), 4)};\n }`;
869
+ }
870
+
871
+ if (body.kind === "BlockStatement") {
872
+ return `() => {\n ${indentContinuation(this.context.emitFunctionBody(body), 2)}\n }`;
873
+ }
874
+ return `() => ${this.context.emitArrowExpression(body)}`;
875
+ }
876
+
877
+ private collectPatternVariables(pat: Pattern): string[] {
878
+ if (pat.kind === "VariablePattern") return [pat.name.name];
879
+ if (pat.kind === "ConstructorPattern") {
880
+ const vars: string[] = [];
881
+ for (const a of pat.args) {
882
+ vars.push(...this.collectPatternVariables(a));
883
+ }
884
+ return vars;
885
+ }
886
+ if (pat.kind === "OrPattern") {
887
+ return pat.patterns.length > 0
888
+ ? this.collectPatternVariables(pat.patterns[0])
889
+ : [];
890
+ }
891
+ if (pat.kind === "RecordPattern") {
892
+ const vars: string[] = [];
893
+ for (const f of pat.fields) {
894
+ if (!f.pattern) {
895
+ vars.push(f.key.name);
896
+ } else {
897
+ vars.push(...this.collectPatternVariables(f.pattern));
898
+ }
899
+ }
900
+ return vars;
901
+ }
902
+ if (pat.kind === "ArrayPattern") {
903
+ const vars: string[] = [];
904
+ for (const el of pat.elements) {
905
+ vars.push(...this.collectPatternVariables(el));
906
+ }
907
+ return vars;
908
+ }
909
+ if (pat.kind === "RestPattern") {
910
+ return this.collectPatternVariables(pat.argument);
911
+ }
912
+ return [];
913
+ }
914
+
915
+ /** Returns true when a pattern can be unpacked with plain JS destructuring. */
916
+ private isSimpleBindingPattern(pat: Pattern): boolean {
917
+ if (
918
+ pat.kind === "WildcardPattern" ||
919
+ pat.kind === "LiteralPattern" ||
920
+ pat.kind === "VariablePattern"
921
+ ) {
922
+ return true;
923
+ }
924
+ if (pat.kind === "RestPattern") {
925
+ return this.isSimpleBindingPattern(pat.argument);
926
+ }
927
+ if (pat.kind === "ArrayPattern") {
928
+ return pat.elements.every((el) => this.isSimpleBindingPattern(el));
929
+ }
930
+ if (pat.kind === "RecordPattern") {
931
+ return pat.fields.every(
932
+ (f) => f.isRest || !f.pattern || this.isSimpleBindingPattern(f.pattern),
933
+ );
934
+ }
935
+ return false;
936
+ }
937
+
938
+ /** Produces a structural signature of where variables are bound in a pattern. */
939
+ private patternBindingSignature(pat: Pattern): string {
940
+ if (pat.kind === "VariablePattern") return `VAR:${pat.name.name}`;
941
+ if (pat.kind === "WildcardPattern" || pat.kind === "LiteralPattern") {
942
+ return "_";
943
+ }
944
+ if (pat.kind === "RestPattern") {
945
+ return `...${this.patternBindingSignature(pat.argument)}`;
946
+ }
947
+ if (pat.kind === "ArrayPattern") {
948
+ return `[${pat.elements
949
+ .map((el, i) =>
950
+ this.collectPatternVariables(el).length > 0
951
+ ? `${i}:${this.patternBindingSignature(el)}`
952
+ : "_",
953
+ )
954
+ .join(",")}]`;
955
+ }
956
+ if (pat.kind === "RecordPattern") {
957
+ const entries = pat.fields
958
+ .filter(
959
+ (f) =>
960
+ f.isRest ||
961
+ !f.pattern ||
962
+ this.collectPatternVariables(f.pattern).length > 0,
963
+ )
964
+ .map((f) =>
965
+ f.isRest
966
+ ? `...${f.key.name}`
967
+ : `${f.key.name}:${f.pattern ? this.patternBindingSignature(f.pattern) : `VAR:${f.key.name}`}`,
968
+ )
969
+ .sort();
970
+ return `{${entries.join(",")}}`;
971
+ }
972
+ if (pat.kind === "ConstructorPattern") {
973
+ return `${pat.constructorName.name}(${pat.args.map((a) => this.patternBindingSignature(a)).join(",")})`;
974
+ }
975
+ if (pat.kind === "OrPattern") {
976
+ return `OR(${pat.patterns.map((p) => this.patternBindingSignature(p)).join("|")})`;
977
+ }
978
+ return "_";
979
+ }
980
+
981
+ /** Emits destructuring and nested unpack lines for a record pattern. */
982
+ private emitRecordPatternUnpack(
983
+ pat: RecordPattern,
984
+ targetExpr: string,
985
+ nextTemp: () => string = (() => {
986
+ let idx = 0;
987
+ return () => `__match${idx++}`;
988
+ })(),
989
+ ): string[] {
990
+ if (this.isSimpleBindingPattern(pat)) {
991
+ const destructParts = this.collectRecordDestructuring(pat);
992
+ return destructParts.length > 0
993
+ ? [`const { ${destructParts.join(", ")} } = ${targetExpr};`]
994
+ : [];
995
+ }
996
+
997
+ const parts: string[] = [];
998
+ const nestedLines: string[] = [];
999
+ const hasRest = pat.fields.some((f) => f.isRest);
1000
+
1001
+ for (const f of pat.fields) {
1002
+ if (f.isRest) {
1003
+ parts.push(`...${f.key.name}`);
1004
+ } else if (!f.pattern) {
1005
+ parts.push(f.key.name);
1006
+ } else if (f.pattern.kind === "VariablePattern") {
1007
+ parts.push(`${f.key.name}: ${f.pattern.name.name}`);
1008
+ } else if (this.isSimpleBindingPattern(f.pattern)) {
1009
+ if (f.pattern.kind === "RecordPattern") {
1010
+ const sub = this.collectRecordDestructuring(f.pattern);
1011
+ if (sub.length > 0) {
1012
+ parts.push(`${f.key.name}: { ${sub.join(", ")} }`);
1013
+ } else if (hasRest) {
1014
+ parts.push(`${f.key.name}: _${f.key.name}`);
1015
+ }
1016
+ } else if (f.pattern.kind === "ArrayPattern") {
1017
+ const target = this.context.emitBindingTarget(f.pattern);
1018
+ if (target && target !== "[]") {
1019
+ parts.push(`${f.key.name}: ${target}`);
1020
+ } else if (hasRest) {
1021
+ parts.push(`${f.key.name}: _${f.key.name}`);
1022
+ }
1023
+ } else if (hasRest) {
1024
+ parts.push(`${f.key.name}: _${f.key.name}`);
1025
+ }
1026
+ } else if (this.collectPatternVariables(f.pattern).length > 0) {
1027
+ const tmp = nextTemp();
1028
+ parts.push(`${f.key.name}: ${tmp}`);
1029
+ nestedLines.push(
1030
+ ...this.emitPatternUnpackLines(f.pattern, tmp, { nextTemp }),
1031
+ );
1032
+ } else if (hasRest) {
1033
+ parts.push(`${f.key.name}: _${f.key.name}`);
1034
+ }
1035
+ }
1036
+
1037
+ if (parts.length > 0) {
1038
+ return [`const { ${parts.join(", ")} } = ${targetExpr};`, ...nestedLines];
1039
+ }
1040
+ return nestedLines;
1041
+ }
1042
+
1043
+ /** Recursively unpacks bindings from any match pattern against `targetExpr`. */
1044
+ private emitPatternUnpackLines(
1045
+ pat: Pattern,
1046
+ targetExpr: string,
1047
+ options?: {
1048
+ isOptionalScrutinee?: boolean;
1049
+ payloadFields?: Map<string, RecordFieldInfo>;
1050
+ nextTemp?: () => string;
1051
+ },
1052
+ ): string[] {
1053
+ let tempCounter = 0;
1054
+ const nextTemp = options?.nextTemp ?? (() => `__match${tempCounter++}`);
1055
+ const vars = this.collectPatternVariables(pat);
1056
+ if (vars.length === 0) {
1057
+ return [];
1058
+ }
1059
+
1060
+ if (pat.kind === "VariablePattern") {
1061
+ return [`const ${pat.name.name} = ${targetExpr};`];
1062
+ }
1063
+
1064
+ if (pat.kind === "RestPattern") {
1065
+ return this.emitPatternUnpackLines(pat.argument, targetExpr, {
1066
+ nextTemp,
1067
+ });
1068
+ }
1069
+
1070
+ if (pat.kind === "RecordPattern") {
1071
+ return this.emitRecordPatternUnpack(pat, targetExpr, nextTemp);
1072
+ }
1073
+
1074
+ if (pat.kind === "ArrayPattern") {
1075
+ const lines: string[] = [];
1076
+ for (let i = 0; i < pat.elements.length; i++) {
1077
+ const el = pat.elements[i];
1078
+ const elemExpr = `${targetExpr}[${i}]`;
1079
+ if (el.kind === "RestPattern") {
1080
+ if (el.argument.kind === "VariablePattern") {
1081
+ lines.push(
1082
+ `const ${el.argument.name.name} = ${targetExpr}.slice(${i});`,
1083
+ );
1084
+ } else if (this.collectPatternVariables(el.argument).length > 0) {
1085
+ const tmp = nextTemp();
1086
+ lines.push(`const ${tmp} = ${targetExpr}.slice(${i});`);
1087
+ lines.push(
1088
+ ...this.emitPatternUnpackLines(el.argument, tmp, { nextTemp }),
1089
+ );
1090
+ }
1091
+ } else if (this.collectPatternVariables(el).length > 0) {
1092
+ lines.push(
1093
+ ...this.emitPatternUnpackLines(el, elemExpr, { nextTemp }),
1094
+ );
1095
+ }
1096
+ }
1097
+ return lines;
1098
+ }
1099
+
1100
+ if (pat.kind === "OrPattern") {
1101
+ const first = pat.patterns[0];
1102
+ if (!first) return [];
1103
+ const firstSig = this.patternBindingSignature(first);
1104
+ const allSameShape = pat.patterns.every(
1105
+ (p) => this.patternBindingSignature(p) === firstSig,
1106
+ );
1107
+ if (allSameShape) {
1108
+ return this.emitPatternUnpackLines(first, targetExpr, {
1109
+ ...options,
1110
+ nextTemp,
1111
+ });
1112
+ }
1113
+ const uniqueVars = Array.from(new Set(vars));
1114
+ const branches = pat.patterns
1115
+ .map((alt) => {
1116
+ const orVar = nextTemp();
1117
+ const altLines = this.emitPatternUnpackLines(alt, orVar, {
1118
+ nextTemp,
1119
+ });
1120
+ const bodyLines = [
1121
+ ...altLines,
1122
+ `return { ${uniqueVars.join(", ")} };`,
1123
+ ];
1124
+ return `.with(${this.emitPattern(alt)}, (${orVar}) => {\n ${bodyLines.join("\n ")}\n })`;
1125
+ })
1126
+ .join("\n ");
1127
+ return [
1128
+ `const { ${uniqueVars.join(", ")} } = match(${targetExpr})\n ${branches}\n .otherwise(() => ({}));`,
1129
+ ];
1130
+ }
1131
+
1132
+ if (pat.kind === "ConstructorPattern") {
1133
+ if (JS_ERROR_NAMES.has(pat.constructorName.name)) {
1134
+ return [`const { ${vars.join(", ")} } = ${targetExpr};`];
1135
+ }
1136
+
1137
+ if (pat.constructorName.name === "Some" && pat.args.length === 1) {
1138
+ const arg = pat.args[0];
1139
+ const cast = "";
1140
+ if (
1141
+ arg.kind === "RecordPattern" &&
1142
+ targetExpr === "$matched" &&
1143
+ patternHasOptionalField(arg, options?.payloadFields)
1144
+ ) {
1145
+ return [
1146
+ this.emitSomeRecordUnpack(
1147
+ arg,
1148
+ options?.payloadFields,
1149
+ options?.isOptionalScrutinee,
1150
+ ),
1151
+ ].filter(Boolean);
1152
+ }
1153
+ if (arg.kind === "VariablePattern") {
1154
+ return [`const { value: ${arg.name.name} } = ${targetExpr}${cast};`];
1155
+ }
1156
+ if (
1157
+ (arg.kind === "RecordPattern" || arg.kind === "ArrayPattern") &&
1158
+ this.isSimpleBindingPattern(arg)
1159
+ ) {
1160
+ const bindingTarget = this.context.emitBindingTarget(arg);
1161
+ if (
1162
+ bindingTarget &&
1163
+ bindingTarget !== "[]" &&
1164
+ bindingTarget !== "{}" &&
1165
+ bindingTarget !== "_"
1166
+ ) {
1167
+ return [
1168
+ `const { value: ${bindingTarget} } = ${targetExpr}${cast};`,
1169
+ ];
1170
+ }
1171
+ }
1172
+ const tmp = nextTemp();
1173
+ return [
1174
+ `const { value: ${tmp} } = ${targetExpr}${cast};`,
1175
+ ...this.emitPatternUnpackLines(arg, tmp, { nextTemp }),
1176
+ ];
1177
+ }
1178
+
1179
+ const fieldNames = this.context.getVariantFields?.(
1180
+ pat.constructorName.name,
1181
+ );
1182
+ if (fieldNames && fieldNames.length === pat.args.length) {
1183
+ const parts: string[] = [];
1184
+ const nestedLines: string[] = [];
1185
+ for (let i = 0; i < fieldNames.length; i++) {
1186
+ const arg = pat.args[i];
1187
+ if (this.collectPatternVariables(arg).length === 0) continue;
1188
+ if (arg.kind === "VariablePattern") {
1189
+ parts.push(`${fieldNames[i]}: ${arg.name.name}`);
1190
+ } else if (
1191
+ arg.kind === "RecordPattern" &&
1192
+ this.isSimpleBindingPattern(arg)
1193
+ ) {
1194
+ const sub = this.collectRecordDestructuring(arg);
1195
+ if (sub.length > 0) {
1196
+ parts.push(`${fieldNames[i]}: { ${sub.join(", ")} }`);
1197
+ }
1198
+ } else if (
1199
+ arg.kind === "ArrayPattern" &&
1200
+ this.isSimpleBindingPattern(arg)
1201
+ ) {
1202
+ const target = this.context.emitBindingTarget(arg);
1203
+ if (target && target !== "[]") {
1204
+ parts.push(`${fieldNames[i]}: ${target}`);
1205
+ }
1206
+ } else {
1207
+ const tmp = nextTemp();
1208
+ parts.push(`${fieldNames[i]}: ${tmp}`);
1209
+ nestedLines.push(
1210
+ ...this.emitPatternUnpackLines(arg, tmp, { nextTemp }),
1211
+ );
1212
+ }
1213
+ }
1214
+ if (parts.length > 0) {
1215
+ return [
1216
+ `const { ${parts.join(", ")} } = ${targetExpr};`,
1217
+ ...nestedLines,
1218
+ ];
1219
+ }
1220
+ return nestedLines;
1221
+ }
1222
+
1223
+ const fieldsVar = nextTemp();
1224
+ const argTargets: string[] = [];
1225
+ const nestedLines: string[] = [];
1226
+ for (const arg of pat.args) {
1227
+ if (this.collectPatternVariables(arg).length === 0) {
1228
+ argTargets.push("");
1229
+ } else if (arg.kind === "VariablePattern") {
1230
+ argTargets.push(arg.name.name);
1231
+ } else {
1232
+ const tmp = nextTemp();
1233
+ argTargets.push(tmp);
1234
+ nestedLines.push(
1235
+ ...this.emitPatternUnpackLines(arg, tmp, { nextTemp }),
1236
+ );
1237
+ }
1238
+ }
1239
+ return [
1240
+ `const { _tag: _, ...${fieldsVar} } = ${targetExpr};`,
1241
+ `const [${argTargets.join(", ")}] = Object.values(${fieldsVar});`,
1242
+ ...nestedLines,
1243
+ ];
1244
+ }
1245
+
1246
+ return [];
1247
+ }
1248
+
1249
+ private emitIfElseMatch(
1250
+ arms: MatchArm[],
1251
+ getCondition: (arm: MatchArm) => string,
1252
+ ): string {
1253
+ const hasBlockArm = arms.some((a) => a.body.kind === "BlockStatement");
1254
+ if (!hasBlockArm) {
1255
+ let code = "";
1256
+ for (let i = 0; i < arms.length; i++) {
1257
+ const arm = arms[i];
1258
+ const isDefault =
1259
+ (arm.pattern.kind === "WildcardPattern" ||
1260
+ arm.pattern.kind === "VariablePattern") &&
1261
+ !arm.guard;
1262
+ const body = this.context.emitExpression(arm.body as Expression);
1263
+ if (isDefault) {
1264
+ code += body;
1265
+ break;
1266
+ }
1267
+ if (i === arms.length - 1) {
1268
+ code += `${getCondition(arm)} ? ${body} : (() => { throw new Error("Non-exhaustive match"); })()`;
1269
+ break;
1270
+ }
1271
+ code += `${getCondition(arm)} ? ${body} : `;
1272
+ }
1273
+ return `(${code})`;
1274
+ }
1275
+
1276
+ const branches: string[] = [];
1277
+ let hasDefault = false;
1278
+ for (let i = 0; i < arms.length; i++) {
1279
+ const arm = arms[i];
1280
+ const isDefault =
1281
+ (arm.pattern.kind === "WildcardPattern" ||
1282
+ arm.pattern.kind === "VariablePattern") &&
1283
+ !arm.guard;
1284
+ const inner =
1285
+ arm.body.kind === "BlockStatement"
1286
+ ? this.context.emitFunctionBody(arm.body)
1287
+ : ` return ${this.context.emitExpression(arm.body)};`;
1288
+ if (i === 0) {
1289
+ if (isDefault) {
1290
+ hasDefault = true;
1291
+ branches.push(inner);
1292
+ break;
1293
+ }
1294
+ branches.push(`if (${getCondition(arm)}) {\n${inner}\n}`);
1295
+ } else if (isDefault) {
1296
+ hasDefault = true;
1297
+ branches.push(`else {\n${inner}\n}`);
1298
+ break;
1299
+ } else {
1300
+ branches.push(`else if (${getCondition(arm)}) {\n${inner}\n}`);
1301
+ }
1302
+ }
1303
+ if (!hasDefault) {
1304
+ branches.push(`else {\n throw new Error("Non-exhaustive match");\n}`);
1305
+ }
1306
+ return `(() => {\n ${branches.join(" ")}\n})()`;
1307
+ }
1308
+
1309
+ private emitCatchExpression(expr: MatchExpression): string {
1310
+ this.context.addEffectImport?.("Effect");
1311
+ const collectCases = (pattern: Pattern, body: string): string[] => {
1312
+ if (pattern.kind === "OrPattern") {
1313
+ return pattern.patterns.flatMap((part) => collectCases(part, body));
1314
+ }
1315
+ if (pattern.kind !== "ConstructorPattern") {
1316
+ throw new Error("Invalid catch arm");
1317
+ }
1318
+ const arg = pattern.args[0];
1319
+ const binding = arg?.kind === "VariablePattern" ? arg.name.name : "";
1320
+ return [
1321
+ `${JSON.stringify(pattern.constructorName.name)}: (${binding}) => {\n${body}\n}`,
1322
+ ];
1323
+ };
1324
+ const cases = expr.arms.flatMap((arm) =>
1325
+ collectCases(arm.pattern, this.context.emitFunctionBody(arm.body)),
1326
+ );
1327
+ const handlers = `{\n${cases.join(",\n")}\n}`;
1328
+ if (expr.isPipeline || !expr.scrutinee) {
1329
+ return `(__catchInput) => Effect.catchTags(__catchInput, ${handlers})`;
1330
+ }
1331
+ return `Effect.catchTags(${this.context.emitExpression(expr.scrutinee)}, ${handlers})`;
1332
+ }
1333
+
1334
+ private emitJSNullishMatch(
1335
+ scrutinee: Expression | undefined,
1336
+ arms: MatchArm[],
1337
+ ): string {
1338
+ if (!arms.length)
1339
+ throw new FunScriptError(
1340
+ "JSNullish match requires at least one arm",
1341
+ scrutinee?.span ?? {
1342
+ start: { line: 1, column: 1, offset: 0 },
1343
+ end: { line: 1, column: 1, offset: 0 },
1344
+ },
1345
+ );
1346
+ // Always capture once: a property getter or foreign expression may be effectful.
1347
+ const value = "$jsNullish";
1348
+ const preamble = scrutinee
1349
+ ? `const ${value} = ${this.context.emitExpression(scrutinee)};`
1350
+ : "";
1351
+ const branches: string[] = [];
1352
+ let coversSuccess = false;
1353
+ let coversNull = false;
1354
+ let coversUndefined = false;
1355
+ let coversAll = false;
1356
+ let terminated = false;
1357
+
1358
+ for (const arm of arms) {
1359
+ const pat = arm.pattern;
1360
+ let condition: string;
1361
+ let binding: string | undefined;
1362
+ let caseKind: "success" | "null" | "undefined" | "failure" | "all";
1363
+ if (pat.kind === "WildcardPattern" || pat.kind === "VariablePattern") {
1364
+ condition = "true";
1365
+ caseKind = "all";
1366
+ if (pat.kind === "VariablePattern") binding = pat.name.name;
1367
+ } else if (
1368
+ pat.kind === "ConstructorPattern" &&
1369
+ pat.constructorName.name === "Success"
1370
+ ) {
1371
+ const arg = pat.args[0];
1372
+ if (
1373
+ pat.args.length !== 1 ||
1374
+ (arg.kind !== "VariablePattern" && arg.kind !== "WildcardPattern")
1375
+ ) {
1376
+ throw new FunScriptError(
1377
+ "JSNullish Success expects one variable or '_' pattern",
1378
+ pat.span,
1379
+ );
1380
+ }
1381
+ condition = `(${value} !== null && ${value} !== undefined)`;
1382
+ caseKind = "success";
1383
+ if (arg.kind === "VariablePattern") binding = arg.name.name;
1384
+ } else if (
1385
+ pat.kind === "ConstructorPattern" &&
1386
+ pat.constructorName.name === "Failure"
1387
+ ) {
1388
+ const arg = pat.args[0];
1389
+ if (pat.args.length !== 1) {
1390
+ throw new FunScriptError(
1391
+ "JSNullish Failure expects Null, Undefined, a variable, or '_'",
1392
+ pat.span,
1393
+ );
1394
+ }
1395
+ if (
1396
+ arg.kind === "ConstructorPattern" &&
1397
+ arg.args.length === 0 &&
1398
+ arg.constructorName.name === "Null"
1399
+ ) {
1400
+ condition = `(${value} === null)`;
1401
+ caseKind = "null";
1402
+ } else if (
1403
+ arg.kind === "ConstructorPattern" &&
1404
+ arg.args.length === 0 &&
1405
+ arg.constructorName.name === "Undefined"
1406
+ ) {
1407
+ condition = `(${value} === undefined)`;
1408
+ caseKind = "undefined";
1409
+ } else if (
1410
+ arg.kind === "VariablePattern" ||
1411
+ arg.kind === "WildcardPattern"
1412
+ ) {
1413
+ condition = `(${value} === null || ${value} === undefined)`;
1414
+ caseKind = "failure";
1415
+ if (arg.kind === "VariablePattern") binding = arg.name.name;
1416
+ } else {
1417
+ throw new FunScriptError(
1418
+ "JSNullish Failure expects Null, Undefined, a variable, or '_'",
1419
+ pat.span,
1420
+ );
1421
+ }
1422
+ } else {
1423
+ throw new FunScriptError(
1424
+ "Match JSNullish using Success(value), Failure(Null), Failure(Undefined), or '_'",
1425
+ pat.span,
1426
+ );
1427
+ }
1428
+
1429
+ if (arm.guard) {
1430
+ const guard = this.context.emitExpression(arm.guard);
1431
+ // Bind the narrowed value inside an IIFE so TypeScript preserves its
1432
+ // narrowed type without triggering TS7006 on an unannotated arrow param.
1433
+ const guardExpr = binding
1434
+ ? `(() => {\n const ${binding} = ${value};\n return (${guard});\n})()`
1435
+ : `(${guard})`;
1436
+ condition =
1437
+ condition === "true" ? guardExpr : `${condition} && ${guardExpr}`;
1438
+ } else {
1439
+ coversSuccess ||= caseKind === "success" || caseKind === "all";
1440
+ coversNull ||=
1441
+ caseKind === "null" || caseKind === "failure" || caseKind === "all";
1442
+ coversUndefined ||=
1443
+ caseKind === "undefined" ||
1444
+ caseKind === "failure" ||
1445
+ caseKind === "all";
1446
+ coversAll ||= caseKind === "all";
1447
+ }
1448
+ const body = this.context.emitFunctionBody(arm.body);
1449
+ const complete =
1450
+ !arm.guard && coversSuccess && coversNull && coversUndefined;
1451
+ const bindingValue =
1452
+ complete && caseKind === "failure"
1453
+ ? `${value} as null | undefined`
1454
+ : value;
1455
+ const bindingLine = binding
1456
+ ? ` const ${binding} = ${bindingValue};\n`
1457
+ : "";
1458
+ if ((caseKind === "all" || complete) && !arm.guard) {
1459
+ branches.push(
1460
+ `${branches.length ? "else " : ""}{\n${bindingLine}${body}\n}`,
1461
+ );
1462
+ terminated = true;
1463
+ break;
1464
+ }
1465
+ branches.push(
1466
+ `${branches.length ? "else " : ""}if (${condition}) {\n${bindingLine}${body}\n}`,
1467
+ );
1468
+ }
1469
+ if (terminated || coversAll) {
1470
+ // A wildcard arm emitted an unconditional final branch.
1471
+ } else if (!(coversSuccess && coversNull && coversUndefined)) {
1472
+ branches.push(
1473
+ `else {\n const __nonExhaustive: never = ${value};\n void __nonExhaustive;\n throw new Error("Non-exhaustive JSNullish match");\n}`,
1474
+ );
1475
+ } else {
1476
+ // Even with all cases covered, retain a final assertion so TypeScript can
1477
+ // infer a non-optional return type for separately tested conditions.
1478
+ branches.push(
1479
+ `else {\n const __exhaustive: never = ${value};\n return __exhaustive;\n}`,
1480
+ );
1481
+ }
1482
+ const bodyLines = preamble
1483
+ ? ` ${preamble}\n ${branches.join(" ")}`
1484
+ : ` ${branches.join(" ")}`;
1485
+ return scrutinee
1486
+ ? `(() => {\n${bodyLines}\n})()`
1487
+ : `(${value}) => {\n${bodyLines}\n}`;
1488
+ }
1489
+
1490
+ private emitJSOptionalMatch(scrutinee: Expression, arms: MatchArm[]): string {
1491
+ const scrutineeId =
1492
+ scrutinee.kind === "Identifier" ? scrutinee.name : "$jsOpt";
1493
+ const preamble =
1494
+ scrutinee.kind === "Identifier"
1495
+ ? ""
1496
+ : `const $jsOpt = ${this.context.emitExpression(scrutinee)};\n `;
1497
+
1498
+ const hasWildcard = arms.some(
1499
+ (a) =>
1500
+ (a.pattern.kind === "WildcardPattern" ||
1501
+ a.pattern.kind === "VariablePattern") &&
1502
+ !a.guard,
1503
+ );
1504
+ const hasSome = arms.some(
1505
+ (a) =>
1506
+ a.pattern.kind === "ConstructorPattern" &&
1507
+ a.pattern.constructorName.name === "Some" &&
1508
+ !a.guard,
1509
+ );
1510
+ const hasFullNone = arms.some(
1511
+ (a) =>
1512
+ a.pattern.kind === "ConstructorPattern" &&
1513
+ a.pattern.constructorName.name === "None" &&
1514
+ !a.guard &&
1515
+ ((a.pattern.args ?? []).length === 0 ||
1516
+ a.pattern.args[0]?.kind === "WildcardPattern"),
1517
+ );
1518
+ const hasNull = arms.some(
1519
+ (a) =>
1520
+ a.pattern.kind === "ConstructorPattern" &&
1521
+ a.pattern.constructorName.name === "None" &&
1522
+ !a.guard &&
1523
+ ((a.pattern.args?.[0]?.kind === "VariablePattern" &&
1524
+ a.pattern.args[0].name.name === "null") ||
1525
+ (a.pattern.args?.[0]?.kind === "ConstructorPattern" &&
1526
+ a.pattern.args[0].constructorName.name === "Null")),
1527
+ );
1528
+ const hasUndefined = arms.some(
1529
+ (a) =>
1530
+ a.pattern.kind === "ConstructorPattern" &&
1531
+ a.pattern.constructorName.name === "None" &&
1532
+ !a.guard &&
1533
+ ((a.pattern.args?.[0]?.kind === "VariablePattern" &&
1534
+ a.pattern.args[0].name.name === "undefined") ||
1535
+ (a.pattern.args?.[0]?.kind === "ConstructorPattern" &&
1536
+ a.pattern.args[0].constructorName.name === "Undefined")),
1537
+ );
1538
+ const isExhaustive =
1539
+ hasWildcard || (hasSome && (hasFullNone || (hasNull && hasUndefined)));
1540
+
1541
+ const branches: string[] = [];
1542
+ for (let i = 0; i < arms.length; i++) {
1543
+ const arm = arms[i];
1544
+ const pat = arm.pattern;
1545
+ const isWildcard =
1546
+ (pat.kind === "WildcardPattern" || pat.kind === "VariablePattern") &&
1547
+ !arm.guard;
1548
+ const bindings: string[] = [];
1549
+ let cond = "true";
1550
+
1551
+ if (pat.kind === "ConstructorPattern") {
1552
+ if (pat.constructorName.name === "Some") {
1553
+ cond = `(${scrutineeId} !== null && ${scrutineeId} !== undefined)`;
1554
+ if (pat.args.length === 1 && pat.args[0].kind === "VariablePattern") {
1555
+ bindings.push(`const ${pat.args[0].name.name} = ${scrutineeId};`);
1556
+ }
1557
+ } else if (pat.constructorName.name === "None") {
1558
+ const arg = pat.args[0];
1559
+ if (
1560
+ (arg?.kind === "VariablePattern" &&
1561
+ arg.name.name === "undefined") ||
1562
+ (arg?.kind === "ConstructorPattern" &&
1563
+ arg.constructorName.name === "Undefined")
1564
+ ) {
1565
+ cond = `(${scrutineeId} === undefined)`;
1566
+ } else if (
1567
+ (arg?.kind === "VariablePattern" && arg.name.name === "null") ||
1568
+ (arg?.kind === "ConstructorPattern" &&
1569
+ arg.constructorName.name === "Null")
1570
+ ) {
1571
+ cond = `(${scrutineeId} === null)`;
1572
+ } else {
1573
+ cond = `(${scrutineeId} === null || ${scrutineeId} === undefined)`;
1574
+ }
1575
+ }
1576
+ } else if (pat.kind === "VariablePattern") {
1577
+ bindings.push(`const ${pat.name.name} = ${scrutineeId};`);
1578
+ }
1579
+
1580
+ if (arm.guard) {
1581
+ const g = this.context.emitExpression(arm.guard);
1582
+ const guard = bindings.length
1583
+ ? `(() => { ${bindings.join(" ")} return (${g}); })()`
1584
+ : `(${g})`;
1585
+ cond = cond === "true" ? guard : `(${cond} && ${guard})`;
1586
+ }
1587
+
1588
+ const bodyCode =
1589
+ arm.body.kind === "BlockStatement"
1590
+ ? this.context.emitFunctionBody(arm.body)
1591
+ : ` return ${this.context.emitExpression(arm.body)};`;
1592
+ const inner =
1593
+ bindings.length > 0
1594
+ ? ` ${bindings.join("\n ")}\n${bodyCode}`
1595
+ : bodyCode;
1596
+
1597
+ const isLast = i === arms.length - 1;
1598
+ if (i === 0) {
1599
+ if (isWildcard) {
1600
+ branches.push(inner);
1601
+ break;
1602
+ }
1603
+ branches.push(`if (${cond}) {\n${inner}\n}`);
1604
+ } else if (
1605
+ isWildcard ||
1606
+ (isLast && !arm.guard && pat.kind !== "ConstructorPattern")
1607
+ ) {
1608
+ branches.push(`else {\n${inner}\n}`);
1609
+ break;
1610
+ } else if (
1611
+ isExhaustive &&
1612
+ isLast &&
1613
+ !arm.guard &&
1614
+ pat.kind === "ConstructorPattern"
1615
+ ) {
1616
+ branches.push(`else {\n${inner}\n}`);
1617
+ break;
1618
+ } else {
1619
+ branches.push(`else if (${cond}) {\n${inner}\n}`);
1620
+ }
1621
+ }
1622
+
1623
+ if (!isExhaustive) {
1624
+ branches.push(
1625
+ `else {\n const __nonExhaustive: never = ${scrutineeId};\n return __nonExhaustive;\n}`,
1626
+ );
1627
+ }
1628
+
1629
+ return `(() => {\n ${preamble}${branches.join(" ")}\n})()`;
1630
+ }
1631
+ }