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,1700 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Unification — the heart of Hindley-Milner
4
+ //
5
+ // WHAT THIS FILE DOES (in plain language)
6
+ // ---------------------------------------------------------------------------
7
+ // *Unification* answers one question, over and over: "can these two type
8
+ // descriptions be made identical, and if so, what must each placeholder
9
+ // stand for?" It is like fitting two puzzle pieces together:
10
+ //
11
+ // • unify `Array a` with `Array Number` → yes, and we learn a = Number
12
+ // • unify `Number` with `String` → no → a type error is reported
13
+ //
14
+ // The answers ("a = Number") are collected in a Substitution (see
15
+ // substitution.ts). The main entry point is `unify(t1, t2)`; internally
16
+ // `unifyCore` works through a long ladder of cases, roughly ordered from
17
+ // "most flexible" to "most specific":
18
+ //
19
+ // 1. wildcards / Any — match anything, ask no questions
20
+ // 2. unions — match if ANY member matches
21
+ // 3. type variables — bind the placeholder to the other side
22
+ // (after the occurs check, which forbids a
23
+ // placeholder containing itself)
24
+ // 4. rows & labels — the machinery for "open" objects
25
+ // 5. functions — parameter unifies with parameter,
26
+ // result with result (incl. curried /
27
+ // variadic chains)
28
+ // 6. records — field-by-field, honouring open rows
29
+ // 7. named types (TCon) — same name, then unify the arguments
30
+ // 8. assorted bridges — special conversions (TypeRep, numeric
31
+ // subtypes, built-in members, merge shapes)
32
+ //
33
+ // A failed match throws UnificationError; the inference engine catches these
34
+ // and turns them into the squiggly-underline diagnostics users see.
35
+ // ============================================================================
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.OccursCheckError = exports.UnificationError = void 0;
38
+ exports.withAliasExpander = withAliasExpander;
39
+ exports.unify = unify;
40
+ exports.unifyWidening = unifyWidening;
41
+ const types_1 = require("./types");
42
+ const typeUtils_1 = require("./typeUtils");
43
+ const substitution_1 = require("./substitution");
44
+ const methodRegistry_1 = require("../registries/methodRegistry");
45
+ const dataTypeRegistry_1 = require("../registries/dataTypeRegistry");
46
+ /** Stack traces of internal control-flow errors are only useful while
47
+ * debugging hinmil itself (`HM_DEBUG=1`). */
48
+ const CAPTURE_STACKS = typeof process !== 'undefined' && !!process.env?.HM_DEBUG;
49
+ /**
50
+ * Unification failure. Thrown very often during SPECULATIVE inference
51
+ * (overload trials, natural-type checks) where the error is caught and
52
+ * discarded, so it is kept cheap: the message is rendered lazily on first
53
+ * read and no stack trace is captured (unless `HM_DEBUG` is set). Together
54
+ * these were ~4% of the FP-library lint.
55
+ */
56
+ class UnificationError extends Error {
57
+ constructor(left, right, message) {
58
+ const limit = Error.stackTraceLimit;
59
+ if (!CAPTURE_STACKS)
60
+ Error.stackTraceLimit = 0;
61
+ super();
62
+ this.left = left;
63
+ this.right = right;
64
+ Error.stackTraceLimit = limit;
65
+ this._message = message;
66
+ this.name = 'UnificationError';
67
+ }
68
+ get message() {
69
+ if (this._message === undefined) {
70
+ this._message = `Cannot unify ${(0, types_1.typeToString)(this.left)} with ${(0, types_1.typeToString)(this.right)}`;
71
+ }
72
+ return this._message;
73
+ }
74
+ set message(value) {
75
+ this._message = value;
76
+ }
77
+ }
78
+ exports.UnificationError = UnificationError;
79
+ /**
80
+ * Specialised {@link UnificationError} thrown by the occurs check when a type
81
+ * variable would have to be bound to a type that mentions itself (an infinite
82
+ * type, e.g. `b ~ a -> b`). Carries the offending variable and the type it
83
+ * occurs in so callers can render an actionable "infinite type" diagnostic.
84
+ * The message keeps the historical `Infinite type:` prefix for back-compat
85
+ * with existing `startsWith('Infinite type:')` checks.
86
+ */
87
+ class OccursCheckError extends UnificationError {
88
+ constructor(left, right, tvType, occursInType) {
89
+ super(left, right, `Infinite type: ${tvType.tag === 'TVar' ? tvType.name : (0, types_1.typeToString)(tvType)} ~ ${(0, types_1.typeToString)(occursInType)}`);
90
+ this.tvType = tvType;
91
+ this.occursInType = occursInType;
92
+ this.name = 'OccursCheckError';
93
+ }
94
+ }
95
+ exports.OccursCheckError = OccursCheckError;
96
+ /** Maximum recursion depth for unification / occurs-check to prevent stack overflow. */
97
+ const MAX_DEPTH = 500;
98
+ /**
99
+ * Occurs check: does type variable `id` appear anywhere inside `type`?
100
+ * Prevents infinite types like `a = a -> b`.
101
+ */
102
+ function occursIn(id, type, depth = 0) {
103
+ if (depth > MAX_DEPTH) {
104
+ throw new UnificationError({ tag: 'TVar', id, name: `t${id}` }, type, `Occurs-check exceeded maximum depth (${MAX_DEPTH})`);
105
+ }
106
+ switch (type.tag) {
107
+ case 'TVar':
108
+ return type.id === id;
109
+ case 'TCon': {
110
+ // Check if TCon name encodes a kind variable with this id.
111
+ // At depth 0 (top-level), a kv-TCon whose varId matches is NOT
112
+ // infinite — it's just the constructor applied to args (m := m a).
113
+ // Only flag it as infinite if it appears nested (depth > 0) or if
114
+ // the id also appears inside the args.
115
+ const kv = (0, types_1.parseKvName)(type.name);
116
+ if (kv && kv.varId === id) {
117
+ if (depth > 0)
118
+ return true;
119
+ return type.args.some((a) => occursIn(id, a, depth + 1));
120
+ }
121
+ return type.args.some((a) => occursIn(id, a, depth + 1));
122
+ }
123
+ case 'TFun':
124
+ return occursIn(id, type.param, depth + 1) || occursIn(id, type.result, depth + 1);
125
+ case 'TRecord':
126
+ for (const k in type.fields) {
127
+ if (occursIn(id, type.fields[k], depth + 1))
128
+ return true;
129
+ }
130
+ // Label-polymorphic fields (`{ [k] :: a, ...r }`) keep their value type
131
+ // in `labelFields`, NOT in `fields`. Skipping them lets an infinite
132
+ // type such as `a = { [k] :: a }` escape the occurs check and later
133
+ // blows the stack in `Substitution.apply`.
134
+ if (type.labelFields) {
135
+ for (const lf of type.labelFields) {
136
+ if (occursIn(id, lf.type, depth + 1))
137
+ return true;
138
+ if (occursIn(id, lf.label, depth + 1))
139
+ return true;
140
+ }
141
+ }
142
+ if (type.rest && occursIn(id, type.rest, depth + 1))
143
+ return true;
144
+ return false;
145
+ case 'TLabel':
146
+ return type.kind === 'var' && type.id === id;
147
+ case 'TRow':
148
+ return type.id === id;
149
+ case 'TForall':
150
+ // Bound vars are globally fresh — `id` can only refer to a FREE
151
+ // (outer) variable, so just recurse into the body.
152
+ return occursIn(id, type.body, depth + 1);
153
+ }
154
+ }
155
+ /** Unify a flexible type (wildcard / Any) with another type.
156
+ * Binds the other side if it's a TVar; otherwise propagates the
157
+ * flexible type into any free TVars contained in `other` so that
158
+ * expressions like `f(x)` against `f :: Any` produce `Any` rather
159
+ * than a leftover unbound result tvar. This mirrors the semantics
160
+ * of a top type: every position absorbs `Any`, including the result
161
+ * of a function call. */
162
+ function unifyFlexible(flex, other) {
163
+ if (other.tag === 'TVar') {
164
+ return substitution_1.Substitution.singleton(other.id, flex);
165
+ }
166
+ // Walk `other` and bind any unbound TVars to `flex`. We avoid
167
+ // touching label vars (which live in their own sort).
168
+ const subst = new substitution_1.Substitution();
169
+ const visit = (t) => {
170
+ switch (t.tag) {
171
+ case 'TVar':
172
+ if (subst.lookup(t.id) === undefined)
173
+ subst.set(t.id, flex);
174
+ return;
175
+ case 'TCon':
176
+ for (const arg of t.args)
177
+ visit(arg);
178
+ return;
179
+ case 'TFun':
180
+ visit(t.param);
181
+ visit(t.result);
182
+ return;
183
+ case 'TRecord':
184
+ for (const k of Object.keys(t.fields))
185
+ visit(t.fields[k]);
186
+ if (t.rest)
187
+ visit(t.rest);
188
+ return;
189
+ case 'TForall':
190
+ // Never bind variables under a nested quantifier — a wildcard must
191
+ // not erase the polymorphism a rank-N annotation demands.
192
+ return;
193
+ default:
194
+ return;
195
+ }
196
+ };
197
+ visit(other);
198
+ return subst;
199
+ }
200
+ /** Instantiate a nested `forall` with fresh flexible type variables.
201
+ * Used for graceful degradation when a TForall meets a non-forall type in a
202
+ * context that has no dedicated rank-N handling (call-site subsumption in
203
+ * the inference layer intercepts BEFORE unification on the strict path). */
204
+ function instantiateForallBody(f) {
205
+ const s = new substitution_1.Substitution();
206
+ for (let i = 0; i < f.vars.length; i++) {
207
+ s.set(f.vars[i], (0, types_1.tVar)(f.varNames[i]));
208
+ }
209
+ return s.apply(f.body);
210
+ }
211
+ /** Bind a TVar to a type, checking for occurs and union membership. */
212
+ function bindVar(tv, other, t1, t2) {
213
+ // TVar is already a direct member of the union — no binding needed
214
+ if (other.tag === 'TCon' && other.name === types_1.T_UNION &&
215
+ other.args.some(a => a.tag === 'TVar' && a.id === tv.id)) {
216
+ return new substitution_1.Substitution();
217
+ }
218
+ if (occursIn(tv.id, other)) {
219
+ throw new OccursCheckError(t1, t2, tv, other);
220
+ }
221
+ return substitution_1.Substitution.singleton(tv.id, other);
222
+ }
223
+ /** Unify argument lists pairwise, threading the substitution through. */
224
+ function unifyArgs(args1, args2, subst, depth) {
225
+ for (let i = 0; i < args1.length; i++) {
226
+ const s = unify(subst.apply(args1[i]), subst.apply(args2[i]), depth);
227
+ subst = s.compose(subst);
228
+ }
229
+ return subst;
230
+ }
231
+ /** Unify a kind-variable TCon against a concrete TCon with partial application. */
232
+ function unifyKvConcrete(kvSide, kvInfo, concrete, t1, t2, depth) {
233
+ if (kvSide.args.length > concrete.args.length) {
234
+ throw new UnificationError(t1, t2);
235
+ }
236
+ if (occursIn(kvInfo.varId, concrete)) {
237
+ throw new UnificationError(t1, t2, `Infinite type`);
238
+ }
239
+ const numAbsorbed = concrete.args.length - kvSide.args.length;
240
+ const absorbedArgs = concrete.args.slice(0, numAbsorbed);
241
+ const matchingArgs = concrete.args.slice(numAbsorbed);
242
+ let subst = substitution_1.Substitution.singleton(kvInfo.varId, (0, types_1.tCon)(concrete.name, absorbedArgs));
243
+ return unifyArgs(kvSide.args, matchingArgs, subst, depth);
244
+ }
245
+ /** TypeRep m coercion: extract the return type's constructor from a function. */
246
+ function isInternalTypeName(name) {
247
+ return name.startsWith('$') || name === types_1.T_ARRAY || name === types_1.T_OBJECT || name === 'Function';
248
+ }
249
+ function unifyTypeRep(typeRep, fn, depth) {
250
+ const ret = (0, types_1.getReturnType)(fn);
251
+ const inner = typeRep.args[0];
252
+ // A constructor function whose result is an OPAQUE type variable — one
253
+ // that does not occur in any parameter — witnesses `TypeRep` for exactly
254
+ // that variable: `(b -> m)` in
255
+ // `mconcatMap :: Monoid m => (b -> m) -> … -> m`, where the same value is
256
+ // called AND passed to `empty :: TypeRep m -> m`. A result variable that
257
+ // is threaded from a parameter (`a -> a`, identity) is not a constructor.
258
+ if (ret.tag === 'TVar') {
259
+ let paramsMentionRet = false;
260
+ for (let t = fn; t.tag === 'TFun'; t = t.result) {
261
+ if (occursIn(ret.id, t.param)) {
262
+ paramsMentionRet = true;
263
+ break;
264
+ }
265
+ }
266
+ if (!paramsMentionRet)
267
+ return unify(inner, ret, depth + 1);
268
+ }
269
+ if (ret.tag !== 'TCon') {
270
+ throw new UnificationError(typeRep, fn);
271
+ }
272
+ // `TypeRep m` denotes the constructor ITSELF (possibly partially applied),
273
+ // not one saturated application of it. When the rep slot is still a bare
274
+ // type variable, strip the witness return type's trailing ELEMENT argument:
275
+ // `a -> Identity a` witnesses `TypeRep Identity`, not `TypeRep (Identity a)`.
276
+ // Leading args stay absorbed (`a -> RTask r e a` → `TypeRep (RTask r e)`),
277
+ // mirroring unifyKvConcrete's partial-application absorption. This keeps a
278
+ // rep usable at MULTIPLE element types in one body (of(A)(x) and of(A)(y)).
279
+ // Only a type-VARIABLE trailing arg is stripped — a concrete element
280
+ // (`() -> Config String`) is part of the constructor's identity.
281
+ if (ret.args.length > 0 && ret.args[ret.args.length - 1].tag === 'TVar') {
282
+ if (inner.tag === 'TVar') {
283
+ return unify(inner, (0, types_1.tCon)(ret.name, ret.args.slice(0, -1)), depth + 1);
284
+ }
285
+ // The rep slot already resolved to a bare/partial constructor (a previous
286
+ // witness bound it): compare constructor identity at the SLOT's arity,
287
+ // dropping the witness's own element applications.
288
+ if (inner.tag === 'TCon' && !(0, types_1.parseKvName)(inner.name)
289
+ && inner.name === ret.name && inner.args.length < ret.args.length) {
290
+ return unify(inner, (0, types_1.tCon)(ret.name, ret.args.slice(0, inner.args.length)), depth + 1);
291
+ }
292
+ }
293
+ return unify(inner, ret, depth + 1);
294
+ }
295
+ // ---------------------------------------------------------------------------
296
+ // label ↔ row bridge (Phase B)
297
+ //
298
+ // `{[i]::a}` (a pure *var-label* record) and `{...a}` (a pure *open row*)
299
+ // are two spellings of "the same arbitrary sub-object". Structurally they
300
+ // differ — the former carries a `labelFields` group whose *value* is a
301
+ // value-type var, the latter a `rest` row var — so HM unification can't see
302
+ // them as equal on its own. When such a label record meets a row-bearing
303
+ // record / `Merge` marker / another label record, we reinterpret each
304
+ // `[lbl]::val` group as an *open row* (`{...val}`): the group's value-var is
305
+ // bound to a fresh row and the record is rewritten in row form (single group
306
+ // ⇒ `{...val}`, multiple groups ⇒ `Merge[{...v1},{...v2}]` collapsed to bare
307
+ // rows). This bridge fires ONLY in abstract record position (the other side
308
+ // is a pure open row, a `Merge` of rows, or another pure-var-label record) —
309
+ // never against a concrete-field record, where the historical
310
+ // `matchLabelFields` concrete-key expansion (deepMerge / label polymorphism)
311
+ // must be preserved.
312
+ // ---------------------------------------------------------------------------
313
+ /** Well-known structural members exposed intrinsically by a concrete builtin
314
+ * container. Used so a concrete value (e.g. an Array) can unify with a record
315
+ * that requires only members the container always provides (e.g. `length`).
316
+ * Returns null for types with no such intrinsic record-shaped members. */
317
+ function builtinStructuralMembers(tconName) {
318
+ switch (tconName) {
319
+ case types_1.T_SPREAD_ARRAY:
320
+ case types_1.T_ARRAY:
321
+ case 'Array':
322
+ case 'String':
323
+ return { length: (0, types_1.tCon)('Number') };
324
+ default:
325
+ return null;
326
+ }
327
+ }
328
+ /** A record written purely as one-or-more `[varLabel]::value` groups, with no
329
+ * concrete fields, no row tail, and not a strict `{}`. */
330
+ function isPureVarLabelRecord(r) {
331
+ if (r.tag !== 'TRecord')
332
+ return false;
333
+ if (r.strictEmpty)
334
+ return false;
335
+ if (r.rest)
336
+ return false;
337
+ if (Object.keys(r.fields).length > 0)
338
+ return false;
339
+ if (!r.labelFields || r.labelFields.length === 0)
340
+ return false;
341
+ return r.labelFields.every((lf) => lf.label.tag === 'TLabel' && lf.label.kind === 'var');
342
+ }
343
+ /** A record written as a pure open row `{...x}` — a single row tail with no
344
+ * concrete fields and no label groups. */
345
+ function isPureOpenRow(r) {
346
+ if (r.tag !== 'TRecord')
347
+ return false;
348
+ if (r.strictEmpty)
349
+ return false;
350
+ if (!r.rest)
351
+ return false;
352
+ if (Object.keys(r.fields).length > 0)
353
+ return false;
354
+ if (r.labelFields && r.labelFields.length > 0)
355
+ return false;
356
+ return true;
357
+ }
358
+ /** True when `other` is an abstract record position the label↔row bridge may
359
+ * unify against: a pure open row, another pure-var-label record, or a
360
+ * `Merge` marker. */
361
+ function isRowishForBridge(other) {
362
+ if (isPureOpenRow(other) || isPureVarLabelRecord(other))
363
+ return true;
364
+ if (other.tag === 'TCon' && other.name === types_1.T_MERGE)
365
+ return true;
366
+ return false;
367
+ }
368
+ /**
369
+ * Reinterpret a pure-var-label record as its row form. Returns the rewritten
370
+ * type plus a substitution binding each group's value-var to the fresh row
371
+ * that now stands in for it.
372
+ * `{[i]::a}` → `{...rowA}` with a := rowA
373
+ * `{[j]::a,[i]::b}` → `Merge[rowA, rowB]` with a := rowA, b := rowB
374
+ */
375
+ function toRowForm(r) {
376
+ const pre = new substitution_1.Substitution();
377
+ const rows = [];
378
+ for (const lf of r.labelFields ?? []) {
379
+ const vt = lf.type;
380
+ if (vt.tag === 'TVar') {
381
+ const row = (0, types_1.tRow)(vt.name);
382
+ pre.set(vt.id, row);
383
+ rows.push(row);
384
+ }
385
+ else if (vt.tag === 'TRow') {
386
+ rows.push(vt);
387
+ }
388
+ else {
389
+ // Non-var value (already concrete / structured): stand in a fresh row
390
+ // so the group still reads as an arbitrary sub-object.
391
+ rows.push((0, types_1.tRow)());
392
+ }
393
+ }
394
+ if (rows.length === 1) {
395
+ return { rowForm: { tag: 'TRecord', fields: {}, rest: rows[0] }, pre };
396
+ }
397
+ return { rowForm: (0, types_1.tCon)(types_1.T_MERGE, rows), pre };
398
+ }
399
+ // ---------------------------------------------------------------------------
400
+ // merge-shape acceptance (object-system robustness decision)
401
+ //
402
+ // A *merge-shape* return type — `{ ...a, ...b }` (a `Merge` marker), a pure
403
+ // open row `{ ...a }`, a pure var-label record `{ [k] :: a }`, or a
404
+ // `mergeRow`-flagged record — describes "some record built from the inputs";
405
+ // its exact shape is not determinable from the signature alone. The system
406
+ // treats it as satisfied by ANY record-ish body (`obj1`, `{...obj1}`, `{}`, a
407
+ // concrete record, …) — never poisoning the parameter rows/labels — while a
408
+ // non-record body (Number, String, Array, …) still reports a mismatch.
409
+ // ---------------------------------------------------------------------------
410
+ /** A "merge-shape" record form (see header). A mixed concrete+open record
411
+ * (`{ x :: Number, ...a }`) is deliberately NOT a merge-shape, so it keeps
412
+ * strict structural checking. */
413
+ function isMergeShape(t) {
414
+ if (t.tag === 'TCon' && t.name === types_1.T_MERGE)
415
+ return true;
416
+ if (t.tag === 'TRecord') {
417
+ if (t.mergeRow)
418
+ return true;
419
+ if (isPureOpenRow(t) || isPureVarLabelRecord(t))
420
+ return true;
421
+ }
422
+ return false;
423
+ }
424
+ /** "Record-ish": a value whose runtime form is an object/record in any
425
+ * encoding — a record (open/closed/label), a `Merge` marker, the `$error`
426
+ * sentinel, or a still-flexible type/row variable. Non-records (Number,
427
+ * String, Array, Boolean, function, …) are excluded. */
428
+ function isRecordIsh(t) {
429
+ if (t.tag === 'TRecord')
430
+ return true;
431
+ if (t.tag === 'TVar' || t.tag === 'TRow')
432
+ return true;
433
+ if (t.tag === 'TCon' && (t.name === types_1.T_MERGE || t.name === types_1.T_ERROR))
434
+ return true;
435
+ return false;
436
+ }
437
+ /** The decision predicate: a merge-shape on one side accepts a record-ish
438
+ * value on the other. Applied as a fallback when normal unification fails. */
439
+ function mergeShapeAccepts(a, b) {
440
+ return (isMergeShape(a) && isRecordIsh(b)) || (isMergeShape(b) && isRecordIsh(a));
441
+ }
442
+ let aliasExpander = null;
443
+ /** Run `f` with `expander` as the alias expander of unify (restored
444
+ * afterwards, so nested engines for imports keep their own). */
445
+ function withAliasExpander(expander, f) {
446
+ const previous = aliasExpander;
447
+ aliasExpander = expander;
448
+ try {
449
+ return f();
450
+ }
451
+ finally {
452
+ aliasExpander = previous;
453
+ }
454
+ }
455
+ /** The body of a bare alias name, or null. */
456
+ function expandedAliasName(t) {
457
+ if (!aliasExpander || t.tag !== 'TCon' || t.args.length !== 0)
458
+ return null;
459
+ const expanded = aliasExpander(t);
460
+ return expanded === t ? null : expanded;
461
+ }
462
+ function unify(t1, t2, _depth = 0) {
463
+ try {
464
+ return unifyCore(t1, t2, _depth);
465
+ }
466
+ catch (e) {
467
+ if (e instanceof UnificationError && mergeShapeAccepts(t1, t2)) {
468
+ return new substitution_1.Substitution();
469
+ }
470
+ // A bare alias name that unify met unexpanded: the recursive reference
471
+ // inside a recursive alias (`Node :: String | … | [Node]`, kept as a
472
+ // name to break the cycle), or a name inside another module's type.
473
+ // Expand it once and retry. Only on the failure path, so a successful
474
+ // unification costs nothing extra.
475
+ if (e instanceof UnificationError && !(t1.tag === 'TCon' && t2.tag === 'TCon' && t1.name === t2.name)) {
476
+ const e1 = expandedAliasName(t1);
477
+ const e2 = e1 ? null : expandedAliasName(t2);
478
+ if (e1 || e2)
479
+ return unify(e1 ?? t1, e2 ?? t2, _depth + 1);
480
+ }
481
+ throw e;
482
+ }
483
+ }
484
+ /**
485
+ * Unify two types, producing a substitution that makes them equal.
486
+ */
487
+ function unifyCore(t1, t2, _depth = 0) {
488
+ if (_depth > MAX_DEPTH) {
489
+ throw new UnificationError(t1, t2, `Unification exceeded maximum depth (${MAX_DEPTH})`);
490
+ }
491
+ // Wildcard type ('*' or named '*:name') unifies with anything.
492
+ if ((0, types_1.isWildcard)(t1))
493
+ return unifyFlexible(t1, t2);
494
+ if ((0, types_1.isWildcard)(t2))
495
+ return unifyFlexible(t2, t1);
496
+ // Any (top type) — unifies with everything like wildcard, but unlike
497
+ // wildcard it is a concrete named type that survives in inference output.
498
+ if ((0, types_1.isAnyType)(t1))
499
+ return unifyFlexible(t1, t2);
500
+ if ((0, types_1.isAnyType)(t2))
501
+ return unifyFlexible(t2, t1);
502
+ // Union type: unify succeeds if the other type matches ANY member
503
+ if ((0, types_1.isUnion)(t1) && t2.tag !== 'TVar') {
504
+ return unifyWithUnion(t1.args, t2, _depth + 1, t1.tag === 'TCon' && !!t1.overloadSet);
505
+ }
506
+ if ((0, types_1.isUnion)(t2) && t1.tag !== 'TVar') {
507
+ return unifyWithUnion(t2.args, t1, _depth + 1, t2.tag === 'TCon' && !!t2.overloadSet);
508
+ }
509
+ // Both are the same variable
510
+ if (t1.tag === 'TVar' && t2.tag === 'TVar' && t1.id === t2.id) {
511
+ return new substitution_1.Substitution();
512
+ }
513
+ // Row variables live in a separate sort (W2 disjoint TRow refactor).
514
+ // Same row-var is trivially equal; row-vs-row binds; row-vs-record
515
+ // captures the record's fields into the row binding (handled by
516
+ // bindRow, which delegates to the existing TRecord splice logic in
517
+ // Substitution.apply). Row-vs-TVar is treated as ordinary TVar
518
+ // binding (the TVar absorbs the row sort) — keeps backward compat
519
+ // while sites still allocate TVars in row position.
520
+ if (t1.tag === 'TRow' && t2.tag === 'TRow') {
521
+ if (t1.id === t2.id)
522
+ return new substitution_1.Substitution();
523
+ return substitution_1.Substitution.singleton(t1.id, t2);
524
+ }
525
+ if (t1.tag === 'TRow') {
526
+ if (occursIn(t1.id, t2)) {
527
+ throw new UnificationError(t1, t2, `Infinite row: ${t1.name} ~ ${(0, types_1.typeToString)(t2)}`);
528
+ }
529
+ return substitution_1.Substitution.singleton(t1.id, t2);
530
+ }
531
+ if (t2.tag === 'TRow') {
532
+ if (occursIn(t2.id, t1)) {
533
+ throw new UnificationError(t1, t2, `Infinite row: ${t2.name} ~ ${(0, types_1.typeToString)(t1)}`);
534
+ }
535
+ return substitution_1.Substitution.singleton(t2.id, t1);
536
+ }
537
+ // Label unification — labels live in their own sort. Same-id vars
538
+ // are trivially equal; lit-vs-lit checks string equality; var-vs-anything
539
+ // (including a non-label type — handled further down by the catch-all)
540
+ // binds. We do NOT throw for TLabel-vs-non-TLabel here, because TVars
541
+ // must still be allowed to absorb a TLabel (so a generic `a` can be
542
+ // bound to a label inside e.g. `(a, b) -> a`).
543
+ if (t1.tag === 'TLabel' && t2.tag === 'TLabel') {
544
+ if (t1.kind === 'var' && t2.kind === 'var' && t1.id === t2.id) {
545
+ return new substitution_1.Substitution();
546
+ }
547
+ if (t1.kind === 'lit' && t2.kind === 'lit') {
548
+ if (t1.value === t2.value)
549
+ return new substitution_1.Substitution();
550
+ throw new UnificationError(t1, t2, `Cannot unify label literals '${t1.value}' and '${t2.value}'`);
551
+ }
552
+ if (t1.kind === 'var')
553
+ return substitution_1.Substitution.singleton(t1.id, t2);
554
+ return substitution_1.Substitution.singleton(t2.id, t1);
555
+ }
556
+ // Both are type variables with different IDs — prefer keeping the one
557
+ // with a user-supplied annotation name (single letter like 'a', 'r')
558
+ // so that annotation names survive through substitution chains.
559
+ // When both have annotation names, keep the one with the lower ID
560
+ // (created earlier — typically the callback parameter rather than
561
+ // a constructor/factory parameter introduced during body inference).
562
+ if (t1.tag === 'TVar' && t2.tag === 'TVar') {
563
+ const t1HasAnnotName = types_1.ANNOTATION_NAME_RE.test(t1.name);
564
+ const t2HasAnnotName = types_1.ANNOTATION_NAME_RE.test(t2.name);
565
+ if (t1HasAnnotName && !t2HasAnnotName) {
566
+ return substitution_1.Substitution.singleton(t2.id, t1);
567
+ }
568
+ if (t2HasAnnotName && !t1HasAnnotName) {
569
+ return substitution_1.Substitution.singleton(t1.id, t2);
570
+ }
571
+ // Both have annotation names or neither does — keep the lower ID
572
+ // (earlier-created variable, typically the binding-site variable).
573
+ if (t1.id < t2.id) {
574
+ return substitution_1.Substitution.singleton(t2.id, t1);
575
+ }
576
+ return substitution_1.Substitution.singleton(t1.id, t2);
577
+ }
578
+ // t1 is a variable — bind it
579
+ if (t1.tag === 'TVar')
580
+ return bindVar(t1, t2, t1, t2);
581
+ // t2 is a variable — bind it
582
+ if (t2.tag === 'TVar')
583
+ return bindVar(t2, t1, t1, t2);
584
+ // Nested universal quantifiers (rank-N annotations).
585
+ if (t1.tag === 'TForall' || t2.tag === 'TForall') {
586
+ if (t1.tag === 'TForall' && t2.tag === 'TForall') {
587
+ if (t1 === t2 || (0, types_1.structuralEquals)(t1, t2))
588
+ return new substitution_1.Substitution();
589
+ if (t1.vars.length === t2.vars.length) {
590
+ // Alpha-rename t2's binders onto t1's, then unify the bodies. The
591
+ // shared binders must come out UNBOUND — a binding would mean one
592
+ // side is less polymorphic than the other.
593
+ const rename = new substitution_1.Substitution();
594
+ for (let i = 0; i < t2.vars.length; i++) {
595
+ rename.set(t2.vars[i], { tag: 'TVar', id: t1.vars[i], name: t1.varNames[i] ?? `t${t1.vars[i]}` });
596
+ }
597
+ const s = unify(t1.body, rename.apply(t2.body), _depth + 1);
598
+ for (const v of t1.vars) {
599
+ if (s.lookup(v) !== undefined) {
600
+ throw new UnificationError(t1, t2, 'Polymorphic type is not general enough');
601
+ }
602
+ }
603
+ return s;
604
+ }
605
+ throw new UnificationError(t1, t2, 'Cannot unify forall types quantifying different numbers of variables');
606
+ }
607
+ // TForall vs a non-forall type: graceful degradation — instantiate the
608
+ // quantifier with fresh flexible vars and unify rank-1 style. The strict
609
+ // rank-N check happens at call sites (subsumption) before unify runs.
610
+ const f = t1.tag === 'TForall' ? t1 : t2;
611
+ const other = t1.tag === 'TForall' ? t2 : t1;
612
+ return unify(instantiateForallBody(f), other, _depth + 1);
613
+ }
614
+ // After TVar binding has been considered, a remaining label-vs-non-label
615
+ // mismatch is usually a hard error. But labels are *runtime strings*, so
616
+ // a TLabel may be used wherever a `String` is expected (and vice versa) —
617
+ // e.g. `if (key === k) ...` inside a label-polymorphic function body.
618
+ // We allow that compatibility silently (no binding); other type pairings
619
+ // (e.g. `Number` vs `TLabel`) remain errors.
620
+ if (t1.tag === 'TLabel' || t2.tag === 'TLabel') {
621
+ const other = t1.tag === 'TLabel' ? t2 : t1;
622
+ if (other.tag === 'TCon' && other.name === 'String' && other.args.length === 0) {
623
+ return new substitution_1.Substitution();
624
+ }
625
+ throw new UnificationError(t1, t2, 'Label vs non-label');
626
+ }
627
+ // Both are function types
628
+ if (t1.tag === 'TFun' && t2.tag === 'TFun') {
629
+ // Spread arrow chain: `a -> b -> ... -> z` absorbs a variable number of
630
+ // *middle* curried parameters when unified against a concrete curried
631
+ // function. Handle the whole chain at once before the generic
632
+ // param/result recursion (which would mismatch `... -> z` against a
633
+ // non-function remainder).
634
+ //
635
+ // Only route here for a GENUINE top-level spread chain — one whose leading
636
+ // params are all simple (no higher-order param before the spread). A type
637
+ // like `(a -> b -> ... -> z) -> (a -> b -> ... -> z)` (e.g. `memoizeCurried`)
638
+ // carries the spread nested inside its function-typed parameter/result; it
639
+ // is a plain 1-arg function and must decompose STRUCTURALLY, otherwise
640
+ // `flattenCurriedType` would merge the callee's result chain into the
641
+ // parameter list and collapse the call result to the bare terminal `z`.
642
+ if ((0, typeUtils_1.hasTopLevelSpreadChain)(t1) || (0, typeUtils_1.hasTopLevelSpreadChain)(t2)) {
643
+ return unifySpreadArrowChain(t1, t2, _depth + 1);
644
+ }
645
+ const s1 = unify(t1.param, t2.param, _depth + 1);
646
+ const s2 = unify(s1.apply(t1.result), s1.apply(t2.result), _depth + 1);
647
+ return s2.compose(s1);
648
+ }
649
+ // Chain-container element collapse. A spread tuple/array whose non-spread
650
+ // elements are all arrows — `(a -> b, b -> c, ..., y -> z)` — represents a
651
+ // chained sequence of functions (how a container-wrapped chain
652
+ // `f (a->b, ..., y->z)` stores its element type). When such a chain meets a
653
+ // SINGLE arrow (e.g. the element expectation of a fold/reduce whose reducer
654
+ // applies each element to an accumulator), collapse the chain to its overall
655
+ // composed arrow `first.param -> last.result` and unify that. This makes a
656
+ // container-wrapped chain fold like the bare spread-array form instead of
657
+ // failing to match the reducer's element type.
658
+ {
659
+ const chainSide = (0, typeUtils_1.isArrowChainTuple)(t1) ? t1 : (0, typeUtils_1.isArrowChainTuple)(t2) ? t2 : null;
660
+ const arrowSide = t1.tag === 'TFun' ? t1 : t2.tag === 'TFun' ? t2 : null;
661
+ if (chainSide && arrowSide) {
662
+ const collapsed = (0, typeUtils_1.collapseArrowChainTuple)(chainSide);
663
+ if (collapsed)
664
+ return unify(collapsed, arrowSide, _depth + 1);
665
+ }
666
+ }
667
+ // Function (TCon) matches any function type (TFun)
668
+ if ((t1.tag === 'TFun' && t2.tag === 'TCon' && t2.name === 'Function' && t2.args.length === 0) ||
669
+ (t2.tag === 'TFun' && t1.tag === 'TCon' && t1.name === 'Function' && t1.args.length === 0)) {
670
+ return new substitution_1.Substitution();
671
+ }
672
+ // Applied `Function [params] result` is sugar for a `TFun`. Desugar so it
673
+ // unifies structurally with a real `TFun` *and* with another applied
674
+ // `Function` (possibly spelled at a different arity, e.g. the curried
675
+ // `Function [x] (Function [y] a)` vs the tupled `Function [x, y] a`).
676
+ if ((0, types_1.isAppliedFunction)(t1) && (t2.tag === 'TFun' || (0, types_1.isAppliedFunction)(t2))) {
677
+ const d1 = (0, types_1.desugarFunctionType)(t1.args[0], t1.args[1]);
678
+ const d2 = (0, types_1.isAppliedFunction)(t2) ? (0, types_1.desugarFunctionType)(t2.args[0], t2.args[1]) : t2;
679
+ return unify(d1, d2, _depth + 1);
680
+ }
681
+ if ((0, types_1.isAppliedFunction)(t2) && t1.tag === 'TFun') {
682
+ return unify(t1, (0, types_1.desugarFunctionType)(t2.args[0], t2.args[1]), _depth + 1);
683
+ }
684
+ // A kind variable applied to one argument (`f a`, e.g. `Functor f => f a`)
685
+ // accepts a one-parameter function value: `f := Function [x]`, the reader
686
+ // functor (`x -> a` is `Function [x] a`). Whether `Function` satisfies the
687
+ // constraint is decided at discharge (`::rep Functor Function#map`).
688
+ {
689
+ const funSide = t1.tag === 'TFun' ? t1 : t2.tag === 'TFun' ? t2 : null;
690
+ const kvSide = !funSide ? null : t1.tag === 'TCon' ? t1 : t2.tag === 'TCon' ? t2 : null;
691
+ const kv = kvSide && kvSide.args.length === 1 ? (0, types_1.parseKvName)(kvSide.name) : null;
692
+ if (kv && funSide
693
+ && !(funSide.param.tag === 'TCon' && (funSide.param.name === types_1.T_TUPLE || funSide.param.name === 'Void'))
694
+ && !occursIn(kv.varId, funSide)
695
+ // Not a variadic chain (`m x -> m y -> ... -> m z` stands for its
696
+ // terminal), and not a function that mentions the kind variable
697
+ // itself (`m x -> …`): binding `m` to it would be circular.
698
+ && !(0, typeUtils_1.hasSpreadInArrowChain)(funSide)
699
+ && !mentionsKindVar(funSide, kv.varId)) {
700
+ const fBinding = substitution_1.Substitution.singleton(kv.varId, (0, types_1.tCon)(types_1.T_FUNCTION, [(0, types_1.tCon)(types_1.T_ARRAY, [funSide.param])]));
701
+ const s2 = unify(fBinding.apply(kvSide.args[0]), fBinding.apply(funSide.result), _depth + 1);
702
+ return s2.compose(fBinding);
703
+ }
704
+ }
705
+ // A kind variable applied to TWO arguments (`p b c`, e.g.
706
+ // `Profunctor p => p b c`) accepts a one-parameter function value:
707
+ // `p := Function`, with `p b c` ≡ `b -> c` — the binary counterpart of the
708
+ // reader functor above. `Substitution.apply` renders the application as
709
+ // `Function [b] c`; whether `Function` satisfies the constraint is decided
710
+ // at discharge (`::rep Profunctor Function#promap`). An applied
711
+ // `Function [x] y` on the other side is read through its desugared arrow,
712
+ // so its parameter list never lands in the `b` slot.
713
+ {
714
+ const asFun = (t) => t.tag === 'TFun' ? t : (0, types_1.isAppliedFunction)(t) ? (0, types_1.desugarFunctionType)(t.args[0], t.args[1]) : null;
715
+ const f1 = t1.tag === 'TCon' && t1.args.length === 2 && (0, types_1.parseKvName)(t1.name) ? null : asFun(t1);
716
+ const f2 = f1 ? null : t2.tag === 'TCon' && t2.args.length === 2 && (0, types_1.parseKvName)(t2.name) ? null : asFun(t2);
717
+ const funSide = f1 ?? f2;
718
+ const kvSide = f1 ? t2 : t1;
719
+ const kv = funSide && funSide.tag === 'TFun' && kvSide.tag === 'TCon' && kvSide.args.length === 2
720
+ ? (0, types_1.parseKvName)(kvSide.name) : null;
721
+ if (kv && funSide && funSide.tag === 'TFun' && kvSide.tag === 'TCon'
722
+ && !(funSide.param.tag === 'TCon' && (funSide.param.name === types_1.T_TUPLE || funSide.param.name === 'Void'))
723
+ && !occursIn(kv.varId, funSide)
724
+ && !(0, typeUtils_1.hasSpreadInArrowChain)(funSide)
725
+ && !mentionsKindVar(funSide, kv.varId)) {
726
+ const pBinding = substitution_1.Substitution.singleton(kv.varId, (0, types_1.tCon)(types_1.T_FUNCTION, []));
727
+ const s1 = unify(pBinding.apply(kvSide.args[0]), pBinding.apply(funSide.param), _depth + 1).compose(pBinding);
728
+ const s2 = unify(s1.apply(kvSide.args[1]), s1.apply(funSide.result), _depth + 1);
729
+ return s2.compose(s1);
730
+ }
731
+ }
732
+ // TypeRep coercion: TypeRep m can unify with a constructor function
733
+ // (e.g. a -> Identity a) by extracting the return type's constructor.
734
+ if (t1.tag === 'TCon' && t1.name === types_1.T_TYPEREP && t1.args.length === 1 && t2.tag === 'TFun') {
735
+ return unifyTypeRep(t1, t2, _depth);
736
+ }
737
+ if (t2.tag === 'TCon' && t2.name === types_1.T_TYPEREP && t2.args.length === 1 && t1.tag === 'TFun') {
738
+ return unifyTypeRep(t2, t1, _depth);
739
+ }
740
+ // TypeRep(f) vs TypeRep($kv:f [args]) — a bare functor-kind var (on the
741
+ // *actual* side) meeting a kv-*application* (on the *expected*/annotated
742
+ // side). A TypeRep denotes a type *constructor*, so both sides refer to
743
+ // the same constructor `f`; the trailing application args (produced by the
744
+ // `of :: TypeRep f -> a -> f a` param fixup) are spurious for TypeRep
745
+ // identity. Bind the actual bare var to the *unapplied* constructor so a
746
+ // later `f b` stays a single-arg `f b` instead of collapsing to the
747
+ // ill-kinded `f a b`. Direction matters: the reverse case (an applied
748
+ // *actual* `TypeRep (m a)` binding a bare *param* `m`, as in
749
+ // `empty :: Monoid m => TypeRep m -> m` under an applied `Monoid (m a)`
750
+ // constraint) must keep the application so `empty(M)` yields `m a` — that
751
+ // falls through to the generic path below.
752
+ if (t1.tag === 'TCon' && t1.name === types_1.T_TYPEREP && t1.args.length === 1 &&
753
+ t2.tag === 'TCon' && t2.name === types_1.T_TYPEREP && t2.args.length === 1) {
754
+ const a1 = t1.args[0];
755
+ const a2 = t2.args[0];
756
+ if (a1.tag === 'TVar' && a2.tag === 'TCon' && a2.args.length > 0 && (0, types_1.parseKvName)(a2.name)) {
757
+ return substitution_1.Substitution.singleton(a1.id, (0, types_1.tCon)(a2.name, []));
758
+ }
759
+ // `TypeRep (f x…)` (a kv application, typically from the `of` param
760
+ // fixup) meeting `TypeRep (T y…)` where `T y…` is UNDER-saturated — a
761
+ // constructor still missing arguments (`StateT Id s` of `StateT m s a`,
762
+ // i.e. a monad-transformer instance). The witness IS that constructor:
763
+ // bind `f := T y…` and drop the phantom `x…`. The generic kv path would
764
+ // absorb a real parameter as the element (`f := StateT Id`, `x := s`).
765
+ for (const [kvSideArg, otherArg] of [[a1, a2], [a2, a1]]) {
766
+ if (kvSideArg.tag !== 'TCon' || otherArg.tag !== 'TCon')
767
+ continue;
768
+ const kv = (0, types_1.parseKvName)(kvSideArg.name);
769
+ if (!kv || kvSideArg.args.length === 0 || (0, types_1.parseKvName)(otherArg.name))
770
+ continue;
771
+ const full = (0, dataTypeRegistry_1.getDataType)(otherArg.name)?.decl.typeVars.length ?? (0, methodRegistry_1.getTypeArity)(otherArg.name);
772
+ if (full > 0 && otherArg.args.length < full) {
773
+ if (occursIn(kv.varId, otherArg))
774
+ throw new UnificationError(t1, t2, 'Infinite type');
775
+ return substitution_1.Substitution.singleton(kv.varId, otherArg);
776
+ }
777
+ }
778
+ // Both sides are kind-variable constructors at *differing* arity, e.g.
779
+ // `TypeRep f` (a bare kv head, 0 args) meeting `TypeRep (f a)` (an applied
780
+ // kv head). This arises when a shared `TypeRep f` binding (`A`) is passed
781
+ // to several `of :: TypeRep f -> a -> f a` calls with different value
782
+ // types: the first call's param-fixup binds `A`'s var to the *unapplied*
783
+ // constructor, so the next call meets `TypeRep g1` vs `TypeRep (g2 a)`.
784
+ // Since a TypeRep names a *constructor*, the trailing application args are
785
+ // phantom for identity — collapse the more-applied head onto the less-
786
+ // applied one (dropping the phantom args) instead of failing the generic
787
+ // kv arity check.
788
+ if (a1.tag === 'TCon' && a2.tag === 'TCon') {
789
+ const kv1 = (0, types_1.parseKvName)(a1.name);
790
+ const kv2 = (0, types_1.parseKvName)(a2.name);
791
+ if (kv1 && kv2 && a1.args.length !== a2.args.length) {
792
+ if (kv1.varId === kv2.varId)
793
+ return new substitution_1.Substitution();
794
+ const [fewer, moreKv] = a1.args.length < a2.args.length
795
+ ? [a1, kv2] : [a2, kv1];
796
+ return substitution_1.Substitution.singleton(moreKv.varId, (0, types_1.tCon)(fewer.name, []));
797
+ }
798
+ }
799
+ }
800
+ // Both are constructed types
801
+ if (t1.tag === 'TCon' && t2.tag === 'TCon') {
802
+ // Strict-empty array (`[]` in an annotation) enforcement — the array
803
+ // analogue of the strict-empty record rule below. A strict-empty array
804
+ // accepts only another empty array: either another strict-empty array, or
805
+ // an empty array *literal* whose element variable is an unbound
806
+ // `emptyArray` TVar. An array with a concrete element type is rejected.
807
+ if (t1.name === types_1.T_ARRAY && t2.name === types_1.T_ARRAY &&
808
+ t1.args.length === 1 && t2.args.length === 1 &&
809
+ (t1.strictEmpty === true || t2.strictEmpty === true)) {
810
+ const acceptsEmpty = (other) => {
811
+ if (other.strictEmpty === true)
812
+ return true;
813
+ const el = other.args[0];
814
+ return el.tag === 'TVar' && el.emptyArray === true;
815
+ };
816
+ const ok = t1.strictEmpty === true
817
+ ? acceptsEmpty(t2)
818
+ : acceptsEmpty(t1);
819
+ if (!ok)
820
+ throw new UnificationError(t1, t2);
821
+ // Both sides are empty — unify the (fresh) element vars harmlessly.
822
+ return unifyArgs(t1.args, t2.args, new substitution_1.Substitution(), _depth + 1);
823
+ }
824
+ const kv1 = (0, types_1.parseKvName)(t1.name);
825
+ const kv2 = (0, types_1.parseKvName)(t2.name);
826
+ // Kind variable vs concrete constructor: bind the kv to the concrete name.
827
+ if (kv1 && !kv2)
828
+ return unifyKvConcrete(t1, kv1, t2, t1, t2, _depth + 1);
829
+ if (!kv1 && kv2)
830
+ return unifyKvConcrete(t2, kv2, t1, t1, t2, _depth + 1);
831
+ if (kv1 && kv2) {
832
+ if (t1.args.length !== t2.args.length) {
833
+ throw new UnificationError(t1, t2);
834
+ }
835
+ if (kv1.varId === kv2.varId) {
836
+ // Same kind variable — just unify args
837
+ return unifyArgs(t1.args, t2.args, new substitution_1.Substitution(), _depth + 1);
838
+ }
839
+ // Different kind vars — bind one to the other
840
+ return unifyArgs(t1.args, t2.args, substitution_1.Substitution.singleton(kv1.varId, (0, types_1.tCon)(t2.name, [])), _depth + 1);
841
+ }
842
+ // Numeric subtype compatibility with directional widening.
843
+ // Convention: t1 = inferred/actual, t2 = expected/annotated.
844
+ // Widening (Integer → Double) is OK; narrowing (Double → Integer) is not.
845
+ // Number ↔ any subtype is always allowed (JS has a single number type).
846
+ if ((0, types_1.isNumericType)(t1) && (0, types_1.isNumericType)(t2)) {
847
+ if (t1.name === t2.name)
848
+ return new substitution_1.Substitution();
849
+ if (t1.name === 'Number' || t2.name === 'Number')
850
+ return new substitution_1.Substitution();
851
+ if ((0, types_1.isNumericSubtypeOf)(t1.name, t2.name))
852
+ return new substitution_1.Substitution();
853
+ // Narrowing or incompatible subtypes — fall through to throw UnificationError
854
+ }
855
+ // A fixed-length tuple flows into `[Any]`: `Any` absorbs every element,
856
+ // so a tuple can be handed to an untyped array helper (and back).
857
+ {
858
+ const isTupleLike = (t) => t.tag === 'TCon' && (t.name === types_1.T_TUPLE || t.name === types_1.T_SPREAD_ARRAY);
859
+ const isAnyArray = (t) => t.tag === 'TCon' && t.name === types_1.T_ARRAY && t.args.length === 1 && (0, types_1.isAnyType)(t.args[0]);
860
+ if ((isTupleLike(t1) && isAnyArray(t2)) || (isAnyArray(t1) && isTupleLike(t2))) {
861
+ return new substitution_1.Substitution();
862
+ }
863
+ }
864
+ // A positional list `[a, b]` (no `...`) meets a list `[e]` when every
865
+ // element is an `e`: a
866
+ // positionally destructured value (`([home, away]) => …`) still accepts
867
+ // a real list, and a pair of the same type can be used as a list.
868
+ {
869
+ const isPlainTuple = (t) => t.tag === 'TCon' && t.name === types_1.T_SPREAD_ARRAY && t.args.length > 0
870
+ && !t.args.some(a => (0, types_1.isSpread)(a));
871
+ const isList = (t) => t.tag === 'TCon' && t.name === types_1.T_ARRAY && t.args.length === 1;
872
+ if ((isPlainTuple(t1) && isList(t2)) || (isList(t1) && isPlainTuple(t2))) {
873
+ const tuple = (isPlainTuple(t1) ? t1 : t2);
874
+ const elem = (isList(t1) ? t1 : t2);
875
+ return unifyArgs(tuple.args, tuple.args.map(() => elem.args[0]), new substitution_1.Substitution(), _depth + 1);
876
+ }
877
+ }
878
+ // A BARE parameterised constructor (`First`, registered arity > 0) only
879
+ // arises from a `TypeRep m` witness, which binds `m` to the constructor
880
+ // itself (`a -> First a` ⊢ `TypeRep First`). When such an `m` is then
881
+ // used in a value slot (`leftIdentity :: TypeRep m -> m -> Boolean`), it
882
+ // stands for an application of that constructor: `First` ≈ `First String`.
883
+ if (t1.name === t2.name && (t1.args.length === 0) !== (t2.args.length === 0)
884
+ && !(0, types_1.parseKvName)(t1.name) && !isInternalTypeName(t1.name)) {
885
+ const full = (0, dataTypeRegistry_1.getDataType)(t1.name)?.decl.typeVars.length ?? (0, methodRegistry_1.getTypeArity)(t1.name);
886
+ const applied = t1.args.length === 0 ? t2 : t1;
887
+ if (full > 0 && applied.args.length === full)
888
+ return new substitution_1.Substitution();
889
+ }
890
+ // Normal case: both are concrete constructors
891
+ if (t1.name !== t2.name || t1.args.length !== t2.args.length) {
892
+ // Spread-tuple unification: Tuple(a, b, ...) can unify with Tuple(X, Y, Z)
893
+ // The ... absorbs any number of elements in the middle.
894
+ if (t1.name === t2.name && (t1.name === types_1.T_TUPLE || t1.name === types_1.T_SPREAD_ARRAY)) {
895
+ const spread1 = t1.args.some(a => (0, types_1.isSpread)(a));
896
+ const spread2 = t2.args.some(a => (0, types_1.isSpread)(a));
897
+ if (spread1 || spread2) {
898
+ return unifySpreadTuple(t1.args, t2.args, t1, t2, _depth + 1);
899
+ }
900
+ }
901
+ // Specialised error message when the constructors share a name
902
+ // but disagree on arity — e.g. `Box a` vs `Box a b`. Internal
903
+ // synthetic names (Tuple, Union, SpreadArray, ...) keep the
904
+ // generic message because they're never user-visible.
905
+ if (t1.name === t2.name &&
906
+ t1.name !== types_1.T_TUPLE && t1.name !== types_1.T_UNION && t1.name !== types_1.T_SPREAD_ARRAY) {
907
+ throw new UnificationError(t1, t2, `Type constructor '${t1.name}' applied to ${t1.args.length} type argument${t1.args.length === 1 ? '' : 's'} ` +
908
+ `but ${t2.args.length} expected`);
909
+ }
910
+ throw new UnificationError(t1, t2);
911
+ }
912
+ // Check for spread tuples even when lengths match
913
+ if ((t1.name === types_1.T_TUPLE || t1.name === types_1.T_SPREAD_ARRAY) &&
914
+ (t1.args.some(a => (0, types_1.isSpread)(a)) || t2.args.some(a => (0, types_1.isSpread)(a)))) {
915
+ return unifySpreadTuple(t1.args, t2.args, t1, t2, _depth + 1);
916
+ }
917
+ return unifyArgs(t1.args, t2.args, new substitution_1.Substitution(), _depth + 1);
918
+ }
919
+ // Both are record types — unify field by field, with row-variable
920
+ // support for open records (`{ x :: a | r }`). Closed-vs-closed remains
921
+ // lenient on extras for back-compat: only the *common* keys are unified
922
+ // and surplus keys on either side are silently accepted. When at least
923
+ // one side is open, the row variable absorbs the surplus from the other
924
+ // side and (if the other side is also open) shares its row tail.
925
+ if (t1.tag === 'TRecord' && t2.tag === 'TRecord') {
926
+ // Nominal check: when BOTH records carry a (different) alias name,
927
+ // they originate from distinct named declarations (e.g.
928
+ // `LocationRow :: { … }` vs `ApplicationRow :: { … }`) and must
929
+ // not unify even if their fields happen to overlap. Without this,
930
+ // the lenient closed-vs-closed rule below would silently accept
931
+ // `QueryTag ApplicationRow` against `QueryTag LocationRow` because they
932
+ // share `id :: Number`, defeating the per-table relation
933
+ // restriction emitted by query-builder introspect. When only one side has
934
+ // an alias (or neither), keep the historical lenient behaviour so
935
+ // record literals can still match named record types.
936
+ if (t1.alias && t2.alias && t1.alias !== t2.alias) {
937
+ throw new UnificationError(t1, t2);
938
+ }
939
+ // label ↔ row bridge: a pure `[var]::value` record meeting a row-bearing
940
+ // (or another label) record is reinterpreted in row form so the two
941
+ // spellings of "an arbitrary sub-object" unify. Scoped to abstract
942
+ // record position — never fires against a concrete-field record, where
943
+ // `matchLabelFields` below performs the concrete-key expansion.
944
+ if (isPureVarLabelRecord(t1) && isRowishForBridge(t2)) {
945
+ const { rowForm, pre } = toRowForm(t1);
946
+ const s = unify(rowForm, pre.apply(t2), _depth + 1);
947
+ return s.compose(pre);
948
+ }
949
+ if (isPureVarLabelRecord(t2) && isRowishForBridge(t1)) {
950
+ const { rowForm, pre } = toRowForm(t2);
951
+ const s = unify(pre.apply(t1), rowForm, _depth + 1);
952
+ return s.compose(pre);
953
+ }
954
+ // A record written as a literal `{}` in an annotation (`strictEmpty`) is a
955
+ // strict, exactly-empty object. Unlike inferred empty object literals
956
+ // (which stay open/lenient so growing objects type-check), a strict `{}`
957
+ // must not absorb any concrete field, so unifying it with a record that
958
+ // carries concrete fields or label fields is an error.
959
+ const isStrictEmpty = (r) => r.strictEmpty === true &&
960
+ !r.rest &&
961
+ Object.keys(r.fields).length === 0 &&
962
+ (!r.labelFields || r.labelFields.length === 0);
963
+ const hasConcreteFields = (r) => Object.keys(r.fields).length > 0 ||
964
+ (r.labelFields != null && r.labelFields.length > 0);
965
+ if ((isStrictEmpty(t1) && hasConcreteFields(t2)) ||
966
+ (isStrictEmpty(t2) && hasConcreteFields(t1))) {
967
+ throw new UnificationError(t1, t2);
968
+ }
969
+ let subst = new substitution_1.Substitution();
970
+ const keys1 = Object.keys(t1.fields);
971
+ const keys2 = Object.keys(t2.fields);
972
+ const commonKeys = keys1.filter((k) => keys2.includes(k));
973
+ for (const k of commonKeys) {
974
+ const s = unify(subst.apply(t1.fields[k]), subst.apply(t2.fields[k]), _depth + 1);
975
+ subst = s.compose(subst);
976
+ }
977
+ const onlyIn1 = {};
978
+ const onlyIn2 = {};
979
+ for (const k of keys1)
980
+ if (!commonKeys.includes(k))
981
+ onlyIn1[k] = subst.apply(t1.fields[k]);
982
+ for (const k of keys2)
983
+ if (!commonKeys.includes(k))
984
+ onlyIn2[k] = subst.apply(t2.fields[k]);
985
+ // Label-keyed fields: bind each unresolved label var to a concrete
986
+ // field name from the *other* side and unify the value type. This
987
+ // handles e.g. `{ [k] :: a, ...r }` ↔ `{ x :: Number, y :: Number }`
988
+ // by picking up `x` for `k` (deterministic when only one candidate
989
+ // remains; first-fit otherwise — caller is expected to disambiguate
990
+ // by passing the label as an argument first).
991
+ const matchLabelFields = (labelFields, candidates) => {
992
+ if (!labelFields || labelFields.length === 0)
993
+ return;
994
+ for (const lf of labelFields) {
995
+ const lbl = subst.apply(lf.label);
996
+ if (lbl.tag !== 'TLabel')
997
+ continue;
998
+ if (lbl.kind === 'lit') {
999
+ // Migrate by direct key match against `candidates`.
1000
+ if (lbl.value in candidates) {
1001
+ const s = unify(subst.apply(lf.type), candidates[lbl.value], _depth + 1);
1002
+ subst = s.compose(subst);
1003
+ delete candidates[lbl.value];
1004
+ }
1005
+ continue;
1006
+ }
1007
+ // Label still a var → pick first remaining candidate, bind label.
1008
+ const remaining = Object.keys(candidates);
1009
+ if (remaining.length === 0)
1010
+ continue;
1011
+ const pickedKey = remaining[0];
1012
+ const s1 = unify(lbl, { tag: 'TLabel', kind: 'lit', value: pickedKey }, _depth + 1);
1013
+ subst = s1.compose(subst);
1014
+ const s2 = unify(subst.apply(lf.type), candidates[pickedKey], _depth + 1);
1015
+ subst = s2.compose(subst);
1016
+ delete candidates[pickedKey];
1017
+ }
1018
+ };
1019
+ matchLabelFields(t1.labelFields, onlyIn2);
1020
+ matchLabelFields(t2.labelFields, onlyIn1);
1021
+ const has1 = Object.keys(onlyIn1).length > 0;
1022
+ const has2 = Object.keys(onlyIn2).length > 0;
1023
+ // Closed-vs-closed: keep historical lenient behaviour (no error, no binding).
1024
+ if (!t1.rest && !t2.rest)
1025
+ return subst;
1026
+ // Helper: build a TRecord carrying `extras` and a (possibly fresh) row tail.
1027
+ const buildTail = (extras, sharedRest) => {
1028
+ const rec = { tag: 'TRecord', fields: extras };
1029
+ if (sharedRest)
1030
+ rec.rest = sharedRest;
1031
+ return rec;
1032
+ };
1033
+ // 1) t1 open, t2 open: link the two rows through a fresh shared row.
1034
+ // r1 := { onlyIn2 | rShared }, r2 := { onlyIn1 | rShared }.
1035
+ if (t1.rest && t2.rest) {
1036
+ // Special case: identical row vars and no surplus → already unified.
1037
+ if (t1.rest.id === t2.rest.id && !has1 && !has2)
1038
+ return subst;
1039
+ // No surplus on either side: link the two row variables DIRECTLY rather
1040
+ // than wrapping each in a fresh `{ rShared }` record. The wrapper would
1041
+ // rebind a named row (`{...a}`) to an anonymous shared row, so hovers on
1042
+ // a parameter typed `{...a}` would collapse to `{ r16 }`. A direct
1043
+ // row-var unification keeps the surviving name (`{ a }`).
1044
+ if (!has1 && !has2) {
1045
+ const s = unify(subst.apply(t1.rest), subst.apply(t2.rest), _depth + 1);
1046
+ return s.compose(subst);
1047
+ }
1048
+ const rShared = (0, types_1.tRow)();
1049
+ const r1Bind = buildTail(onlyIn2, rShared);
1050
+ const r2Bind = buildTail(onlyIn1, rShared);
1051
+ const s1 = unify(subst.apply(t1.rest), r1Bind, _depth + 1);
1052
+ subst = s1.compose(subst);
1053
+ const s2 = unify(subst.apply(t2.rest), subst.apply(r2Bind), _depth + 1);
1054
+ subst = s2.compose(subst);
1055
+ return subst;
1056
+ }
1057
+ // 2) Only t1 open: t1.rest absorbs the surplus from t2. Surplus on t1
1058
+ // side (has1) is acceptable because t2 is closed-but-lenient.
1059
+ if (t1.rest) {
1060
+ const r1Bind = buildTail(onlyIn2);
1061
+ const s1 = unify(subst.apply(t1.rest), r1Bind, _depth + 1);
1062
+ subst = s1.compose(subst);
1063
+ return subst;
1064
+ }
1065
+ // 3) Only t2 open: symmetric.
1066
+ if (t2.rest) {
1067
+ const r2Bind = buildTail(onlyIn1);
1068
+ const s2 = unify(subst.apply(t2.rest), r2Bind, _depth + 1);
1069
+ subst = s2.compose(subst);
1070
+ return subst;
1071
+ }
1072
+ return subst;
1073
+ }
1074
+ // Wildcard (named or bare) wrapping a record — allow compatibility
1075
+ if ((t1.tag === 'TCon' && t2.tag === 'TRecord') ||
1076
+ (t1.tag === 'TRecord' && t2.tag === 'TCon')) {
1077
+ const tcon = (t1.tag === 'TCon' ? t1 : t2);
1078
+ const rec = t1.tag === 'TRecord' ? t1 : t2;
1079
+ // A bare alias name and the record expanded from that same alias are
1080
+ // one type. The name reaches unify unexpanded when it travels inside
1081
+ // another module's type (`Promise Error (Toast -> ())`, an FP library's
1082
+ // `Component` in a list of routes); the local side is expanded. Before,
1083
+ // they met as "Cannot unify 'Toast' with 'Toast'".
1084
+ if (tcon.args.length === 0 && rec.alias === tcon.name) {
1085
+ return new substitution_1.Substitution();
1086
+ }
1087
+ // Applied `Object k a` is sugar for `{ [k] :: a }`. Desugar and unify
1088
+ // structurally with the concrete record so e.g. `Object k a` accepts a
1089
+ // real `{ x :: Number }` (binding the label/value vars accordingly).
1090
+ if (tcon.name === 'Object' && tcon.args.length === 2) {
1091
+ const desugared = (0, types_1.desugarObjectType)(tcon.args[0], tcon.args[1]);
1092
+ return unify(t1.tag === 'TRecord' ? t1 : desugared, t1.tag === 'TRecord' ? desugared : t2, _depth + 1);
1093
+ }
1094
+ // A kind-variable constructor applied to one argument (`f a`, e.g. the
1095
+ // parameter of a `Foldable f => f a -> …` function) can accept a concrete
1096
+ // record by treating the record as an `Object k a`: bind the constructor
1097
+ // variable `f` to the partial application `Object k` and unify its single
1098
+ // argument with the record's value type via the `Object`-record desugar.
1099
+ // Unification only needs to succeed structurally — whether `Object`
1100
+ // legitimately satisfies the constraint is decided later by constraint
1101
+ // discharge (a `::rep Foldable Object#reduce` bridges it). Without this,
1102
+ // passing an object literal to such a function is wrongly rejected before
1103
+ // the rep can ever be consulted.
1104
+ const kvApplied = (0, types_1.parseKvName)(tcon.name);
1105
+ if (kvApplied && tcon.args.length === 1 && !occursIn(kvApplied.varId, rec)) {
1106
+ const label = (0, types_1.tLabelVar)();
1107
+ const fBinding = substitution_1.Substitution.singleton(kvApplied.varId, (0, types_1.tCon)(types_1.T_OBJECT, [label]));
1108
+ const desugared = (0, types_1.desugarObjectType)(label, tcon.args[0]);
1109
+ const s2 = unify(fBinding.apply(rec), fBinding.apply(desugared), _depth + 1);
1110
+ return s2.compose(fBinding);
1111
+ }
1112
+ // `Merge a b` ↔ TRecord compatibility: when one side is a deferred
1113
+ // `Merge` marker (used to type combinators like `QueryTag#concat`
1114
+ // whose result row is the structural union of both operands) and
1115
+ // every argument resolves to a TRecord, flatten the marker into a
1116
+ // single TRecord and unify it with `rec`. Mirrors the runtime
1117
+ // collapse performed by `applyMergeReduction` in `src/infer/calls.ts`
1118
+ // but at unification time, so the marker doesn't leak when the call
1119
+ // result is unified before the post-processor runs (e.g. when the
1120
+ // surrounding `one(x.concat(y))` call's parameter slot pulls the
1121
+ // expectation through).
1122
+ if (tcon.name === types_1.T_MERGE && tcon.args.length >= 2) {
1123
+ // label ↔ row bridge: a pure `[var]::value` record on the other side of
1124
+ // a `Merge` marker is rewritten in row form (`Merge[rowA,rowB]`) so the
1125
+ // two spellings unify positionally.
1126
+ if (isPureVarLabelRecord(rec)) {
1127
+ const { rowForm, pre } = toRowForm(rec);
1128
+ const s = unify(pre.apply(tcon), rowForm, _depth + 1);
1129
+ return s.compose(pre);
1130
+ }
1131
+ const flat = {};
1132
+ let allRecords = true;
1133
+ for (const arg of tcon.args) {
1134
+ if (arg.tag === 'TRecord') {
1135
+ for (const k in arg.fields) {
1136
+ if (!(k in flat))
1137
+ flat[k] = arg.fields[k];
1138
+ }
1139
+ }
1140
+ else {
1141
+ allRecords = false;
1142
+ break;
1143
+ }
1144
+ }
1145
+ if (allRecords) {
1146
+ const collapsed = { tag: 'TRecord', fields: flat };
1147
+ return unify(t1.tag === 'TRecord' ? t1 : collapsed, t1.tag === 'TRecord' ? collapsed : t2, _depth + 1);
1148
+ }
1149
+ }
1150
+ // Picked-projection compatibility:
1151
+ // `Picked R sel` ≡ TRecord X iff X was produced by selecting from R.
1152
+ // Generic primitive — `Picked` is hinmil's projection type for "the
1153
+ // record obtained by applying selector `sel` to row `R`". When the
1154
+ // call-site projection has run (see `applyPickedProjection` in
1155
+ // src/infer/calls.ts), the resulting TRecord carries `pickedFrom = R`.
1156
+ // A slot expectation `Picked R _` (typically a branch of a
1157
+ // `<Table>Selector` union) accepts any such record. This makes the
1158
+ // mechanism library-agnostic: any DSL that emits `Picked R sel` slots
1159
+ // and produces records via the projection benefits — not just query-builder.
1160
+ if (tcon.name === types_1.T_PICKED && tcon.args.length >= 1) {
1161
+ const rArg = tcon.args[0];
1162
+ const rowName = rArg.tag === 'TCon' ? rArg.name :
1163
+ rArg.tag === 'TRecord' ? rArg.alias :
1164
+ undefined;
1165
+ const recRow = rec.pickedFrom ?? rec.alias;
1166
+ if (rowName && recRow && rowName === recRow) {
1167
+ // Bind the selector tvar (if any) to a fresh var — the actual
1168
+ // selector list has already been absorbed into the projected
1169
+ // record's fields, so its precise type carries no further info.
1170
+ if (tcon.args.length >= 2 && tcon.args[1].tag === 'TVar') {
1171
+ return substitution_1.Substitution.singleton(tcon.args[1].id, (0, types_1.tVar)());
1172
+ }
1173
+ return new substitution_1.Substitution();
1174
+ }
1175
+ }
1176
+ // istanbul ignore next — wildcard TCons are intercepted by the early
1177
+ // isWildcard(t1)/isWildcard(t2) guards at the top of unify(), so
1178
+ // isWildcard(tcon) is always false when this branch is reached.
1179
+ /* istanbul ignore next */
1180
+ if ((0, types_1.isWildcard)(tcon))
1181
+ return new substitution_1.Substitution();
1182
+ // Object is compatible with any record type (JS object)
1183
+ if (tcon.tag === 'TCon' && tcon.name === 'Object' && tcon.args.length === 0)
1184
+ return new substitution_1.Substitution();
1185
+ // StrMap a is compatible with a record if all field values unify with a
1186
+ if (tcon.tag === 'TCon' && tcon.name === 'StrMap' && tcon.args.length === 1) {
1187
+ const valType = tcon.args[0];
1188
+ let subst = new substitution_1.Substitution();
1189
+ for (const k in rec.fields) {
1190
+ const s = unify(subst.apply(rec.fields[k]), subst.apply(valType), _depth + 1);
1191
+ subst = s.compose(subst);
1192
+ }
1193
+ return subst;
1194
+ }
1195
+ // A concrete builtin container satisfies a record whose concrete fields are
1196
+ // all well-known structural members it exposes — e.g. an Array (or String)
1197
+ // instance has `length :: Number`, so `[Number]` unifies with
1198
+ // `{ length :: a | Undefined }`. This powers predicates like
1199
+ // `hasProp("length")([2])` where the parameter record's label var resolves
1200
+ // to a concrete key the value type provides intrinsically.
1201
+ {
1202
+ const fieldKeys = Object.keys(rec.fields);
1203
+ if (fieldKeys.length > 0) {
1204
+ const members = builtinStructuralMembers(tcon.name);
1205
+ if (members && fieldKeys.every((k) => k in members)) {
1206
+ let subst = new substitution_1.Substitution();
1207
+ for (const k of fieldKeys) {
1208
+ const s = unify(subst.apply(rec.fields[k]), subst.apply(members[k]), _depth + 1);
1209
+ subst = s.compose(subst);
1210
+ }
1211
+ return subst;
1212
+ }
1213
+ }
1214
+ }
1215
+ // A user-defined nominal type satisfies a record whose concrete fields are
1216
+ // all registered instance members it exposes — e.g. `Arrow` declares
1217
+ // `Arrow#@@type :: Arrow a b ~> String`, so `Arrow a b` unifies with
1218
+ // `{ @@type :: String }` (as required by `getType :: { @@type :: String }
1219
+ // | Undefined -> String`). Each member's type is produced by its factory
1220
+ // instantiated with the container's type args, then unified with the
1221
+ // record field. Restricted to non-builtin types (builtins expose many
1222
+ // methods and are handled structurally above) and to records with no
1223
+ // label-polymorphic groups, to keep the match precise.
1224
+ {
1225
+ const fieldKeys = Object.keys(rec.fields);
1226
+ if (fieldKeys.length > 0 &&
1227
+ (!rec.labelFields || rec.labelFields.length === 0) &&
1228
+ // A user sumtype shadows a builtin of the same name (FP-library's
1229
+ // `Response` vs the Fetch API `Response`).
1230
+ (!(0, methodRegistry_1.isBuiltinType)(tcon.name) || (0, dataTypeRegistry_1.getDataType)(tcon.name) !== null)) {
1231
+ const entries = fieldKeys.map((k) => (0, methodRegistry_1.lookupMethod)(tcon.name, k));
1232
+ if (entries.every((e) => e !== null)) {
1233
+ let subst = new substitution_1.Substitution();
1234
+ let ok = true;
1235
+ for (let i = 0; i < fieldKeys.length; i++) {
1236
+ let memberType;
1237
+ try {
1238
+ memberType = entries[i].factory(tcon.args);
1239
+ }
1240
+ catch {
1241
+ ok = false;
1242
+ break;
1243
+ }
1244
+ const s = unify(subst.apply(rec.fields[fieldKeys[i]]), subst.apply(memberType), _depth + 1);
1245
+ subst = s.compose(subst);
1246
+ }
1247
+ if (ok)
1248
+ return subst;
1249
+ }
1250
+ }
1251
+ }
1252
+ throw new UnificationError(t1, t2);
1253
+ }
1254
+ // Mismatched tags
1255
+ throw new UnificationError(t1, t2);
1256
+ }
1257
+ /**
1258
+ * Every member of `sub` unifies with some member of `sup`, under one
1259
+ * substitution that is threaded through the members. Concrete members of
1260
+ * `sup` are tried before type variables, so `Undefined` meets `Undefined`
1261
+ * instead of binding `a := Undefined`. Null when a member does not fit.
1262
+ */
1263
+ function unionSubsetSubstitution(sub, sup, depth) {
1264
+ const ordered = [...sup.filter(m => m.tag !== 'TVar'), ...sup.filter(m => m.tag === 'TVar')];
1265
+ let subst = new substitution_1.Substitution();
1266
+ for (const member of sub) {
1267
+ let found = null;
1268
+ for (const candidate of ordered) {
1269
+ try {
1270
+ found = unify(subst.apply(member), subst.apply(candidate), depth + 1);
1271
+ break;
1272
+ }
1273
+ catch { /* try next candidate */ }
1274
+ }
1275
+ if (!found)
1276
+ return null;
1277
+ subst = found.compose(subst);
1278
+ }
1279
+ return subst;
1280
+ }
1281
+ /**
1282
+ * Unify a concrete type with a union type.
1283
+ * Succeeds if the type matches at least one member of the union.
1284
+ */
1285
+ function unifyWithUnion(members, other, depth = 0, overloadSet = false) {
1286
+ // If the other side is also a Union, check that all its members match some member here
1287
+ if ((0, types_1.isUnion)(other)) {
1288
+ let allMatched = true;
1289
+ for (const otherMember of other.args) {
1290
+ let matched = false;
1291
+ for (const member of members) {
1292
+ try {
1293
+ unify(member, otherMember, depth + 1);
1294
+ matched = true;
1295
+ break;
1296
+ }
1297
+ catch { /* try next */ }
1298
+ }
1299
+ if (!matched) {
1300
+ allMatched = false;
1301
+ break;
1302
+ }
1303
+ }
1304
+ if (allMatched)
1305
+ return new substitution_1.Substitution();
1306
+ // The other direction: every member here fits a member of `other`
1307
+ // (`Number | Undefined` against `a | Null | Undefined`). The bindings
1308
+ // are kept (`a := Number`), so a defaulting helper like
1309
+ // `valueOr :: a -> a | Null | Undefined -> a` accepts a narrower union.
1310
+ const subset = unionSubsetSubstitution(members, other.args, depth);
1311
+ if (subset)
1312
+ return subset;
1313
+ // Relaxed: when the value-side union is an "overloaded identifier" union
1314
+ // — i.e. it mixes callable (TFun) members with one or more non-callable
1315
+ // value members (Table TCon, metadata TRecord, …) — accept the union
1316
+ // as long as at least one of its non-function members matches some
1317
+ // member of the expected union. This supports query-builder-style overloads
1318
+ // like `LocationType :: Table | (a -> b) | (c -> d) | { props :: … }`
1319
+ // being usable as a `Selector` (whose Table branch matches Table); the
1320
+ // function and metadata branches are ignored at value sites.
1321
+ const hasFun = members.some(m => m.tag === 'TFun');
1322
+ const valueMembers = members.filter(m => m.tag !== 'TFun');
1323
+ if (hasFun && valueMembers.length > 0) {
1324
+ for (const vm of valueMembers) {
1325
+ for (const otherMember of other.args) {
1326
+ try {
1327
+ unify(vm, otherMember, depth + 1);
1328
+ return new substitution_1.Substitution();
1329
+ }
1330
+ catch { /* try next */ }
1331
+ }
1332
+ }
1333
+ }
1334
+ throw new UnificationError((0, types_1.tCon)(types_1.T_UNION, members), other);
1335
+ }
1336
+ // Soundness gate for widened heterogeneous function arrays. When an array
1337
+ // literal mixes functions of DIFFERENT arities its element type widens to a
1338
+ // union like `(a -> b) | (a -> b -> c)`. Matching such a union against a
1339
+ // single concrete function expectation must NOT silently succeed by picking
1340
+ // whichever member happens to fit — no single arity can describe every
1341
+ // element. Reject when every member is a function and their arities differ.
1342
+ // (Overload/selector unions carry non-function members and are unaffected;
1343
+ // same-arity function unions keep the permissive element-widening behaviour.)
1344
+ // An OVERLOAD SET (the alternatives of an overloaded function, possibly a
1345
+ // still-ambiguous partial application) is different: it denotes ONE of its
1346
+ // branches, chosen by context — so a function expectation simply selects
1347
+ // the first branch (declaration order) that fits.
1348
+ if (overloadSet && other.tag === 'TFun' && members.every(m => m.tag === 'TFun')) {
1349
+ for (const member of members) {
1350
+ try {
1351
+ return unify(member, other, depth + 1);
1352
+ }
1353
+ catch { /* try next branch */ }
1354
+ }
1355
+ throw new UnificationError((0, types_1.tCon)(types_1.T_UNION, members), other);
1356
+ }
1357
+ if (other.tag === 'TFun' && members.length >= 2 &&
1358
+ members.every(m => m.tag === 'TFun')) {
1359
+ // Exemption: a spread arrow chain `a -> b -> ... -> z` is BUILT to absorb
1360
+ // differing arities, so a mixed-arity function union CAN be described by
1361
+ // it — e.g. FP-library `liftN` returning `lift2 | lift3 | …` checked against
1362
+ // `(x -> y -> ... -> z) -> m x -> m y -> ... -> m z`. Soundness is kept
1363
+ // by requiring EVERY member (every runtime branch) to fit the chain.
1364
+ if ((0, typeUtils_1.hasTopLevelSpreadChain)(other) ||
1365
+ (other.param.tag === 'TFun' && (0, typeUtils_1.hasSpreadInArrowChain)(other.param))) {
1366
+ let subst = new substitution_1.Substitution();
1367
+ for (const member of members) {
1368
+ const s = unify(subst.apply(member), subst.apply(other), depth + 1);
1369
+ subst = s.compose(subst);
1370
+ }
1371
+ return subst;
1372
+ }
1373
+ const arities = new Set(members.map(m => (0, types_1.flattenCurriedType)(m).params.length));
1374
+ if (arities.size > 1) {
1375
+ throw new UnificationError((0, types_1.tCon)(types_1.T_UNION, members), other);
1376
+ }
1377
+ }
1378
+ // A member with the same type constructor is the most specific match: try
1379
+ // it first. Otherwise a structural member can win by declaration order —
1380
+ // a query builder's generated `Departments :: ({ props :: … } | Table DepartmentsRow | …)`
1381
+ // matched `Table r` through the `{ props }` record (via `Table#props`)
1382
+ // and left `r` unbound, so `Repo (Departments)` lost the row type.
1383
+ // (`isUnion` above is a type guard that narrows every TCon away, hence
1384
+ // the widening cast.)
1385
+ const target = other;
1386
+ if (target.tag === 'TCon') {
1387
+ const name = target.name;
1388
+ const nominal = members.findIndex(m => m.tag === 'TCon' && m.name === name);
1389
+ if (nominal > 0) {
1390
+ try {
1391
+ return unify(members[nominal], other, depth + 1);
1392
+ }
1393
+ catch { /* fall back to declaration order */ }
1394
+ }
1395
+ }
1396
+ // Try each member — succeed if any one matches
1397
+ for (const member of members) {
1398
+ try {
1399
+ return unify(member, other, depth + 1);
1400
+ }
1401
+ catch { /* try next member */ }
1402
+ }
1403
+ // Friendlier diagnostic for the "wrong relation" case: when union members
1404
+ // include `… (Picked R _)` branches and `other` carries a record tagged
1405
+ // with `pickedFrom`, surface "'X' is not a valid relation here." instead
1406
+ // of dumping the entire union.
1407
+ const friendly = buildPickedMismatchMessage(members, other);
1408
+ if (friendly) {
1409
+ throw new UnificationError((0, types_1.tCon)(types_1.T_UNION, members), other, friendly);
1410
+ }
1411
+ throw new UnificationError((0, types_1.tCon)(types_1.T_UNION, members), other);
1412
+ }
1413
+ /** Walk a type collecting names `R` from any `Picked R …` TCon nodes. */
1414
+ function collectPickedRowNames(t, out, depth = 0) {
1415
+ if (depth > 20)
1416
+ return;
1417
+ switch (t.tag) {
1418
+ case 'TCon':
1419
+ if (t.name === types_1.T_PICKED && t.args.length >= 1) {
1420
+ const r = t.args[0];
1421
+ if (r.tag === 'TCon')
1422
+ out.add(r.name);
1423
+ else if (r.tag === 'TRecord' && r.alias)
1424
+ out.add(r.alias);
1425
+ }
1426
+ for (const a of t.args)
1427
+ collectPickedRowNames(a, out, depth + 1);
1428
+ return;
1429
+ case 'TFun':
1430
+ collectPickedRowNames(t.param, out, depth + 1);
1431
+ collectPickedRowNames(t.result, out, depth + 1);
1432
+ return;
1433
+ case 'TRecord':
1434
+ for (const k in t.fields)
1435
+ collectPickedRowNames(t.fields[k], out, depth + 1);
1436
+ if (t.rest)
1437
+ collectPickedRowNames(t.rest, out, depth + 1);
1438
+ return;
1439
+ default:
1440
+ return;
1441
+ }
1442
+ }
1443
+ /** Find the `pickedFrom` tag of any TRecord embedded in `t`. */
1444
+ function findPickedFrom(t, depth = 0) {
1445
+ if (depth > 20)
1446
+ return undefined;
1447
+ switch (t.tag) {
1448
+ case 'TRecord':
1449
+ if (t.pickedFrom)
1450
+ return t.pickedFrom;
1451
+ for (const k in t.fields) {
1452
+ const r = findPickedFrom(t.fields[k], depth + 1);
1453
+ if (r)
1454
+ return r;
1455
+ }
1456
+ if (t.rest)
1457
+ return findPickedFrom(t.rest, depth + 1);
1458
+ return undefined;
1459
+ case 'TCon':
1460
+ for (const a of t.args) {
1461
+ const r = findPickedFrom(a, depth + 1);
1462
+ if (r)
1463
+ return r;
1464
+ }
1465
+ return undefined;
1466
+ case 'TFun': {
1467
+ const r = findPickedFrom(t.param, depth + 1);
1468
+ if (r)
1469
+ return r;
1470
+ return findPickedFrom(t.result, depth + 1);
1471
+ }
1472
+ default:
1473
+ return undefined;
1474
+ }
1475
+ }
1476
+ function buildPickedMismatchMessage(members, other) {
1477
+ const validRows = new Set();
1478
+ for (const m of members)
1479
+ collectPickedRowNames(m, validRows);
1480
+ if (validRows.size === 0)
1481
+ return undefined;
1482
+ const attempted = findPickedFrom(other);
1483
+ if (!attempted)
1484
+ return undefined;
1485
+ if (validRows.has(attempted))
1486
+ return undefined; // shouldn't happen, but be safe
1487
+ const sorted = Array.from(validRows).sort();
1488
+ const list = sorted.length <= 8
1489
+ ? sorted.join(', ')
1490
+ : sorted.slice(0, 8).join(', ') + `, … (${sorted.length - 8} more)`;
1491
+ return `'${attempted}' is not a valid relation here. Valid relations: ${list}`;
1492
+ }
1493
+ /**
1494
+ * Unify two tuple/spread-array arg lists where one side has a spread marker (...).
1495
+ * The spread marker absorbs any number of elements.
1496
+ *
1497
+ * Example: Tuple(a, b, ...) unifies with Tuple(Number, String, Boolean)
1498
+ * → a=Number, b=String (the ... absorbs Boolean)
1499
+ *
1500
+ * Example: Tuple(..., y, z) unifies with Tuple(Number, String, Boolean)
1501
+ * → y=String, z=Boolean (the ... absorbs Number)
1502
+ */
1503
+ /**
1504
+ * Unify a spread arrow chain (`a -> b -> ... -> y -> z`) against another
1505
+ * function type. The `...` marker absorbs a variable number of *middle*
1506
+ * curried parameters: the params BEFORE the spread match the concrete
1507
+ * function's leading params, the params AFTER the spread match its trailing
1508
+ * params, the terminal result unifies with the concrete terminal result, and
1509
+ * every parameter in between is absorbed by the spread.
1510
+ *
1511
+ * Mirrors {@link unifySpreadTuple} but for curried arrow chains.
1512
+ */
1513
+ function unifySpreadArrowChain(t1, t2, depth) {
1514
+ const f1 = (0, types_1.flattenCurriedType)(t1);
1515
+ const f2 = (0, types_1.flattenCurriedType)(t2);
1516
+ const spread1 = f1.params.findIndex(types_1.isSpread);
1517
+ const spread2 = f2.params.findIndex(types_1.isSpread);
1518
+ // Both sides carry a spread: unify shared before/after positionally
1519
+ // (shorter side wins) plus the terminal results.
1520
+ if (spread1 >= 0 && spread2 >= 0) {
1521
+ const before1 = f1.params.slice(0, spread1);
1522
+ const after1 = f1.params.slice(spread1 + 1);
1523
+ const before2 = f2.params.slice(0, spread2);
1524
+ const after2 = f2.params.slice(spread2 + 1);
1525
+ let subst = new substitution_1.Substitution();
1526
+ const minB = Math.min(before1.length, before2.length);
1527
+ for (let i = 0; i < minB; i++) {
1528
+ const s = unify(subst.apply(before1[i]), subst.apply(before2[i]), depth + 1);
1529
+ subst = s.compose(subst);
1530
+ }
1531
+ const minA = Math.min(after1.length, after2.length);
1532
+ for (let i = 0; i < minA; i++) {
1533
+ const s = unify(subst.apply(after1[after1.length - minA + i]), subst.apply(after2[after2.length - minA + i]), depth + 1);
1534
+ subst = s.compose(subst);
1535
+ }
1536
+ const sr = unify(subst.apply(f1.result), subst.apply(f2.result), depth + 1);
1537
+ return sr.compose(subst);
1538
+ }
1539
+ // One side spread, the other concrete.
1540
+ const [sp, conc] = spread1 >= 0 ? [f1, f2] : [f2, f1];
1541
+ const spreadIdx = sp.params.findIndex(types_1.isSpread);
1542
+ const before = sp.params.slice(0, spreadIdx);
1543
+ const after = sp.params.slice(spreadIdx + 1);
1544
+ // Each level of a spread arrow chain consumes a SINGLE argument. A concrete
1545
+ // level written with multiple parameters (`(x, dummy) => …`, typed with a
1546
+ // Tuple param) collapses to its first parameter — the surplus params are
1547
+ // `undefined` at runtime. Collapsing here keeps the SpreadArray applier
1548
+ // slots single-valued so array elements unify cleanly.
1549
+ const concParams = conc.params.map(typeUtils_1.collapseMultiParamLevel);
1550
+ // The concrete side supplies fewer params than the spread chain's fixed
1551
+ // before+after. A spread arrow chain is intentionally variadic, so a shorter
1552
+ // concrete chain is a valid instance rather than an error: the concrete
1553
+ // function simply "bottoms out" earlier (its terminal result stands in for
1554
+ // the whole variadic tail). This covers a polymorphic annotation result
1555
+ // reconciled against a longer inferred chain, a shorter-arity function passed
1556
+ // where the chain permits more params, AND a body that collapses the nested
1557
+ // currying into a single terminal (e.g. a recursive memoizer inferred as
1558
+ // `a -> b | c | d` against `a -> b -> ... -> z`). Unify as many leading
1559
+ // params as supplied and let the concrete terminal absorb the tail.
1560
+ if (conc.params.length < before.length + after.length) {
1561
+ let subst = new substitution_1.Substitution();
1562
+ const n = Math.min(before.length, concParams.length);
1563
+ for (let i = 0; i < n; i++) {
1564
+ const s = unify(subst.apply(before[i]), subst.apply(concParams[i]), depth + 1);
1565
+ subst = s.compose(subst);
1566
+ }
1567
+ // PARTIAL APPLICATION of a spread-chain CALLEE (result = peeled remainder,
1568
+ // not the terminal) is handled context-aware in the call path
1569
+ // (`inferCallExpression` → trySpreadChainCalleePeel), NOT here: at the
1570
+ // unification level a short concrete side is indistinguishable from a
1571
+ // short function ARGUMENT, which must keep bottoming out on the terminal
1572
+ // so arity bookkeeping (over-application diagnostics) stays intact.
1573
+ // Reconcile the concrete terminal with the spread chain's terminal result
1574
+ // so the variadic tail propagates (keeps the call result informative).
1575
+ const s = unify(subst.apply(conc.result), subst.apply(sp.result), depth + 1);
1576
+ return s.compose(subst);
1577
+ }
1578
+ let subst = new substitution_1.Substitution();
1579
+ for (let i = 0; i < before.length; i++) {
1580
+ const s = unify(subst.apply(before[i]), subst.apply(concParams[i]), depth + 1);
1581
+ subst = s.compose(subst);
1582
+ }
1583
+ for (let i = 0; i < after.length; i++) {
1584
+ const cIdx = concParams.length - after.length + i;
1585
+ const s = unify(subst.apply(after[i]), subst.apply(concParams[cIdx]), depth + 1);
1586
+ subst = s.compose(subst);
1587
+ }
1588
+ // The spread absorbs every middle concrete param; the terminal result of
1589
+ // the chain unifies with the concrete terminal result.
1590
+ const sr = unify(subst.apply(sp.result), subst.apply(conc.result), depth + 1);
1591
+ return sr.compose(subst);
1592
+ }
1593
+ function unifySpreadTuple(args1, args2, t1, t2, depth = 0) {
1594
+ const spreadIdx1 = args1.findIndex(a => (0, types_1.isSpread)(a));
1595
+ const spreadIdx2 = args2.findIndex(a => (0, types_1.isSpread)(a));
1596
+ // If both have spreads, unify the non-spread elements positionally
1597
+ if (spreadIdx1 >= 0 && spreadIdx2 >= 0) {
1598
+ const before1 = args1.slice(0, spreadIdx1);
1599
+ const after1 = args1.slice(spreadIdx1 + 1);
1600
+ const before2 = args2.slice(0, spreadIdx2);
1601
+ const after2 = args2.slice(spreadIdx2 + 1);
1602
+ // Unify before elements (shorter side)
1603
+ let subst = new substitution_1.Substitution();
1604
+ const minBefore = Math.min(before1.length, before2.length);
1605
+ for (let i = 0; i < minBefore; i++) {
1606
+ const s = unify(subst.apply(before1[i]), subst.apply(before2[i]), depth + 1);
1607
+ subst = s.compose(subst);
1608
+ }
1609
+ // Unify after elements (shorter side, from the end)
1610
+ const minAfter = Math.min(after1.length, after2.length);
1611
+ for (let i = 0; i < minAfter; i++) {
1612
+ const s = unify(subst.apply(after1[after1.length - minAfter + i]), subst.apply(after2[after2.length - minAfter + i]), depth + 1);
1613
+ subst = s.compose(subst);
1614
+ }
1615
+ return subst;
1616
+ }
1617
+ // One side has a spread, the other is concrete
1618
+ const [spreadArgs, concreteArgs] = spreadIdx1 >= 0 ? [args1, args2] : [args2, args1];
1619
+ const spreadIdx = spreadArgs.findIndex(a => (0, types_1.isSpread)(a));
1620
+ const before = spreadArgs.slice(0, spreadIdx);
1621
+ const after = spreadArgs.slice(spreadIdx + 1);
1622
+ // The concrete side must have at least as many elements as the non-spread parts
1623
+ if (concreteArgs.length < before.length + after.length) {
1624
+ throw new UnificationError(t1, t2);
1625
+ }
1626
+ let subst = new substitution_1.Substitution();
1627
+ // Unify "before" elements with the first N concrete elements
1628
+ for (let i = 0; i < before.length; i++) {
1629
+ const s = unify(subst.apply(before[i]), subst.apply(concreteArgs[i]), depth + 1);
1630
+ subst = s.compose(subst);
1631
+ }
1632
+ // Unify "after" elements with the last M concrete elements
1633
+ for (let i = 0; i < after.length; i++) {
1634
+ const concreteIdx = concreteArgs.length - after.length + i;
1635
+ const s = unify(subst.apply(after[i]), subst.apply(concreteArgs[concreteIdx]), depth + 1);
1636
+ subst = s.compose(subst);
1637
+ }
1638
+ return subst;
1639
+ }
1640
+ /** Does `t` contain an application of the kind variable `varId` (`$kv:m:id`)? */
1641
+ function mentionsKindVar(t, varId) {
1642
+ switch (t.tag) {
1643
+ case 'TCon': {
1644
+ const kv = (0, types_1.parseKvName)(t.name);
1645
+ if (kv && kv.varId === varId)
1646
+ return true;
1647
+ return t.args.some(a => mentionsKindVar(a, varId));
1648
+ }
1649
+ case 'TFun': return mentionsKindVar(t.param, varId) || mentionsKindVar(t.result, varId);
1650
+ case 'TRecord': return Object.values(t.fields).some(f => mentionsKindVar(f, varId));
1651
+ default: return false;
1652
+ }
1653
+ }
1654
+ /**
1655
+ * Unify a value against a WIDER declared type, in one direction: every
1656
+ * member of an actual union must unify with some member of the declared
1657
+ * union (`ReactElement | Null` fits `ReactElement | String | Null`); for
1658
+ * functions the parameters unify and the result widens (covariant). Used
1659
+ * where an annotation is checked against its implementation: symmetric
1660
+ * unification rejects two different unions. Returns the substitution, or
1661
+ * null when the actual type is not narrower.
1662
+ */
1663
+ function unifyWidening(actual, declared) {
1664
+ const acc = new substitution_1.Substitution();
1665
+ const members = (t) => {
1666
+ const r = acc.apply(t);
1667
+ return r.tag === 'TCon' && r.name === types_1.T_UNION ? r.args.flatMap(members) : [r];
1668
+ };
1669
+ const go = (a0, d0) => {
1670
+ const a = acc.apply(a0);
1671
+ const d = acc.apply(d0);
1672
+ if (a.tag === 'TFun' && d.tag === 'TFun') {
1673
+ try {
1674
+ acc.mergeFrom(unify(acc.apply(a.param), acc.apply(d.param)));
1675
+ }
1676
+ catch (e) {
1677
+ if (!(e instanceof UnificationError))
1678
+ throw e;
1679
+ return false;
1680
+ }
1681
+ return go(a.result, d.result);
1682
+ }
1683
+ const declaredMembers = members(d);
1684
+ if (declaredMembers.length < 2)
1685
+ return false;
1686
+ return members(a).every(member => declaredMembers.some(m => {
1687
+ try {
1688
+ acc.mergeFrom(unify(acc.apply(member), acc.apply(m)));
1689
+ return true;
1690
+ }
1691
+ catch (e) {
1692
+ if (!(e instanceof UnificationError))
1693
+ throw e;
1694
+ return false;
1695
+ }
1696
+ }));
1697
+ };
1698
+ return go(actual, declared) ? acc : null;
1699
+ }
1700
+ //# sourceMappingURL=unify.js.map