hinmil 0.0.0-stage → 0.2.0

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 (301) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2306 -2
  3. package/dist/cli.d.ts +15 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +338 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/commentParser.d.ts +384 -0
  8. package/dist/commentParser.d.ts.map +1 -0
  9. package/dist/commentParser.js +2487 -0
  10. package/dist/commentParser.js.map +1 -0
  11. package/dist/config.d.ts +203 -0
  12. package/dist/config.d.ts.map +1 -0
  13. package/dist/config.js +375 -0
  14. package/dist/config.js.map +1 -0
  15. package/dist/debugLog.d.ts +13 -0
  16. package/dist/debugLog.d.ts.map +1 -0
  17. package/dist/debugLog.js +44 -0
  18. package/dist/debugLog.js.map +1 -0
  19. package/dist/estree.d.ts +100 -0
  20. package/dist/estree.d.ts.map +1 -0
  21. package/dist/estree.js +34 -0
  22. package/dist/estree.js.map +1 -0
  23. package/dist/hm/env.d.ts +134 -0
  24. package/dist/hm/env.d.ts.map +1 -0
  25. package/dist/hm/env.js +939 -0
  26. package/dist/hm/env.js.map +1 -0
  27. package/dist/hm/index.d.ts +7 -0
  28. package/dist/hm/index.d.ts.map +1 -0
  29. package/dist/hm/index.js +26 -0
  30. package/dist/hm/index.js.map +1 -0
  31. package/dist/hm/substitution.d.ts +57 -0
  32. package/dist/hm/substitution.d.ts.map +1 -0
  33. package/dist/hm/substitution.js +546 -0
  34. package/dist/hm/substitution.js.map +1 -0
  35. package/dist/hm/typeParser.d.ts +39 -0
  36. package/dist/hm/typeParser.d.ts.map +1 -0
  37. package/dist/hm/typeParser.js +1285 -0
  38. package/dist/hm/typeParser.js.map +1 -0
  39. package/dist/hm/typeUtils.d.ts +248 -0
  40. package/dist/hm/typeUtils.d.ts.map +1 -0
  41. package/dist/hm/typeUtils.js +905 -0
  42. package/dist/hm/typeUtils.js.map +1 -0
  43. package/dist/hm/types.d.ts +738 -0
  44. package/dist/hm/types.d.ts.map +1 -0
  45. package/dist/hm/types.js +1853 -0
  46. package/dist/hm/types.js.map +1 -0
  47. package/dist/hm/unify.d.ts +59 -0
  48. package/dist/hm/unify.d.ts.map +1 -0
  49. package/dist/hm/unify.js +1700 -0
  50. package/dist/hm/unify.js.map +1 -0
  51. package/dist/index.d.ts +20 -0
  52. package/dist/index.d.ts.map +1 -0
  53. package/dist/index.js +196 -0
  54. package/dist/index.js.map +1 -0
  55. package/dist/infer/annotation-rigid.d.ts +76 -0
  56. package/dist/infer/annotation-rigid.d.ts.map +1 -0
  57. package/dist/infer/annotation-rigid.js +542 -0
  58. package/dist/infer/annotation-rigid.js.map +1 -0
  59. package/dist/infer/annotation-validation.d.ts +109 -0
  60. package/dist/infer/annotation-validation.d.ts.map +1 -0
  61. package/dist/infer/annotation-validation.js +1078 -0
  62. package/dist/infer/annotation-validation.js.map +1 -0
  63. package/dist/infer/annotations.d.ts +277 -0
  64. package/dist/infer/annotations.d.ts.map +1 -0
  65. package/dist/infer/annotations.js +1343 -0
  66. package/dist/infer/annotations.js.map +1 -0
  67. package/dist/infer/call-overloads.d.ts +24 -0
  68. package/dist/infer/call-overloads.d.ts.map +1 -0
  69. package/dist/infer/call-overloads.js +900 -0
  70. package/dist/infer/call-overloads.js.map +1 -0
  71. package/dist/infer/call-rows.d.ts +154 -0
  72. package/dist/infer/call-rows.d.ts.map +1 -0
  73. package/dist/infer/call-rows.js +2162 -0
  74. package/dist/infer/call-rows.js.map +1 -0
  75. package/dist/infer/calls.d.ts +20 -0
  76. package/dist/infer/calls.d.ts.map +1 -0
  77. package/dist/infer/calls.js +1468 -0
  78. package/dist/infer/calls.js.map +1 -0
  79. package/dist/infer/constraints.d.ts +99 -0
  80. package/dist/infer/constraints.d.ts.map +1 -0
  81. package/dist/infer/constraints.js +1208 -0
  82. package/dist/infer/constraints.js.map +1 -0
  83. package/dist/infer/expr-assignment.d.ts +20 -0
  84. package/dist/infer/expr-assignment.d.ts.map +1 -0
  85. package/dist/infer/expr-assignment.js +620 -0
  86. package/dist/infer/expr-assignment.js.map +1 -0
  87. package/dist/infer/expr-constraint-lookup.d.ts +44 -0
  88. package/dist/infer/expr-constraint-lookup.d.ts.map +1 -0
  89. package/dist/infer/expr-constraint-lookup.js +207 -0
  90. package/dist/infer/expr-constraint-lookup.js.map +1 -0
  91. package/dist/infer/expr-functions.d.ts +20 -0
  92. package/dist/infer/expr-functions.d.ts.map +1 -0
  93. package/dist/infer/expr-functions.js +1359 -0
  94. package/dist/infer/expr-functions.js.map +1 -0
  95. package/dist/infer/expr-jsx.d.ts +19 -0
  96. package/dist/infer/expr-jsx.d.ts.map +1 -0
  97. package/dist/infer/expr-jsx.js +310 -0
  98. package/dist/infer/expr-jsx.js.map +1 -0
  99. package/dist/infer/expr-member.d.ts +40 -0
  100. package/dist/infer/expr-member.d.ts.map +1 -0
  101. package/dist/infer/expr-member.js +1154 -0
  102. package/dist/infer/expr-member.js.map +1 -0
  103. package/dist/infer/expr-prototype.d.ts +11 -0
  104. package/dist/infer/expr-prototype.d.ts.map +1 -0
  105. package/dist/infer/expr-prototype.js +202 -0
  106. package/dist/infer/expr-prototype.js.map +1 -0
  107. package/dist/infer/expressions.d.ts +40 -0
  108. package/dist/infer/expressions.d.ts.map +1 -0
  109. package/dist/infer/expressions.js +1497 -0
  110. package/dist/infer/expressions.js.map +1 -0
  111. package/dist/infer/functionPatterns.d.ts +229 -0
  112. package/dist/infer/functionPatterns.d.ts.map +1 -0
  113. package/dist/infer/functionPatterns.js +1035 -0
  114. package/dist/infer/functionPatterns.js.map +1 -0
  115. package/dist/infer/helpers.d.ts +73 -0
  116. package/dist/infer/helpers.d.ts.map +1 -0
  117. package/dist/infer/helpers.js +187 -0
  118. package/dist/infer/helpers.js.map +1 -0
  119. package/dist/infer/index.d.ts +551 -0
  120. package/dist/infer/index.d.ts.map +1 -0
  121. package/dist/infer/index.js +1127 -0
  122. package/dist/infer/index.js.map +1 -0
  123. package/dist/infer/jsx-dom.d.ts +26 -0
  124. package/dist/infer/jsx-dom.d.ts.map +1 -0
  125. package/dist/infer/jsx-dom.js +303 -0
  126. package/dist/infer/jsx-dom.js.map +1 -0
  127. package/dist/infer/moduleReps.d.ts +7 -0
  128. package/dist/infer/moduleReps.d.ts.map +1 -0
  129. package/dist/infer/moduleReps.js +48 -0
  130. package/dist/infer/moduleReps.js.map +1 -0
  131. package/dist/infer/modules.d.ts +10 -0
  132. package/dist/infer/modules.d.ts.map +1 -0
  133. package/dist/infer/modules.js +775 -0
  134. package/dist/infer/modules.js.map +1 -0
  135. package/dist/infer/narrowing.d.ts +199 -0
  136. package/dist/infer/narrowing.d.ts.map +1 -0
  137. package/dist/infer/narrowing.js +1428 -0
  138. package/dist/infer/narrowing.js.map +1 -0
  139. package/dist/infer/results.d.ts +24 -0
  140. package/dist/infer/results.d.ts.map +1 -0
  141. package/dist/infer/results.js +611 -0
  142. package/dist/infer/results.js.map +1 -0
  143. package/dist/infer/setupPass.d.ts +11 -0
  144. package/dist/infer/setupPass.d.ts.map +1 -0
  145. package/dist/infer/setupPass.js +524 -0
  146. package/dist/infer/setupPass.js.map +1 -0
  147. package/dist/infer/statements.d.ts +26 -0
  148. package/dist/infer/statements.d.ts.map +1 -0
  149. package/dist/infer/statements.js +750 -0
  150. package/dist/infer/statements.js.map +1 -0
  151. package/dist/infer/stmt-bindings.d.ts +22 -0
  152. package/dist/infer/stmt-bindings.d.ts.map +1 -0
  153. package/dist/infer/stmt-bindings.js +1482 -0
  154. package/dist/infer/stmt-bindings.js.map +1 -0
  155. package/dist/infer/stmt-destructure.d.ts +29 -0
  156. package/dist/infer/stmt-destructure.d.ts.map +1 -0
  157. package/dist/infer/stmt-destructure.js +490 -0
  158. package/dist/infer/stmt-destructure.js.map +1 -0
  159. package/dist/infer/types.d.ts +220 -0
  160. package/dist/infer/types.d.ts.map +1 -0
  161. package/dist/infer/types.js +46 -0
  162. package/dist/infer/types.js.map +1 -0
  163. package/dist/infer/unifyDiag.d.ts +46 -0
  164. package/dist/infer/unifyDiag.d.ts.map +1 -0
  165. package/dist/infer/unifyDiag.js +642 -0
  166. package/dist/infer/unifyDiag.js.map +1 -0
  167. package/dist/parsing-babel.d.ts +3 -0
  168. package/dist/parsing-babel.d.ts.map +1 -0
  169. package/dist/parsing-babel.js +353 -0
  170. package/dist/parsing-babel.js.map +1 -0
  171. package/dist/parsing.d.ts +69 -0
  172. package/dist/parsing.d.ts.map +1 -0
  173. package/dist/parsing.js +288 -0
  174. package/dist/parsing.js.map +1 -0
  175. package/dist/registries/constraintRegistry.d.ts +233 -0
  176. package/dist/registries/constraintRegistry.d.ts.map +1 -0
  177. package/dist/registries/constraintRegistry.js +803 -0
  178. package/dist/registries/constraintRegistry.js.map +1 -0
  179. package/dist/registries/dataTypeRegistry.d.ts +63 -0
  180. package/dist/registries/dataTypeRegistry.d.ts.map +1 -0
  181. package/dist/registries/dataTypeRegistry.js +180 -0
  182. package/dist/registries/dataTypeRegistry.js.map +1 -0
  183. package/dist/registries/domGlobals.d.ts +33 -0
  184. package/dist/registries/domGlobals.d.ts.map +1 -0
  185. package/dist/registries/domGlobals.js +309 -0
  186. package/dist/registries/domGlobals.js.map +1 -0
  187. package/dist/registries/methodRegistry.d.ts +277 -0
  188. package/dist/registries/methodRegistry.d.ts.map +1 -0
  189. package/dist/registries/methodRegistry.js +2074 -0
  190. package/dist/registries/methodRegistry.js.map +1 -0
  191. package/dist/registries/session.d.ts +38 -0
  192. package/dist/registries/session.d.ts.map +1 -0
  193. package/dist/registries/session.js +75 -0
  194. package/dist/registries/session.js.map +1 -0
  195. package/dist/server.d.ts +2 -0
  196. package/dist/server.d.ts.map +1 -0
  197. package/dist/server.js +1896 -0
  198. package/dist/server.js.map +1 -0
  199. package/dist/services/codeActions.d.ts +22 -0
  200. package/dist/services/codeActions.d.ts.map +1 -0
  201. package/dist/services/codeActions.js +465 -0
  202. package/dist/services/codeActions.js.map +1 -0
  203. package/dist/services/completion.d.ts +259 -0
  204. package/dist/services/completion.d.ts.map +1 -0
  205. package/dist/services/completion.js +2794 -0
  206. package/dist/services/completion.js.map +1 -0
  207. package/dist/services/definitions.d.ts +37 -0
  208. package/dist/services/definitions.d.ts.map +1 -0
  209. package/dist/services/definitions.js +605 -0
  210. package/dist/services/definitions.js.map +1 -0
  211. package/dist/services/diagnosticCodes.d.ts +70 -0
  212. package/dist/services/diagnosticCodes.d.ts.map +1 -0
  213. package/dist/services/diagnosticCodes.js +239 -0
  214. package/dist/services/diagnosticCodes.js.map +1 -0
  215. package/dist/services/diagnostics.d.ts +86 -0
  216. package/dist/services/diagnostics.d.ts.map +1 -0
  217. package/dist/services/diagnostics.js +665 -0
  218. package/dist/services/diagnostics.js.map +1 -0
  219. package/dist/services/documentCache.d.ts +88 -0
  220. package/dist/services/documentCache.d.ts.map +1 -0
  221. package/dist/services/documentCache.js +108 -0
  222. package/dist/services/documentCache.js.map +1 -0
  223. package/dist/services/documentSymbols.d.ts +20 -0
  224. package/dist/services/documentSymbols.d.ts.map +1 -0
  225. package/dist/services/documentSymbols.js +381 -0
  226. package/dist/services/documentSymbols.js.map +1 -0
  227. package/dist/services/fileSelection.d.ts +24 -0
  228. package/dist/services/fileSelection.d.ts.map +1 -0
  229. package/dist/services/fileSelection.js +154 -0
  230. package/dist/services/fileSelection.js.map +1 -0
  231. package/dist/services/fileSelectionRefresh.d.ts +26 -0
  232. package/dist/services/fileSelectionRefresh.d.ts.map +1 -0
  233. package/dist/services/fileSelectionRefresh.js +77 -0
  234. package/dist/services/fileSelectionRefresh.js.map +1 -0
  235. package/dist/services/files.d.ts +342 -0
  236. package/dist/services/files.d.ts.map +1 -0
  237. package/dist/services/files.js +1712 -0
  238. package/dist/services/files.js.map +1 -0
  239. package/dist/services/fsProbe.d.ts +14 -0
  240. package/dist/services/fsProbe.d.ts.map +1 -0
  241. package/dist/services/fsProbe.js +112 -0
  242. package/dist/services/fsProbe.js.map +1 -0
  243. package/dist/services/globalsLoader.d.ts +20 -0
  244. package/dist/services/globalsLoader.d.ts.map +1 -0
  245. package/dist/services/globalsLoader.js +122 -0
  246. package/dist/services/globalsLoader.js.map +1 -0
  247. package/dist/services/hmFileServices.d.ts +113 -0
  248. package/dist/services/hmFileServices.d.ts.map +1 -0
  249. package/dist/services/hmFileServices.js +686 -0
  250. package/dist/services/hmFileServices.js.map +1 -0
  251. package/dist/services/hover.d.ts +280 -0
  252. package/dist/services/hover.d.ts.map +1 -0
  253. package/dist/services/hover.js +1687 -0
  254. package/dist/services/hover.js.map +1 -0
  255. package/dist/services/importContext.d.ts +396 -0
  256. package/dist/services/importContext.d.ts.map +1 -0
  257. package/dist/services/importContext.js +1999 -0
  258. package/dist/services/importContext.js.map +1 -0
  259. package/dist/services/projectChecker.d.ts +50 -0
  260. package/dist/services/projectChecker.d.ts.map +1 -0
  261. package/dist/services/projectChecker.js +228 -0
  262. package/dist/services/projectChecker.js.map +1 -0
  263. package/dist/services/references.d.ts +41 -0
  264. package/dist/services/references.d.ts.map +1 -0
  265. package/dist/services/references.js +757 -0
  266. package/dist/services/references.js.map +1 -0
  267. package/dist/services/rename.d.ts +22 -0
  268. package/dist/services/rename.d.ts.map +1 -0
  269. package/dist/services/rename.js +101 -0
  270. package/dist/services/rename.js.map +1 -0
  271. package/dist/services/shortCircuit.d.ts +27 -0
  272. package/dist/services/shortCircuit.d.ts.map +1 -0
  273. package/dist/services/shortCircuit.js +28 -0
  274. package/dist/services/shortCircuit.js.map +1 -0
  275. package/dist/services/sidecarPerf.d.ts +19 -0
  276. package/dist/services/sidecarPerf.d.ts.map +1 -0
  277. package/dist/services/sidecarPerf.js +59 -0
  278. package/dist/services/sidecarPerf.js.map +1 -0
  279. package/dist/services/signatureHelp.d.ts +27 -0
  280. package/dist/services/signatureHelp.d.ts.map +1 -0
  281. package/dist/services/signatureHelp.js +984 -0
  282. package/dist/services/signatureHelp.js.map +1 -0
  283. package/dist/walking.d.ts +25 -0
  284. package/dist/walking.d.ts.map +1 -0
  285. package/dist/walking.js +107 -0
  286. package/dist/walking.js.map +1 -0
  287. package/hm-types-builtin/assert.hm +20 -0
  288. package/hm-types-builtin/buffer.hm +8 -0
  289. package/hm-types-builtin/child_process.hm +16 -0
  290. package/hm-types-builtin/crypto.hm +17 -0
  291. package/hm-types-builtin/fs.hm +15 -0
  292. package/hm-types-builtin/http.hm +14 -0
  293. package/hm-types-builtin/os.hm +19 -0
  294. package/hm-types-builtin/path.hm +18 -0
  295. package/hm-types-builtin/react-dom.hm +27 -0
  296. package/hm-types-builtin/react.hm +113 -0
  297. package/hm-types-builtin/url.hm +7 -0
  298. package/hm-types-builtin/zlib.hm +12 -0
  299. package/package.json +53 -4
  300. package/schemas/hinmil.config.schema.json +261 -0
  301. package/schemas/package-hinmil.schema.json +59 -0
@@ -0,0 +1,900 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Overload-trial machinery for call inference — extracted from calls.ts
4
+ //
5
+ // Plain language: an *overloaded* function has several alternative
6
+ // signatures. To type a call, the checker tries each signature in turn
7
+ // against the actual arguments — in pencil (see `speculate` in helpers.ts),
8
+ // so a failed try leaves no trace — and commits to the branch that fits.
9
+ // This file contains that trial-and-selection machinery.
10
+ // ============================================================================
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.tryInferOverloadedCall = tryInferOverloadedCall;
13
+ const types_1 = require("../hm/types");
14
+ const unify_1 = require("../hm/unify");
15
+ const typeUtils_1 = require("../hm/typeUtils");
16
+ const helpers_1 = require("./helpers");
17
+ const call_rows_1 = require("./call-rows");
18
+ const unifyDiag_1 = require("./unifyDiag");
19
+ /**
20
+ * Collect the ids of constraint kind-variables (`$kv:` TCons — e.g. the `f`
21
+ * in `Alt f => f a`) that appear in the resolved types of a call's argument
22
+ * expressions. The argument expressions are inferred inside a snapshot that
23
+ * is immediately rolled back, so this has no lasting effect on the
24
+ * substitution. Used to keep concrete overload branches from silently pinning
25
+ * a constraint variable (see {@link tryInferOverloadedCall}).
26
+ */
27
+ function collectConstraintKvIds(engine, node, env) {
28
+ const ids = new Set();
29
+ (0, helpers_1.speculate)(engine, () => {
30
+ for (const arg of node.arguments) {
31
+ let t;
32
+ try {
33
+ t = engine.subst.apply(engine.inferExpression(arg, env));
34
+ }
35
+ catch {
36
+ continue;
37
+ }
38
+ (0, typeUtils_1.someType)(t, n => {
39
+ if (n.tag === 'TCon') {
40
+ const kv = (0, types_1.parseKvName)(n.name);
41
+ if (kv)
42
+ ids.add(kv.varId);
43
+ }
44
+ return false;
45
+ });
46
+ }
47
+ });
48
+ return ids;
49
+ }
50
+ /**
51
+ * Overload-resolution path for callees whose type resolves to a `Union`
52
+ * of `TFun` branches — the shape produced by repeated `Name :: ...` lines
53
+ * in a `.hm` annotation file.
54
+ *
55
+ * Returns `null` when the callee is NOT an overloaded union (so the regular
56
+ * call-inference code handles it). Otherwise infers the argument
57
+ * expressions, then tries each branch in declaration order:
58
+ *
59
+ * • snapshot the substitution
60
+ * • unify the branch's parameter shape with the actual args
61
+ * • on success: unify the branch's result with the expected result type
62
+ * (if any), record the result, and return
63
+ * • on failure: restore the snapshot and try the next branch
64
+ *
65
+ * If no branch matches, emit a single diagnostic listing every branch's
66
+ * parameter type and return a fresh `TVar`.
67
+ */
68
+ function tryInferOverloadedCall(engine, node, env, calleeType, expectedResultType) {
69
+ const resolved = engine.subst.apply(calleeType);
70
+ if (resolved.tag !== 'TCon' || resolved.name !== types_1.T_UNION)
71
+ return null;
72
+ const branches = resolved.args.filter((b) => b.tag === 'TFun');
73
+ // Need at least 2 callable branches. Non-TFun branches (e.g. a TCon
74
+ // mixed in for property-access purposes) are silently ignored — they
75
+ // simply can't satisfy a call site.
76
+ if (branches.length < 2)
77
+ return null;
78
+ // Skip when ANY argument is a spread — let the regular path handle it.
79
+ if (node.arguments.some((a) => a.type === 'SpreadElement'))
80
+ return null;
81
+ // Expand bare polymorphic type aliases inside the branches before
82
+ // unification. Branches imported from a sidecar (e.g. `Table :: [Selector]
83
+ // -> QueryTag b`) reference aliases by name only — `expandAliases` cannot
84
+ // transform a bare TCon whose args are empty when the alias has free
85
+ // type vars, because it has no scheme-level binders to instantiate
86
+ // against. Since the branches reaching this point are already
87
+ // `instantiate`d (their TVars are fresh), it is safe to instantiate
88
+ // each bare polymorphic alias with its own fresh TVars here.
89
+ const expandBareAliases = (t) => (0, typeUtils_1.mapType)(t, n => {
90
+ if (n.tag !== 'TCon')
91
+ return undefined;
92
+ if (!engine.typeAliases.has(n.name))
93
+ return undefined;
94
+ if (n.args.length !== 0)
95
+ return undefined;
96
+ const vars = engine.typeAliasVars.get(n.name) ?? [];
97
+ if (vars.length === 0)
98
+ return undefined; // handled by ordinary expandAliases
99
+ return engine.maybeExpandAlias(n);
100
+ });
101
+ const expandedBranches = branches.map(b => {
102
+ const eb = expandBareAliases(b);
103
+ return eb.tag === 'TFun' ? eb : b;
104
+ });
105
+ const numArgs = node.arguments.length;
106
+ const calleeStart = node.callee.start;
107
+ // Branch ordering by record discrimination. Ordinary record unification is
108
+ // lenient (it merges differing field names), so the *first* branch whose
109
+ // parameter is any record will swallow a record argument even when a later
110
+ // branch matches it precisely (e.g. `objectOverload :: { nam } -> { nam }`
111
+ // accepting a `Test = { name }` argument meant for the `Test -> Test`
112
+ // branch). To pick the genuinely-matching overload we infer the arguments
113
+ // once (without committing them), score each branch by how precisely its
114
+ // record parameters match, and try branches in best-first order. Scores
115
+ // are zero for every non-record overload, so this is a no-op (original
116
+ // order preserved by the stable sort) for the common Number/String/Array
117
+ // discriminations handled by unification.
118
+ let trialOrder = expandedBranches.map((_, i) => i);
119
+ const plainArgTypes = (0, helpers_1.speculate)(engine, () => {
120
+ engine.suppressPoisonDepth++;
121
+ try {
122
+ return node.arguments.map(a => {
123
+ try {
124
+ return engine.subst.apply(engine.inferExpression(a, env));
125
+ }
126
+ catch {
127
+ return null;
128
+ }
129
+ });
130
+ }
131
+ finally {
132
+ engine.suppressPoisonDepth--;
133
+ }
134
+ }) ?? node.arguments.map(() => null);
135
+ {
136
+ const scoreBranch = (branch) => {
137
+ const params = branch.param.tag === 'TCon' && branch.param.name === types_1.T_TUPLE
138
+ ? branch.param.args
139
+ : [branch.param];
140
+ let score = 0;
141
+ for (let k = 0; k < numArgs; k++) {
142
+ const at = plainArgTypes[k];
143
+ const pt = params[k];
144
+ if (!at || !pt)
145
+ continue;
146
+ const verdict = (0, typeUtils_1.discriminateRecordArg)(engine.subst.apply(at), engine.subst.apply(pt));
147
+ if (verdict === 'exact')
148
+ score += 2;
149
+ else if (verdict === 'reject')
150
+ score -= 3;
151
+ }
152
+ return score;
153
+ };
154
+ const scores = expandedBranches.map(scoreBranch);
155
+ // Only reorder when there is an actual record-discrimination signal;
156
+ // otherwise leave the original order completely untouched.
157
+ if (scores.some(s => s !== 0)) {
158
+ trialOrder = trialOrder
159
+ .slice()
160
+ .sort((a, b) => scores[b] - scores[a] || a - b);
161
+ }
162
+ }
163
+ const isFnLiteralArg = (k) => {
164
+ const t = node.arguments[k].type;
165
+ return t === 'ArrowFunctionExpression' || t === 'FunctionExpression';
166
+ };
167
+ // Per-trial capture of the applied expected type for each function-literal
168
+ // argument, populated by `attemptBranch` just before it returns (while the
169
+ // branch's unifications are still live). Used by the ambiguous curried-union
170
+ // path below to link a provided callback's parameter nodes to the surviving
171
+ // tails' element variable, so hover resolves them once a later curried
172
+ // application pins the element type.
173
+ let trialArgExpected = [];
174
+ // Attempt to apply a single branch to the provided args: push the branch's
175
+ // expected param shapes down into the argument expressions, unify, and
176
+ // return the (possibly still-curried) remainder type on success — or `null`
177
+ // when the branch cannot accept this many args. Mutates `engine.subst`;
178
+ // callers snapshot/restore around it. Throws on a genuine unification
179
+ // failure (treated as "branch rejected" by the caller).
180
+ // Direction (as for an ordinary call, see `argumentOutsideParameter`): the
181
+ // symmetric unifier lets a plain `String` fit a literal union and a union
182
+ // argument fit as soon as one member does. A branch whose parameter the
183
+ // argument does not fit in that direction does not match.
184
+ // `unionArgRejected`: a branch fell out because a UNION argument did not fit
185
+ // in that direction — only then is distributing the union worth a try.
186
+ let unionArgRejected = false;
187
+ const argOutsideBranch = (argType, paramType) => {
188
+ if (paramType === undefined || (0, unifyDiag_1.argumentOutsideParameter)(engine, argType, paramType) === null)
189
+ return false;
190
+ const a = engine.subst.apply(argType);
191
+ if (a.tag === 'TCon' && a.name === types_1.T_UNION)
192
+ unionArgRejected = true;
193
+ return true;
194
+ };
195
+ const attemptBranch = (branch, fixedArgTypes) => {
196
+ // Single array-literal argument vs a fixed-arity positional parameter
197
+ // (`[k1,]`, `[k1, k2]`, … — encoded as a SpreadArray TCon): reject the
198
+ // branch when the literal's length cannot satisfy the parameter's arity.
199
+ // Without this guard a length mismatch is only caught later as a spurious
200
+ // arity diagnostic on whichever branch happens to be committed. The guard
201
+ // lets a single-argument overload set be discriminated by the literal's
202
+ // length alone — e.g. `lensPath(["a", "b"])` selects the `[k1, k2] -> …`
203
+ // branch over the `[k1,]` / `[k1, k2, k3]` branches.
204
+ if (numArgs === 1 && branch.param.tag === 'TCon' && branch.param.name === types_1.T_SPREAD_ARRAY) {
205
+ const argNode = node.arguments[0];
206
+ if (argNode.type === 'ArrayExpression' && Array.isArray(argNode.elements)) {
207
+ const litLen = argNode.elements.length;
208
+ const spreadIdx = branch.param.args.findIndex(a => (0, types_1.isSpread)(a));
209
+ if (spreadIdx < 0) {
210
+ // Fixed positional: literal length must match exactly.
211
+ if (litLen !== branch.param.args.length)
212
+ return null;
213
+ }
214
+ else {
215
+ // With a rest element: literal must supply at least the fixed slots.
216
+ const minRequired = branch.param.args.length - 1;
217
+ if (litLen < minRequired)
218
+ return null;
219
+ }
220
+ }
221
+ }
222
+ const branchExpected = [];
223
+ // Zero-arg call: `f ()` in JS always INVOKES — it is never a partial
224
+ // application. Without this, every branch trivially "accepts" zero
225
+ // provided args, and the ambiguous-curried-union path below returns the
226
+ // whole overload union as the call's result (an FP library's `RTask.ask ()`
227
+ // against `() -> RTask r e r | (r -> a) -> RTask r e a` leaked the
228
+ // union into the surrounding `forkWith` argument slot). Mirror the
229
+ // regular call path's semantics: a nullary branch (`Void`/`Undefined`
230
+ // param) matches outright; any other branch gets implicit `undefined`
231
+ // for every declared parameter and is rejected when that fails.
232
+ if (numArgs === 0) {
233
+ let cur = engine.subst.apply(branch);
234
+ if (cur.tag !== 'TFun')
235
+ return null;
236
+ const p = engine.subst.apply(cur.param);
237
+ if (p.tag === 'TCon' && (p.name === 'Void' || p.name === 'Undefined')) {
238
+ cur = engine.subst.apply(cur.result);
239
+ }
240
+ else {
241
+ let walk = cur;
242
+ while (walk.tag === 'TFun') {
243
+ const params = walk.param.tag === 'TCon' && walk.param.name === types_1.T_TUPLE
244
+ ? walk.param.args
245
+ : [walk.param];
246
+ for (const prm of params) {
247
+ engine.subst.mergeFrom((0, unify_1.unify)(engine.subst.apply(prm), types_1.tUndefined));
248
+ }
249
+ walk = engine.subst.apply(walk.result);
250
+ }
251
+ cur = walk;
252
+ }
253
+ if (expectedResultType) {
254
+ engine.subst.mergeFrom((0, unify_1.unify)(engine.subst.apply(cur), engine.subst.apply(expectedResultType)));
255
+ }
256
+ return engine.subst.apply(cur);
257
+ }
258
+ if (branch.param.tag === 'TCon' && branch.param.name === types_1.T_TUPLE) {
259
+ for (let k = 0; k < numArgs; k++)
260
+ branchExpected.push(branch.param.args[k]);
261
+ }
262
+ else {
263
+ let walk = branch;
264
+ for (let k = 0; k < numArgs; k++) {
265
+ if (walk.tag === 'TFun') {
266
+ branchExpected.push(walk.param);
267
+ walk = walk.result;
268
+ }
269
+ else
270
+ branchExpected.push(undefined);
271
+ }
272
+ }
273
+ const argTypes = [];
274
+ // Pin the branch-result's free vars during argument inference (see
275
+ // `pinnedElementVarIds`): array-literal elements matched against an
276
+ // expanded union must keep sharing vars that thread into the result.
277
+ const prevPinned = engine.pinnedElementVarIds;
278
+ {
279
+ const resultVarNames = new Map();
280
+ (0, types_1.collectVarNames)(engine.subst.apply(branch.result), resultVarNames);
281
+ engine.pinnedElementVarIds = new Set(resultVarNames.keys());
282
+ }
283
+ try {
284
+ for (let k = 0; k < numArgs; k++) {
285
+ const exp = branchExpected[k];
286
+ const fixed = fixedArgTypes?.[k];
287
+ const t = fixed
288
+ ? fixed
289
+ : exp
290
+ ? engine.inferExpressionWithExpected(node.arguments[k], env, exp)
291
+ : engine.inferExpression(node.arguments[k], env);
292
+ argTypes.push(t);
293
+ }
294
+ }
295
+ finally {
296
+ engine.pinnedElementVarIds = prevPinned;
297
+ }
298
+ // Multi-arg tuple branch: unify the whole tuple with the branch's param.
299
+ if (branch.param.tag === 'TCon' && branch.param.name === types_1.T_TUPLE) {
300
+ const actualArgShape = numArgs === 1 ? argTypes[0] : (0, types_1.tTuple)(argTypes);
301
+ engine.subst.mergeFrom((0, unify_1.unify)(engine.subst.apply(branch.param), engine.subst.apply(actualArgShape)));
302
+ for (let k = 0; k < numArgs; k++) {
303
+ if (argOutsideBranch(argTypes[k], branch.param.args[k]))
304
+ return null;
305
+ }
306
+ // Reduce record-spread results (`(a, b) -> { ...a, ...b }`, e.g.
307
+ // `Object.assign`) BEFORE comparing with the expected result: an
308
+ // unreduced `Merge` marker only unifies with plain records, so a branch
309
+ // returning `Merge {} {[k]::a} {[k]::a}` was rejected against
310
+ // `{ [k] :: a }`. No node: this is a speculative trial.
311
+ engine.subst.mergeFrom((0, unify_1.unify)((0, call_rows_1.applyMergeReduction)(engine, engine.subst.apply(branch.result)), engine.subst.apply(expectedResultType ?? (0, types_1.tVar)())));
312
+ trialArgExpected = branchExpected.map((exp, k) => exp && isFnLiteralArg(k) ? engine.subst.apply(exp) : undefined);
313
+ return engine.subst.apply(branch.result);
314
+ }
315
+ // Curried / single-arg branch: walk through one application at a time.
316
+ let cur = branch;
317
+ let i = 0;
318
+ while (i < numArgs && cur.tag === 'TFun') {
319
+ engine.subst.mergeFrom((0, unify_1.unify)(engine.subst.apply(cur.param), engine.subst.apply(argTypes[i])));
320
+ if (argOutsideBranch(argTypes[i], cur.param))
321
+ return null;
322
+ cur = engine.subst.apply(cur.result);
323
+ i++;
324
+ }
325
+ if (i !== numArgs)
326
+ return null; // too many args for this branch
327
+ if (expectedResultType) {
328
+ try {
329
+ engine.subst.mergeFrom((0, unify_1.unify)(engine.subst.apply(cur), engine.subst.apply(expectedResultType)));
330
+ }
331
+ catch (e) {
332
+ // Bridge: branch result is a TCon X but a callable is expected — try
333
+ // the constructor's annotated call signatures for X.
334
+ const expR = engine.subst.apply(expectedResultType);
335
+ if (cur.tag === 'TCon' && expR.tag === 'TFun' &&
336
+ !engine.tryConstructorCallable(cur, cur, expectedResultType, expR)) {
337
+ throw e;
338
+ }
339
+ }
340
+ cur = engine.subst.apply(cur);
341
+ }
342
+ trialArgExpected = branchExpected.map((exp, k) => exp && isFnLiteralArg(k) ? engine.subst.apply(exp) : undefined);
343
+ return cur;
344
+ };
345
+ // Phase 1: discover which branches accept the provided args WITHOUT
346
+ // committing. Greedily committing the first matching branch is wrong for
347
+ // CURRIED overloads whose provided-arg prefix is identical across branches
348
+ // (e.g. `reduce :: (b->a->b) -> b -> [a] -> b` and
349
+ // `reduce :: (b->a->b) -> b -> { [k] :: a } -> b`): the discriminating
350
+ // argument arrives in a LATER application, so committing now would force the
351
+ // record argument against `[a]`. Instead we collect every compatible branch
352
+ // and, when more than one survives with a still-curried tail, return their
353
+ // tails as a union so the next application can discriminate.
354
+ // Union-argument distribution. A partial application of an overloaded
355
+ // function can stay AMBIGUOUS (`merge (lift3 f)` fits both the binary and
356
+ // the ternary `merge` branch — the discriminating Tuple arrives later), so
357
+ // its type is an overload-set union of the surviving tails. When such a
358
+ // value is itself the argument of an overloaded call (`compose (merge
359
+ // (lift3 f))`), re-inferring it against one parameter shape would commit
360
+ // the inner choice too early. Instead resolve this call once per
361
+ // argument branch, with the argument's type fixed to that branch, and keep
362
+ // every surviving result as a new overload-set union: the next
363
+ // application discriminates, exactly as for the inner call.
364
+ if (numArgs === 1) {
365
+ const nat = plainArgTypes[0];
366
+ if (nat && nat.tag === 'TCon' && nat.name === types_1.T_UNION && nat.overloadSet
367
+ && nat.args.length >= 2 && nat.args.every(b => b.tag === 'TFun')) {
368
+ const results = [];
369
+ engine.suppressPoisonDepth++;
370
+ try {
371
+ for (const argBranch of nat.args) {
372
+ for (const branchIndex of trialOrder) {
373
+ const r = (0, helpers_1.speculate)(engine, () => {
374
+ const diagsBefore = engine.diagnostics.length;
375
+ const out = attemptBranch(expandedBranches[branchIndex], [argBranch]);
376
+ const newErrors = engine.diagnostics.slice(diagsBefore)
377
+ .some(d => d.severity === undefined || d.severity === 1);
378
+ return newErrors || !out ? null : engine.subst.apply(out);
379
+ }, null);
380
+ if (r && !(0, types_1.containsErrorType)(r)) {
381
+ results.push(r);
382
+ break;
383
+ }
384
+ }
385
+ }
386
+ }
387
+ finally {
388
+ engine.suppressPoisonDepth--;
389
+ }
390
+ if (results.length >= 2 && results.every(r => r.tag === 'TFun')) {
391
+ const union = (0, types_1.tUnion)(results, { overloadSet: true });
392
+ engine.recordNodeType(node, union);
393
+ return union;
394
+ }
395
+ }
396
+ }
397
+ const accepted = [];
398
+ engine.suppressPoisonDepth++;
399
+ for (const branchIndex of trialOrder) {
400
+ trialArgExpected = [];
401
+ // A branch whose trial produced an ERROR diagnostic did not really match
402
+ // — e.g. an array-literal argument inferred against the branch's tuple
403
+ // parameter (`[k1, Number]`) with a mismatching element. Such failures
404
+ // happen inside argument inference, are reported as diagnostics instead
405
+ // of thrown, and would otherwise let the branch count as accepted.
406
+ const remainder = (0, helpers_1.speculate)(engine, () => {
407
+ const diagsBefore = engine.diagnostics.length;
408
+ const r = attemptBranch(expandedBranches[branchIndex]);
409
+ const newErrors = engine.diagnostics.slice(diagsBefore)
410
+ .some(d => d.severity === undefined || d.severity === 1);
411
+ return newErrors ? null : r;
412
+ }, null);
413
+ const argExpected = trialArgExpected;
414
+ if (remainder)
415
+ accepted.push({ branchIndex, remainder, argExpected });
416
+ }
417
+ engine.suppressPoisonDepth--;
418
+ // Union-argument distribution for a plain union (a value that is one of
419
+ // several types). With the direction check, a union argument only fits a
420
+ // branch when EVERY member does, so `toTask (x)` with `x :: Result | Task
421
+ // Result` against `Task a -> Task a` and `a -> Task a` would fall to the
422
+ // generic branch with `a := Result | Task Result`. At runtime each member
423
+ // takes the branch that fits it: resolve the call per member, and when the
424
+ // members pick DIFFERENT branches whose results agree, that common result
425
+ // is the call's type. When every member picks the same branch, or the
426
+ // results disagree, the ordinary trials decide (unchanged). Only tried
427
+ // when the direction check rejected a branch for the whole union.
428
+ if (numArgs === 1 && unionArgRejected) {
429
+ const nat = plainArgTypes[0];
430
+ if (nat && nat.tag === 'TCon' && nat.name === types_1.T_UNION && !nat.overloadSet
431
+ && nat.args.length >= 2 && nat.args.every(m => m.tag !== 'TFun')) {
432
+ const results = [];
433
+ const chosen = new Set();
434
+ engine.suppressPoisonDepth++;
435
+ try {
436
+ for (const member of nat.args) {
437
+ for (const branchIndex of trialOrder) {
438
+ const r = (0, helpers_1.speculate)(engine, () => {
439
+ const diagsBefore = engine.diagnostics.length;
440
+ const out = attemptBranch(expandedBranches[branchIndex], [member]);
441
+ const newErrors = engine.diagnostics.slice(diagsBefore)
442
+ .some(d => d.severity === undefined || d.severity === 1);
443
+ return newErrors || !out ? null : engine.subst.apply(out);
444
+ }, null);
445
+ if (r && !(0, types_1.containsErrorType)(r)) {
446
+ results.push(r);
447
+ chosen.add(branchIndex);
448
+ break;
449
+ }
450
+ }
451
+ }
452
+ }
453
+ finally {
454
+ engine.suppressPoisonDepth--;
455
+ }
456
+ if (results.length === nat.args.length && chosen.size >= 2) {
457
+ const common = (0, helpers_1.tryCommit)(engine, () => {
458
+ for (const r of results.slice(1)) {
459
+ engine.subst.mergeFrom((0, unify_1.unify)(engine.subst.apply(results[0]), engine.subst.apply(r)));
460
+ }
461
+ if (expectedResultType) {
462
+ engine.subst.mergeFrom((0, unify_1.unify)(engine.subst.apply(results[0]), engine.subst.apply(expectedResultType)));
463
+ }
464
+ return engine.subst.apply(results[0]);
465
+ });
466
+ if (common) {
467
+ engine.recordNodeType(node, common);
468
+ return common;
469
+ }
470
+ }
471
+ }
472
+ }
473
+ // Literal specificity. A branch whose parameter is a numeric literal type
474
+ // (`_Tuple :: 2 -> …`) only accepts that very literal, so when it matched
475
+ // it is strictly more specific than a rival that merely accepted a
476
+ // `Number` (`_Tuple :: Number -> Any`, the fallback for an unknown `n`).
477
+ // Keep the branches with the most literal-typed parameters.
478
+ if (accepted.length > 1) {
479
+ const literalParams = (branchIndex) => {
480
+ const b = expandedBranches[branchIndex];
481
+ const params = b.param.tag === 'TCon' && b.param.name === types_1.T_TUPLE
482
+ ? b.param.args.slice(0, numArgs)
483
+ : (() => { const ps = []; let w = b; for (let k = 0; k < numArgs && w.tag === 'TFun'; k++) {
484
+ ps.push(w.param);
485
+ w = w.result;
486
+ } return ps; })();
487
+ return params.filter(p => p.tag === 'TCon' && p.args.length === 0 && (0, types_1.isNumLitName)(p.name)).length;
488
+ };
489
+ const scores = accepted.map(a => literalParams(a.branchIndex));
490
+ const best = Math.max(...scores);
491
+ if (best > 0 && scores.some(sc => sc < best)) {
492
+ for (let i = accepted.length - 1; i >= 0; i--) {
493
+ if (scores[i] < best)
494
+ accepted.splice(i, 1);
495
+ }
496
+ }
497
+ }
498
+ // Poison-absorption filter. `attemptBranch` captures its remainder via
499
+ // `subst.apply`, so if a branch "accepted" the args only because a nested
500
+ // call's unification failed and `unifyWithDiagnostic` bound the offending
501
+ // free vars to the `$error` sentinel (see `poisonFreeVars`), that sentinel
502
+ // is BAKED into the captured remainder — even though the substitution is
503
+ // rolled back immediately after. Such a branch did not genuinely match; it
504
+ // merely absorbed the failure. Drop every `$error`-polluted remainder,
505
+ // provided at least one rival branch matched cleanly. When EVERY branch is
506
+ // polluted (e.g. an argument was already poisoned upstream) the set is left
507
+ // intact so a real diagnostic still surfaces downstream.
508
+ if (accepted.some(a => !(0, types_1.containsErrorType)(a.remainder))) {
509
+ for (let i = accepted.length - 1; i >= 0; i--) {
510
+ if ((0, types_1.containsErrorType)(accepted[i].remainder))
511
+ accepted.splice(i, 1);
512
+ }
513
+ }
514
+ // Natural-type structural filter. A branch can spuriously "accept" a nested
515
+ // overloaded-call argument: pushing the branch's (function-shaped) parameter
516
+ // down into that argument forces the argument's OWN overload resolution to
517
+ // fail, yielding a poison `tVar` that then unifies with anything. Re-check
518
+ // each accepted branch against the argument's NATURAL type (inferred with no
519
+ // expected type). When a genuine structural conflict exists between two
520
+ // concrete shapes (e.g. an applied container `f b` vs a function `b -> c`)
521
+ // and at least one rival branch is naturally compatible, drop the
522
+ // conflicting branch — it only "matched" via the poisoned variable.
523
+ if (accepted.length > 1) {
524
+ const branchParams = (branch) => {
525
+ const params = [];
526
+ if (branch.param.tag === 'TCon' && branch.param.name === types_1.T_TUPLE) {
527
+ for (let k = 0; k < numArgs; k++)
528
+ params.push(branch.param.args[k]);
529
+ }
530
+ else {
531
+ let walk = branch;
532
+ for (let k = 0; k < numArgs; k++) {
533
+ if (walk.tag === 'TFun') {
534
+ params.push(walk.param);
535
+ walk = walk.result;
536
+ }
537
+ else
538
+ params.push(undefined);
539
+ }
540
+ }
541
+ return params;
542
+ };
543
+ const naturallyCompatible = (branchIndex) => {
544
+ const params = branchParams(expandedBranches[branchIndex]);
545
+ for (let k = 0; k < numArgs; k++) {
546
+ const nat = plainArgTypes[k];
547
+ const par = params[k];
548
+ if (!nat || !par)
549
+ continue;
550
+ const na = engine.subst.apply(nat);
551
+ const pa = engine.subst.apply(par);
552
+ // A bare type variable on either side unifies with anything and must
553
+ // not trigger a rejection — only two concrete shapes can conflict.
554
+ if (na.tag === 'TVar' || pa.tag === 'TVar')
555
+ continue;
556
+ const ok = (0, helpers_1.speculate)(engine, () => { engine.subst.mergeFrom((0, unify_1.unify)(na, pa)); return true; }, false);
557
+ if (!ok)
558
+ return false;
559
+ }
560
+ return true;
561
+ };
562
+ const compat = accepted.map(a => naturallyCompatible(a.branchIndex));
563
+ if (compat.some(c => c) && compat.some(c => !c)) {
564
+ for (let i = accepted.length - 1; i >= 0; i--) {
565
+ if (!compat[i])
566
+ accepted.splice(i, 1);
567
+ }
568
+ }
569
+ }
570
+ // Constraint-satisfiability filter. A branch can "accept" the args by mere
571
+ // unification yet pin one of its constraint variables to a type that does
572
+ // NOT satisfy that constraint (e.g. the `Category c => TypeRep c -> c`
573
+ // overload of `id` accepts `id(Function)` by binding `c = Function`, but
574
+ // `Function` is not a `Category`). Detect such branches by re-running them
575
+ // in isolation and counting freshly-violated pending constraints; drop them
576
+ // when at least one rival branch is constraint-clean. When every branch
577
+ // violates (a genuine error) the set is left intact so a diagnostic still
578
+ // surfaces downstream.
579
+ // Both filters below (constraint violations, rigid pinning) measure the
580
+ // SAME thing — the state right after `attemptBranch` from the current
581
+ // substitution — so each surviving branch is trialled ONCE and both metrics
582
+ // are read from that single speculation (each trial re-infers every
583
+ // argument, which made these filters the dominant cost of overload
584
+ // resolution). `uniqueRigid` comes from the real substitution, which the
585
+ // speculative filters never change.
586
+ const uniqueRigid = [];
587
+ if (accepted.length > 1) {
588
+ const rigidVarIds = engine.pendingConstraints
589
+ .filter(c => c.given)
590
+ .map(c => {
591
+ const r = engine.subst.apply({ tag: 'TVar', id: c.varId, name: '' });
592
+ return r.tag === 'TVar' ? r.id : -1;
593
+ })
594
+ .filter(id => id >= 0);
595
+ uniqueRigid.push(...new Set(rigidVarIds));
596
+ }
597
+ // A rigid functor variable must stay a variable (or another kind
598
+ // variable). If a branch resolves it to anything concrete — a container
599
+ // constructor (`Array`, `Object`), a function/Reader shape, a record, … —
600
+ // that branch violates parametricity.
601
+ const pinsRigidNow = () => {
602
+ for (const id of uniqueRigid) {
603
+ const r = engine.subst.apply({ tag: 'TVar', id, name: '' });
604
+ if (r.tag !== 'TVar' && !(r.tag === 'TCon' && (0, types_1.parseKvName)(r.name)))
605
+ return true;
606
+ }
607
+ return false;
608
+ };
609
+ const trialMetrics = new Map();
610
+ if (accepted.length > 1) {
611
+ for (const a of accepted) {
612
+ let pins = false;
613
+ const violations = (0, helpers_1.speculate)(engine, () => {
614
+ attemptBranch(expandedBranches[a.branchIndex]);
615
+ pins = pinsRigidNow();
616
+ const before = engine.diagnostics.length;
617
+ engine.validatePendingConstraints();
618
+ return engine.countViolatedPendingConstraints() + (engine.diagnostics.length - before);
619
+ }, Number.MAX_SAFE_INTEGER);
620
+ trialMetrics.set(a.branchIndex, { violations, pins });
621
+ }
622
+ }
623
+ if (accepted.length > 1) {
624
+ // Counted with the FULL check (method presence AND method shape, e.g. a
625
+ // curried `Foldable#reduce` vs the native `Array#reduce`), so a branch
626
+ // that only unifies structurally does not win just by coming first in
627
+ // declaration order. Unrelated pending constraints count equally for
628
+ // every branch, hence "fewest violations" rather than "zero".
629
+ const fewest = Math.min(...accepted.map(a => trialMetrics.get(a.branchIndex).violations));
630
+ const clean = accepted.filter(a => trialMetrics.get(a.branchIndex).violations === fewest);
631
+ if (clean.length > 0 && clean.length < accepted.length) {
632
+ accepted.length = 0;
633
+ accepted.push(...clean);
634
+ }
635
+ }
636
+ // Parametricity filter (must run BEFORE the ambiguous curried-union path
637
+ // below). A universally-quantified type-class variable introduced by an
638
+ // annotation's `=>` context — e.g. the `f` of
639
+ // `(Applicative f, Setoid (f b)) => TypeRep f -> …` — is RIGID: the body may
640
+ // not instantiate it to a concrete constructor, even one that happens to
641
+ // satisfy the constraint (`Array` is an `Applicative`, yet a `forall f`
642
+ // signature still may not pick `f := Array`). A concrete-container overload
643
+ // branch (`[a -> b] -> [a] -> [b]`) can nonetheless "accept" an argument
644
+ // whose type is `f (a -> b)` by binding the rigid `f := Array`; if such a
645
+ // branch survives into an ambiguous union, a later application
646
+ // (`ap(of(A)(f))(of(A)(x))`) propagates the concrete slot back and pins the
647
+ // shared rigid functor, producing a spurious `Cannot unify 'Array' with
648
+ // 'f a'`. Detect this by trialling each branch (against the REAL
649
+ // substitution, so the rigid var ids are the genuine ones) and dropping any
650
+ // branch that leaves a given/rigid constraint variable bound to a concrete
651
+ // constructor — provided at least one rival branch keeps them abstract. A
652
+ // no-op when there are no given constraints (unannotated code stays
653
+ // permissive) or when every branch pins one (a real error still surfaces).
654
+ let rigidFilterNarrowed = false;
655
+ if (accepted.length > 1 && uniqueRigid.length > 0) {
656
+ const clean = accepted.filter(a => !trialMetrics.get(a.branchIndex).pins);
657
+ if (clean.length > 0 && clean.length < accepted.length) {
658
+ accepted.length = 0;
659
+ accepted.push(...clean);
660
+ rigidFilterNarrowed = true;
661
+ }
662
+ }
663
+ // When the parametricity filter above narrowed the set to a single still-
664
+ // curried branch, keep it UNCOMMITTED (return the loose remainder) instead
665
+ // of falling through to the single-branch commit path. Committing via
666
+ // `attemptBranch` here re-infers the argument against the branch's parameter
667
+ // and mutates the shared substitution, which — for a self-referential
668
+ // argument such as `of(A)(x => x) :: f (a -> a)` — ties the rigid functor's
669
+ // element variable to `a -> a` and yields a spurious infinite type at the
670
+ // next application. The uncommitted remainder unifies cleanly there, exactly
671
+ // as the multi-branch ambiguous union does.
672
+ if (rigidFilterNarrowed && accepted.length === 1 && accepted[0].remainder.tag === 'TFun') {
673
+ const remainder = accepted[0].remainder;
674
+ engine.recordNodeType(node, remainder);
675
+ return remainder;
676
+ }
677
+ if (accepted.length > 1 && accepted.every(a => a.remainder.tag === 'TFun')) {
678
+ // Still-ambiguous curried overload: keep all compatible tails alive as a
679
+ // union so a later application can pick the right branch. Do NOT pin
680
+ // `callSiteOverloadIndex` — the call site remains compatible with every
681
+ // surviving overload (hover / signature help surface them all).
682
+ //
683
+ // A provided callback parameter (e.g. `pair` in `map(pair => …)(acc)`) would
684
+ // otherwise hover as a bare type variable: the Phase-1 trials were rolled
685
+ // back, so the param node references a now-unbound trial variable while each
686
+ // surviving tail references ITS OWN (also unbound) element variable. We
687
+ // reconnect them WITHOUT committing any branch: for every provided function
688
+ // literal, allocate one shared element variable per parameter position and
689
+ // rewrite each surviving tail so that its corresponding element variable IS
690
+ // that shared variable. Recording the callback param nodes against the same
691
+ // shared variable means a later curried application (which pins the functor
692
+ // element, e.g. `(acc)`) resolves the callback params, while the union tails
693
+ // stay uncommitted so signature-help narrowing is unaffected.
694
+ const remainders = accepted.map(a => a.remainder);
695
+ for (let k = 0; k < numArgs; k++) {
696
+ if (!isFnLiteralArg(k))
697
+ continue;
698
+ // If any surviving branch applied a fully-resolved (concrete-parameter)
699
+ // function type to this callback, the callback's element type is already
700
+ // known (e.g. `Pair Number (f a) -> …` once a later `(acc)` pinned the
701
+ // functor). The callback BODY was only ever inferred under the rolled-
702
+ // back Phase-1 trials, so its parameter usages and body-local bindings
703
+ // (`pair.fst`, `let n = pair.fst`, `let xs = pair.snd`) still reference
704
+ // now-unbound trial variables and hover as bare vars. Re-infer the whole
705
+ // callback against that concrete function type ONCE so the entire body
706
+ // resolves. The concrete type carries only OUTER variables (never the
707
+ // union tails' own element variable), so the union built below stays
708
+ // polymorphic and signature-help narrowing is unaffected.
709
+ const concreteFn = accepted
710
+ .map(a => (a.argExpected[k] ? engine.subst.apply(a.argExpected[k]) : undefined))
711
+ .find(t => t !== undefined && t.tag === 'TFun' && t.param.tag !== 'TVar');
712
+ if (concreteFn) {
713
+ const argNode = node.arguments[k];
714
+ // Drop the callback body's stale node-type recordings first: the
715
+ // Phase-1 trials that produced them were rolled back, so declaration
716
+ // sites (`let n = pair.fst`) still point at now-unbound trial vars that
717
+ // re-inference does not overwrite (a binding is recorded once, at its
718
+ // declarator). Clearing the span makes the re-inference authoritative.
719
+ for (const off of [...engine.nodeTypes.keys()]) {
720
+ if (off >= argNode.start && off < argNode.end)
721
+ engine.nodeTypes.delete(off);
722
+ }
723
+ for (const off of [...engine.nodeTypesByEnd.keys()]) {
724
+ if (off > argNode.start && off <= argNode.end)
725
+ engine.nodeTypesByEnd.delete(off);
726
+ }
727
+ // Re-inference is best-effort; the union return below is unchanged.
728
+ (0, helpers_1.bestEffort)(engine, () => {
729
+ engine.inferExpressionWithExpected(argNode, env, concreteFn);
730
+ });
731
+ continue;
732
+ }
733
+ // Otherwise every branch left this callback's parameters as free element
734
+ // vars (e.g. while the enclosing binding is still being generalised).
735
+ // Link each parameter position to ONE shared var (rewriting each
736
+ // surviving tail) so a later curried application — which pins the functor
737
+ // element — resolves it.
738
+ const freeArgNode = node.arguments[k];
739
+ const paramNodes = (node.arguments[k].params) ?? [];
740
+ const sharedByPos = [];
741
+ for (let j = 0; j < paramNodes.length; j++) {
742
+ const pn = paramNodes[j];
743
+ if (pn.type !== 'Identifier') {
744
+ sharedByPos[j] = (0, types_1.tVar)();
745
+ continue;
746
+ }
747
+ // Each surviving branch's applied type for this parameter position
748
+ // (walk the curried applied-expected type `j` steps).
749
+ const perBranch = accepted.map(a => {
750
+ let walk = a.argExpected[k];
751
+ for (let s = 0; s < j && walk && walk.tag === 'TFun'; s++)
752
+ walk = walk.result;
753
+ return walk && walk.tag === 'TFun' ? walk.param : undefined;
754
+ });
755
+ // Link every branch's free element var to ONE shared var (rewriting each
756
+ // surviving tail) so a later curried application resolves it.
757
+ const shared = (0, types_1.tVar)();
758
+ let linked = false;
759
+ perBranch.forEach((t, bi) => {
760
+ if (t && t.tag === 'TVar') {
761
+ const id = t.id;
762
+ remainders[bi] = (0, typeUtils_1.mapType)(remainders[bi], (x) => x.tag === 'TVar' && x.id === id ? shared : undefined);
763
+ linked = true;
764
+ }
765
+ });
766
+ sharedByPos[j] = shared;
767
+ if (linked)
768
+ engine.recordNodeType(pn, shared);
769
+ }
770
+ // The callback BODY (`let n = pair.fst`, `let xs = pair.snd`, `n - 1`, …)
771
+ // was only inferred under the rolled-back Phase-1 trials, so its local
772
+ // bindings still reference now-unbound trial variables and hover as bare
773
+ // vars. Re-infer the callback against a function type built from the
774
+ // shared parameter vars (RESULT left free) so body-internal constraints
775
+ // resolve those bindings from how they are USED (e.g. `n - 1` ⇒
776
+ // `n :: Number`). The shared parameter stays a free variable — its field
777
+ // accesses are structurally unconstrained — so the union tails remain
778
+ // polymorphic and signature-help narrowing is unaffected.
779
+ if (sharedByPos.length > 0) {
780
+ let expected = (0, types_1.tVar)();
781
+ for (let j = sharedByPos.length - 1; j >= 0; j--) {
782
+ expected = (0, types_1.tFun)(sharedByPos[j] ?? (0, types_1.tVar)(), expected);
783
+ }
784
+ for (const off of [...engine.nodeTypes.keys()]) {
785
+ if (off >= freeArgNode.start && off < freeArgNode.end)
786
+ engine.nodeTypes.delete(off);
787
+ }
788
+ for (const off of [...engine.nodeTypesByEnd.keys()]) {
789
+ if (off > freeArgNode.start && off <= freeArgNode.end)
790
+ engine.nodeTypesByEnd.delete(off);
791
+ }
792
+ // Re-inference is best-effort; the union return below is unchanged.
793
+ (0, helpers_1.bestEffort)(engine, () => {
794
+ engine.inferExpressionWithExpected(freeArgNode, env, expected);
795
+ });
796
+ }
797
+ }
798
+ // The surviving tails are still an overload set: keep declaration order
799
+ // so the next application tries them in that order too.
800
+ const aligned = (0, types_1.tUnion)(remainders, { overloadSet: true });
801
+ engine.recordNodeType(node, aligned);
802
+ return aligned;
803
+ }
804
+ // Constraint-variable preservation. When an argument's type carries a
805
+ // type-class constraint variable (encoded as a `$kv:` kind-variable TCon —
806
+ // e.g. `f a` under `Alt f =>`), a concrete overload branch such as
807
+ // `Array a -> Array a -> Array a` can still "accept" it by unifying the
808
+ // kind variable with `Array`, silently pinning the polymorphic parameter to
809
+ // a concrete type everywhere. That is wrong: the constraint-polymorphic
810
+ // branch (`Alt f => f a -> …`) is the genuine match. Re-order the accepted
811
+ // branches so those that DON'T concretise a constraint variable present in
812
+ // the arguments are committed first. This is order-independent (it does not
813
+ // rely on the union's branch order) and is a no-op when no argument carries
814
+ // a constraint variable.
815
+ if (accepted.length > 1) {
816
+ const argKvIds = collectConstraintKvIds(engine, node, env);
817
+ if (argKvIds.size > 0) {
818
+ const concretisations = (branch) => (0, helpers_1.speculate)(engine, () => {
819
+ attemptBranch(branch);
820
+ let count = 0;
821
+ for (const id of argKvIds) {
822
+ const bound = engine.subst.apply((0, types_1.tCon)((0, types_1.kvName)('', id), []));
823
+ // After substitution the kind variable resolves to a concrete
824
+ // (non-kind-variable) constructor when the branch pinned it.
825
+ if (bound.tag === 'TCon' && !(0, types_1.parseKvName)(bound.name))
826
+ count++;
827
+ }
828
+ return count;
829
+ }, Number.MAX_SAFE_INTEGER);
830
+ const score = new Map();
831
+ for (const a of accepted)
832
+ score.set(a.branchIndex, concretisations(expandedBranches[a.branchIndex]));
833
+ accepted.sort((x, y) => (score.get(x.branchIndex) - score.get(y.branchIndex)));
834
+ }
835
+ }
836
+ if (accepted.length >= 1) {
837
+ // A single compatible branch (or several whose tail is already a final,
838
+ // fully-applied value): commit the best one (trialOrder is best-first).
839
+ const branchIndex = accepted[0].branchIndex;
840
+ const committed = (0, helpers_1.tryCommit)(engine, () => {
841
+ const remainder = attemptBranch(expandedBranches[branchIndex]);
842
+ const result = (0, call_rows_1.applyMergeReduction)(engine, engine.subst.apply(remainder ?? (0, types_1.tVar)()), node);
843
+ engine.recordNodeType(node, result);
844
+ // Only pin the matched overload index for a DIRECT application of the
845
+ // named/member binding (`f(args)` / `obj.m(args)`). For a chained
846
+ // curried sub-application (`f(a)(b)` — callee is itself a CallExpression)
847
+ // the union being resolved is a transient remainder union whose branch
848
+ // order does NOT correspond to the original overload list, and every
849
+ // sub-application shares the same callee start offset, so pinning here
850
+ // would overwrite the call site with a meaningless index. Leaving it
851
+ // unset lets hover / signature help surface all compatible overloads.
852
+ if (node.callee.type !== 'CallExpression') {
853
+ engine.callSiteOverloadIndex.set(calleeStart, branchIndex);
854
+ }
855
+ return result;
856
+ });
857
+ if (committed)
858
+ return committed;
859
+ }
860
+ // No branch matched. When the caller supplied an expected RESULT type,
861
+ // check whether the arguments alone select a branch: then the arguments
862
+ // are fine and the result is what conflicts — say that, instead of the
863
+ // misleading "No overload matches arguments" (e.g. `fs.readFileSync (p,
864
+ // "utf-8")` inside a function annotated to return a Number).
865
+ if (expectedResultType) {
866
+ const expectedForMessage = expectedResultType;
867
+ expectedResultType = undefined;
868
+ let argOnly = null;
869
+ engine.suppressPoisonDepth++;
870
+ try {
871
+ for (const branchIndex of trialOrder) {
872
+ trialArgExpected = [];
873
+ const remainder = (0, helpers_1.speculate)(engine, () => {
874
+ const r = attemptBranch(expandedBranches[branchIndex]);
875
+ return r ? (0, call_rows_1.applyMergeReduction)(engine, engine.subst.apply(r)) : null;
876
+ }, null);
877
+ if (remainder) {
878
+ argOnly = remainder;
879
+ break;
880
+ }
881
+ }
882
+ }
883
+ finally {
884
+ engine.suppressPoisonDepth--;
885
+ expectedResultType = expectedForMessage;
886
+ }
887
+ if (argOnly) {
888
+ engine.addDiag(`Type mismatch: Cannot unify '${(0, types_1.prettyTypeToString)(argOnly)}' with '${(0, types_1.prettyTypeToString)(engine.subst.apply(expectedForMessage))}'`, node);
889
+ return (0, types_1.tVar)();
890
+ }
891
+ }
892
+ // No branch matched — emit a single descriptive diagnostic.
893
+ // Re-infer argTypes once more in raw form for the message.
894
+ const rawArgTypes = node.arguments.map(a => engine.inferExpression(a, env));
895
+ const sigs = branches.map(b => (0, types_1.prettyTypeToString)(b)).join('\n ');
896
+ const argList = rawArgTypes.map(t => (0, types_1.prettyTypeToString)(engine.subst.apply(t))).join(', ');
897
+ engine.addDiag(`No overload matches arguments (${argList}). Available signatures:\n ${sigs}`, node);
898
+ return (0, types_1.tVar)();
899
+ }
900
+ //# sourceMappingURL=call-overloads.js.map