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,905 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Type Utilities — higher-level operations on Type values
4
+ //
5
+ // WHAT THIS FILE DOES (in plain language)
6
+ // ---------------------------------------------------------------------------
7
+ // The building blocks of a type live in types.ts. This file is the toolbox
8
+ // for *working with* whole type trees: walking through every part of a type,
9
+ // searching it, copying it with changes, merging two types into one, and
10
+ // recognising special shapes (like "a chain of functions" or "a variadic
11
+ // parameter list").
12
+ //
13
+ // The most important general-purpose tools are:
14
+ // • mapType — "walk the tree and rewrite the parts you care about"
15
+ // • someType — "does any part of this type satisfy a test?"
16
+ // • eachType — "visit every part of the tree once"
17
+ // Most other helpers here are built from these three.
18
+ //
19
+ // These are pure functions (no inference engine state) that perform
20
+ // structural transformations, pattern recognition, and traversal on the Type
21
+ // AST. Primitive constructors and representations live in types.ts; this
22
+ // module holds the more complex algorithms that build on those primitives.
23
+ // ============================================================================
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.structuralEquals = void 0;
26
+ exports.isUnionable = isUnionable;
27
+ exports.mergeUnion = mergeUnion;
28
+ exports.mergeSameConstructor = mergeSameConstructor;
29
+ exports.mapType = mapType;
30
+ exports.scrubSkolems = scrubSkolems;
31
+ exports.someType = someType;
32
+ exports.eachType = eachType;
33
+ exports.replaceUnionInType = replaceUnionInType;
34
+ exports.collectTVarIdsFromType = collectTVarIdsFromType;
35
+ exports.extractCorresponding = extractCorresponding;
36
+ exports.freshenType = freshenType;
37
+ exports.replaceSpreadTupleWithConcrete = replaceSpreadTupleWithConcrete;
38
+ exports.hasSpreadInArrowChain = hasSpreadInArrowChain;
39
+ exports.isSpreadTupleOrArray = isSpreadTupleOrArray;
40
+ exports.collapseMultiParamLevel = collapseMultiParamLevel;
41
+ exports.isArrowChainTuple = isArrowChainTuple;
42
+ exports.collapseArrowChainTuple = collapseArrowChainTuple;
43
+ exports.hasTopLevelSpreadChain = hasTopLevelSpreadChain;
44
+ exports.detectSpreadChainLink = detectSpreadChainLink;
45
+ exports.extractParamTVarIds = extractParamTVarIds;
46
+ exports.containsQuantifiedVar = containsQuantifiedVar;
47
+ exports.findCarrierTVarId = findCarrierTVarId;
48
+ exports.findOverloadSlots = findOverloadSlots;
49
+ exports.findHostSlots = findHostSlots;
50
+ exports.substTVar = substTVar;
51
+ exports.narrowCallResultByArgs = narrowCallResultByArgs;
52
+ exports.neutralizeUnions = neutralizeUnions;
53
+ exports.collectKvApplications = collectKvApplications;
54
+ exports.fixTypeRepKvVars = fixTypeRepKvVars;
55
+ exports.extractParamList = extractParamList;
56
+ exports.discriminateRecordArg = discriminateRecordArg;
57
+ exports.renameKvInType = renameKvInType;
58
+ const types_1 = require("./types");
59
+ // Re-export for consumers that import from typeUtils
60
+ var types_2 = require("./types");
61
+ Object.defineProperty(exports, "structuralEquals", { enumerable: true, get: function () { return types_2.structuralEquals; } });
62
+ // ---------------------------------------------------------------------------
63
+ // Auto-union helpers
64
+ //
65
+ // Plain language: when the same variable can hold different types on
66
+ // different code paths (e.g. `x = 1` in one branch, `x = 'a'` in another),
67
+ // the checker combines them into a union (`Number | String`). These helpers
68
+ // decide when that is allowed and perform the combining.
69
+ // ---------------------------------------------------------------------------
70
+ /** A type is unionable if it's a simple TCon (no higher-kinded args) or an
71
+ * existing Union type. */
72
+ function isUnionable(t) {
73
+ if (t.tag !== 'TCon')
74
+ return false;
75
+ if (t.name === types_1.T_UNION)
76
+ return true;
77
+ // Wildcards should not participate in union creation
78
+ if ((0, types_1.isWildcard)(t))
79
+ return false;
80
+ // Simple concrete type (String, Number, Boolean, …) — no args
81
+ return t.args.length === 0;
82
+ }
83
+ /** Merge two unionable types into a single Union, flattening nested unions
84
+ * and deduplicating members. */
85
+ function mergeUnion(a, b) {
86
+ const members = [];
87
+ const addMember = (t) => {
88
+ if (t.tag === 'TCon' && t.name === types_1.T_UNION) {
89
+ for (const m of t.args)
90
+ addMember(m);
91
+ }
92
+ else {
93
+ if (!members.some(m => (0, types_1.structuralEquals)(m, t))) {
94
+ members.push(t);
95
+ }
96
+ }
97
+ };
98
+ addMember(a);
99
+ addMember(b);
100
+ return (0, types_1.tUnion)(members);
101
+ }
102
+ /**
103
+ * Merge two TCon types with the same constructor name by unioning the
104
+ * differing type arguments. Returns the merged type, or null if the
105
+ * types cannot be merged (different constructors, different arg counts,
106
+ * or non-unionable differing args).
107
+ *
108
+ * Example: Either String Number + Either String String → Either String (String | Number)
109
+ */
110
+ function mergeSameConstructor(a, b) {
111
+ if (a.tag !== 'TCon' || b.tag !== 'TCon')
112
+ return null;
113
+ if (a.name !== b.name || a.args.length !== b.args.length || a.args.length === 0)
114
+ return null;
115
+ const mergedArgs = [];
116
+ for (let i = 0; i < a.args.length; i++) {
117
+ if ((0, types_1.typeToString)(a.args[i]) === (0, types_1.typeToString)(b.args[i])) {
118
+ mergedArgs.push(a.args[i]);
119
+ }
120
+ else if (isUnionable(a.args[i]) && isUnionable(b.args[i])) {
121
+ mergedArgs.push(mergeUnion(a.args[i], b.args[i]));
122
+ }
123
+ else {
124
+ // Try recursively merging nested same-name constructors
125
+ const nested = mergeSameConstructor(a.args[i], b.args[i]);
126
+ if (nested) {
127
+ mergedArgs.push(nested);
128
+ }
129
+ else {
130
+ return null;
131
+ }
132
+ }
133
+ }
134
+ return (0, types_1.tCon)(a.name, mergedArgs);
135
+ }
136
+ // ---------------------------------------------------------------------------
137
+ // Generic type-tree traversal helpers
138
+ //
139
+ // Plain language: a type is a tree of parts (see types.ts). These three
140
+ // functions are the standard ways to move through that tree — rewrite it
141
+ // (mapType), search it (someType), or just look at every part (eachType).
142
+ // ---------------------------------------------------------------------------
143
+ /**
144
+ * Transform a type tree top-down with structural sharing.
145
+ * `pre` is called on each node — if it returns a Type, that replaces the node
146
+ * (no further recursion). If it returns `undefined`, children are recursed
147
+ * and the node is reconstructed only when something changed.
148
+ */
149
+ function mapType(t, pre) {
150
+ const replaced = pre(t);
151
+ if (replaced !== undefined)
152
+ return replaced;
153
+ switch (t.tag) {
154
+ case 'TVar': return t;
155
+ case 'TCon': {
156
+ const newArgs = t.args.map(a => mapType(a, pre));
157
+ if (newArgs.every((a, i) => a === t.args[i]))
158
+ return t;
159
+ return { ...t, args: newArgs };
160
+ }
161
+ case 'TFun': {
162
+ const p = mapType(t.param, pre), r = mapType(t.result, pre);
163
+ if (p === t.param && r === t.result)
164
+ return t;
165
+ return { ...t, param: p, result: r };
166
+ }
167
+ case 'TRecord': {
168
+ const fields = {};
169
+ let changed = false;
170
+ for (const k in t.fields) {
171
+ const nv = mapType(t.fields[k], pre);
172
+ if (nv !== t.fields[k])
173
+ changed = true;
174
+ fields[k] = nv;
175
+ }
176
+ let newLabelFields = t.labelFields;
177
+ if (t.labelFields) {
178
+ const mapped = t.labelFields.map(lf => {
179
+ const nl = mapType(lf.label, pre);
180
+ const nt = mapType(lf.type, pre);
181
+ if (nl === lf.label && nt === lf.type)
182
+ return lf;
183
+ changed = true;
184
+ // Mapped label may have collapsed to a non-TLabel (defensive: keep original).
185
+ return { label: nl.tag === 'TLabel' ? nl : lf.label, type: nt };
186
+ });
187
+ newLabelFields = mapped;
188
+ }
189
+ if (t.rest) {
190
+ const newRest = mapType(t.rest, pre);
191
+ if (newRest !== t.rest)
192
+ changed = true;
193
+ // Row position accepts TVar or TRow; anything else is dropped
194
+ // (conservative — the caller's `pre` returned something that
195
+ // can't sit in row position, so we close the record instead).
196
+ if (changed) {
197
+ const out = { ...t, fields };
198
+ if (newLabelFields !== t.labelFields)
199
+ out.labelFields = newLabelFields;
200
+ if (newRest.tag === 'TVar' || newRest.tag === 'TRow')
201
+ out.rest = newRest;
202
+ else
203
+ delete out.rest;
204
+ return out;
205
+ }
206
+ return t;
207
+ }
208
+ if (!changed)
209
+ return t;
210
+ const out = { ...t, fields };
211
+ if (newLabelFields !== t.labelFields)
212
+ out.labelFields = newLabelFields;
213
+ return out;
214
+ }
215
+ case 'TLabel': return t;
216
+ case 'TRow': return t;
217
+ case 'TForall': {
218
+ const b = mapType(t.body, pre);
219
+ if (b === t.body)
220
+ return t;
221
+ return { ...t, body: b };
222
+ }
223
+ }
224
+ }
225
+ /**
226
+ * Replace rigid skolem constants (`§N` TCons, produced by `instantiateSkolem`)
227
+ * with fresh display type variables so a type can be shown to the user without
228
+ * leaking internal skolem names. Each distinct skolem maps to a single fresh
229
+ * TVar (memoized per call) so shared skolems render with one consistent letter
230
+ * (e.g. `§0 -> §1 -> §0` → `b -> a -> b`). When `skolemToName` carries the
231
+ * original annotation letter, that name is preserved on the display var.
232
+ */
233
+ function scrubSkolems(t, skolemToName) {
234
+ const cache = new Map();
235
+ return mapType(t, n => {
236
+ if (!(0, types_1.isSkolem)(n))
237
+ return undefined;
238
+ const name = n.name;
239
+ let v = cache.get(name);
240
+ if (!v) {
241
+ v = (0, types_1.tVar)(skolemToName?.get(name));
242
+ cache.set(name, v);
243
+ }
244
+ return v;
245
+ });
246
+ }
247
+ /** Returns true if `predicate` holds for any node in the type tree. */
248
+ function someType(t, predicate) {
249
+ if (predicate(t))
250
+ return true;
251
+ switch (t.tag) {
252
+ case 'TVar': return false;
253
+ case 'TCon': return t.args.some(a => someType(a, predicate));
254
+ case 'TFun': return someType(t.param, predicate) || someType(t.result, predicate);
255
+ case 'TRecord':
256
+ for (const k in t.fields) {
257
+ if (someType(t.fields[k], predicate))
258
+ return true;
259
+ }
260
+ if (t.labelFields) {
261
+ for (const lf of t.labelFields) {
262
+ if (someType(lf.label, predicate))
263
+ return true;
264
+ if (someType(lf.type, predicate))
265
+ return true;
266
+ }
267
+ }
268
+ if (t.rest && someType(t.rest, predicate))
269
+ return true;
270
+ return false;
271
+ case 'TLabel': return false;
272
+ case 'TRow': return false;
273
+ case 'TForall': return someType(t.body, predicate);
274
+ }
275
+ }
276
+ /** Visit every node in a type tree. */
277
+ function eachType(t, visitor) {
278
+ visitor(t);
279
+ switch (t.tag) {
280
+ case 'TVar': break;
281
+ case 'TCon':
282
+ t.args.forEach(a => eachType(a, visitor));
283
+ break;
284
+ case 'TFun':
285
+ eachType(t.param, visitor);
286
+ eachType(t.result, visitor);
287
+ break;
288
+ case 'TRecord':
289
+ for (const k in t.fields)
290
+ eachType(t.fields[k], visitor);
291
+ if (t.labelFields) {
292
+ for (const lf of t.labelFields) {
293
+ eachType(lf.label, visitor);
294
+ eachType(lf.type, visitor);
295
+ }
296
+ }
297
+ if (t.rest)
298
+ eachType(t.rest, visitor);
299
+ break;
300
+ case 'TLabel':
301
+ case 'TRow':
302
+ break;
303
+ case 'TForall':
304
+ eachType(t.body, visitor);
305
+ break;
306
+ }
307
+ }
308
+ // ---------------------------------------------------------------------------
309
+ // Union replacement
310
+ // ---------------------------------------------------------------------------
311
+ /**
312
+ * Replace occurrences of a specific union type in a type tree with a
313
+ * replacement type. Uses structural (string) comparison to match unions.
314
+ */
315
+ function replaceUnionInType(type, union, replacement) {
316
+ return mapType(type, t => (0, types_1.isUnion)(t) && (0, types_1.structuralEquals)(t, union) ? replacement : undefined);
317
+ }
318
+ // ---------------------------------------------------------------------------
319
+ // Spread / variadic chain helpers
320
+ //
321
+ // Plain language: some functions accept "any number of arguments" (variadic),
322
+ // written in signatures with a `...` marker, e.g. `(a, b, ...) -> z` or the
323
+ // curried chain `a -> b -> ... -> z`. These helpers recognise those shapes
324
+ // and convert them to concrete forms once the real argument count is known.
325
+ // ---------------------------------------------------------------------------
326
+ /** Collect all TVar ids from a type into the given Set. Also includes
327
+ * TLabel-variable ids — they live in the same id-space and need to be
328
+ * freshened/generalized alongside ordinary type variables.
329
+ *
330
+ * Variables BOUND by a nested `TForall` are scoped to its body and are
331
+ * deliberately excluded — they are never free, so `generalize` must not
332
+ * re-quantify them and `instantiate` must not freshen them. */
333
+ function collectTVarIdsFromType(t, ids) {
334
+ switch (t.tag) {
335
+ case 'TVar':
336
+ ids.add(t.id);
337
+ return;
338
+ case 'TRow':
339
+ ids.add(t.id);
340
+ return;
341
+ case 'TLabel':
342
+ if (t.kind === 'var')
343
+ ids.add(t.id);
344
+ return;
345
+ case 'TCon': {
346
+ // Kind-variable TCon names (`$kv:p:376`) carry a type-variable id
347
+ // embedded in the name string. Without collecting it here, the kv
348
+ // var is invisible to `generalize` (so it never gets quantified) and
349
+ // to `instantiate` (so it never gets freshened) — letting a stale kv
350
+ // id leak across an import boundary and collide with an unrelated
351
+ // binding in the consumer (e.g. `p a c` resolving to `Arrow String a c`).
352
+ const kv = (0, types_1.parseKvName)(t.name);
353
+ if (kv)
354
+ ids.add(kv.varId);
355
+ for (const a of t.args)
356
+ collectTVarIdsFromType(a, ids);
357
+ return;
358
+ }
359
+ case 'TFun':
360
+ collectTVarIdsFromType(t.param, ids);
361
+ collectTVarIdsFromType(t.result, ids);
362
+ return;
363
+ case 'TRecord':
364
+ for (const k in t.fields)
365
+ collectTVarIdsFromType(t.fields[k], ids);
366
+ if (t.labelFields) {
367
+ for (const lf of t.labelFields) {
368
+ collectTVarIdsFromType(lf.label, ids);
369
+ collectTVarIdsFromType(lf.type, ids);
370
+ }
371
+ }
372
+ if (t.rest)
373
+ collectTVarIdsFromType(t.rest, ids);
374
+ return;
375
+ case 'TForall': {
376
+ const inner = new Set();
377
+ collectTVarIdsFromType(t.body, inner);
378
+ for (const v of t.vars)
379
+ inner.delete(v);
380
+ for (const id of inner)
381
+ ids.add(id);
382
+ return;
383
+ }
384
+ }
385
+ }
386
+ /**
387
+ * Given a template type where `targetId` appears at some structural position,
388
+ * return the type at the SAME position in `target`. Returns null if the
389
+ * structures don't match or if targetId isn't found in the template.
390
+ */
391
+ function extractCorresponding(template, target, targetId) {
392
+ if (template.tag === 'TVar' && template.id === targetId)
393
+ return target;
394
+ if (template.tag === 'TCon' && target.tag === 'TCon' &&
395
+ (template.name === target.name || !!(0, types_1.parseKvName)(template.name)) &&
396
+ template.args.length === target.args.length) {
397
+ for (let i = 0; i < template.args.length; i++) {
398
+ const found = extractCorresponding(template.args[i], target.args[i], targetId);
399
+ if (found)
400
+ return found;
401
+ }
402
+ }
403
+ if (template.tag === 'TFun' && target.tag === 'TFun') {
404
+ const fromParam = extractCorresponding(template.param, target.param, targetId);
405
+ if (fromParam)
406
+ return fromParam;
407
+ return extractCorresponding(template.result, target.result, targetId);
408
+ }
409
+ return null;
410
+ }
411
+ /** Create a fresh copy of a type, replacing all TVars (and TLabel-vars)
412
+ * with new fresh ones — keeping shared identity within `t`.
413
+ *
414
+ * `pinned` (optional) is a set of variable ids that must NOT be freshened:
415
+ * vars that also occur outside the type being copied (e.g. a params var `p`
416
+ * threaded from an array-element union into the callee's result type) keep
417
+ * their identity so per-element freshening doesn't sever the link. */
418
+ function freshenType(t, pinned) {
419
+ const mapping = new Map();
420
+ const labelMapping = new Map();
421
+ const pre = (n) => {
422
+ if (n.tag === 'TVar') {
423
+ if (pinned?.has(n.id))
424
+ return undefined;
425
+ if (!mapping.has(n.id))
426
+ mapping.set(n.id, (0, types_1.tVar)());
427
+ return mapping.get(n.id);
428
+ }
429
+ if (n.tag === 'TLabel' && n.kind === 'var') {
430
+ if (pinned?.has(n.id))
431
+ return undefined;
432
+ if (!labelMapping.has(n.id))
433
+ labelMapping.set(n.id, { tag: 'TLabel', kind: 'var', id: (0, types_1.tVar)().id, name: n.name });
434
+ return labelMapping.get(n.id);
435
+ }
436
+ if (n.tag === 'TForall') {
437
+ // Freshen the bound vars too (through the SAME mapping so body
438
+ // occurrences stay linked) and rewrite the vars list accordingly —
439
+ // otherwise the quantifier would list stale ids that no longer occur
440
+ // in the freshened body.
441
+ const vars = n.vars.map(id => {
442
+ if (pinned?.has(id))
443
+ return id;
444
+ if (!mapping.has(id))
445
+ mapping.set(id, (0, types_1.tVar)());
446
+ return mapping.get(id).id;
447
+ });
448
+ return { ...n, vars, body: mapType(n.body, pre) };
449
+ }
450
+ return undefined;
451
+ };
452
+ return mapType(t, pre);
453
+ }
454
+ /**
455
+ * Replace Tuple nodes containing spread markers with concrete Tuple nodes
456
+ * using the given concrete parameter list. Used after spread-function wrapper
457
+ * inference to strip the `...` from result types.
458
+ *
459
+ * Example: (String, Number, ...) -> String → (String, Number) -> String
460
+ */
461
+ function replaceSpreadTupleWithConcrete(type, concreteParams) {
462
+ return mapType(type, n => {
463
+ if (n.tag === 'TCon'
464
+ && (n.name === types_1.T_TUPLE || n.name === types_1.T_SPREAD_ARRAY)
465
+ && n.args.some(a => (0, types_1.isSpread)(a))) {
466
+ if (concreteParams.length === 1)
467
+ return concreteParams[0];
468
+ return (0, types_1.tCon)(types_1.T_TUPLE, concreteParams);
469
+ }
470
+ return undefined;
471
+ });
472
+ }
473
+ /**
474
+ * Check if an arrow chain (TFun chain) contains a bare spread marker as a
475
+ * param. This distinguishes curry-style results (a -> b -> ... -> z) from
476
+ * multi-param function results ((a, b, ...) -> z).
477
+ */
478
+ function hasSpreadInArrowChain(t) {
479
+ if (t.tag !== 'TFun')
480
+ return false;
481
+ if ((0, types_1.isSpread)(t.param))
482
+ return true;
483
+ return hasSpreadInArrowChain(t.result);
484
+ }
485
+ /** Check if a type is a Tuple or SpreadArray containing spread markers. */
486
+ function isSpreadTupleOrArray(t) {
487
+ return t.tag === 'TCon' &&
488
+ (t.name === types_1.T_TUPLE || t.name === types_1.T_SPREAD_ARRAY) &&
489
+ t.args.some(a => (0, types_1.isSpread)(a));
490
+ }
491
+ /**
492
+ * Collapse a curried level that was written with multiple parameters
493
+ * (`(x, dummy) => …`, typed with a Tuple param) down to its first parameter.
494
+ * In a spread arrow chain each level consumes a SINGLE argument, so the
495
+ * surplus parameters are `undefined` at runtime and the level behaves like
496
+ * `x -> …`. Spread tuples (variadic markers) and empty tuples are left
497
+ * untouched.
498
+ */
499
+ function collapseMultiParamLevel(t) {
500
+ if (t.tag === 'TCon' && t.name === types_1.T_TUPLE) {
501
+ const args = t.args;
502
+ if (args.length > 0 && !args.some(a => (0, types_1.isSpread)(a))) {
503
+ return args[0];
504
+ }
505
+ }
506
+ return t;
507
+ }
508
+ /**
509
+ * A spread tuple/array whose non-spread elements are ALL arrows — i.e. a
510
+ * chained sequence of functions `(a -> b, b -> c, ..., y -> z)` (or the bracket
511
+ * form). This is how a container-wrapped chain `f (a->b,...,y->z)` stores its
512
+ * element sequence. Part of the chain-combinator subsystem's predicate surface
513
+ * (re-exported via `src/infer/functionPatterns.ts`).
514
+ */
515
+ function isArrowChainTuple(t) {
516
+ if (t.tag !== 'TCon')
517
+ return false;
518
+ if (t.name !== types_1.T_TUPLE && t.name !== types_1.T_SPREAD_ARRAY)
519
+ return false;
520
+ if (!t.args.some(a => (0, types_1.isSpread)(a)))
521
+ return false;
522
+ const nonSpread = t.args.filter(a => !(0, types_1.isSpread)(a));
523
+ return nonSpread.length > 0 && nonSpread.every(a => a.tag === 'TFun');
524
+ }
525
+ /**
526
+ * Collapse an arrow-chain tuple to its overall composed arrow
527
+ * `first.param -> last.result` (e.g. `(a->b, b->c, ..., y->z)` → `a -> z`).
528
+ */
529
+ function collapseArrowChainTuple(t) {
530
+ const nonSpread = t.args.filter(a => !(0, types_1.isSpread)(a));
531
+ const first = nonSpread[0];
532
+ const last = nonSpread[nonSpread.length - 1];
533
+ if (first.tag !== 'TFun' || last.tag !== 'TFun')
534
+ return null;
535
+ return (0, types_1.tFun)(first.param, last.result);
536
+ }
537
+ /**
538
+ * True when a curried arrow chain contains a bare spread marker (`...`) as a
539
+ * TOP-LEVEL parameter — i.e. reachable by walking `.result` links without first
540
+ * passing through a param that is itself a function type. This is the genuine
541
+ * variadic-chain shape (`a -> b -> ... -> z`) that `unifySpreadArrowChain` can
542
+ * absorb. A type whose spread is nested inside a higher-order parameter
543
+ * (`(a -> b -> ... -> z) -> r`) is a plain function and returns `false`, so it
544
+ * decomposes structurally instead.
545
+ */
546
+ function hasTopLevelSpreadChain(t) {
547
+ let cur = t;
548
+ while (cur.tag === 'TFun') {
549
+ if ((0, types_1.isSpread)(cur.param))
550
+ return true;
551
+ // A function-typed parameter means this is a higher-order function, not a
552
+ // flat variadic chain — stop before flattening across it.
553
+ if (cur.param.tag === 'TFun')
554
+ return false;
555
+ cur = cur.result;
556
+ }
557
+ return false;
558
+ }
559
+ /**
560
+ * Detect the chain link pattern in spread tuple elements.
561
+ * Returns the direction (ltr/rtl), structural templates for result/param sides,
562
+ * and the shared TVar id that forms the chain link.
563
+ *
564
+ * LTR example: (a->b), (b->c) — result of elem[i] links to param of elem[i+1]
565
+ * RTL example: (b->c), (a->b) — param of elem[i] links to result of elem[i+1]
566
+ * HK example: (a->m b), (b->m c) — inner of result links to param (still LTR)
567
+ */
568
+ function detectSpreadChainLink(before, after) {
569
+ function findInElements(elements) {
570
+ if (elements.length < 2)
571
+ return null;
572
+ for (let i = 0; i < elements.length - 1; i++) {
573
+ const a = elements[i], b = elements[i + 1];
574
+ if (a.tag !== 'TFun' || b.tag !== 'TFun')
575
+ continue;
576
+ // Check LTR: result(a) shares TVar with param(b)
577
+ const resultAIds = new Set();
578
+ collectTVarIdsFromType(a.result, resultAIds);
579
+ const paramBIds = new Set();
580
+ collectTVarIdsFromType(b.param, paramBIds);
581
+ for (const id of resultAIds) {
582
+ if (paramBIds.has(id)) {
583
+ return { direction: 'ltr', resultTemplate: a.result, paramTemplate: b.param, linkId: id };
584
+ }
585
+ }
586
+ // Check RTL: param(a) shares TVar with result(b)
587
+ const paramAIds = new Set();
588
+ collectTVarIdsFromType(a.param, paramAIds);
589
+ const resultBIds = new Set();
590
+ collectTVarIdsFromType(b.result, resultBIds);
591
+ for (const id of paramAIds) {
592
+ if (resultBIds.has(id)) {
593
+ return { direction: 'rtl', resultTemplate: b.result, paramTemplate: a.param, linkId: id };
594
+ }
595
+ }
596
+ }
597
+ return null;
598
+ }
599
+ // Try before first (pipe patterns), then after (compose patterns)
600
+ return findInElements(before) ?? findInElements(after);
601
+ }
602
+ /** Extract the TVar IDs from the parameter positions of a (possibly curried)
603
+ * function type. Returns undefined for positions that are not plain TVars. */
604
+ function extractParamTVarIds(t, numParams) {
605
+ const result = [];
606
+ let current = t;
607
+ for (let i = 0; i < numParams; i++) {
608
+ if (current.tag === 'TFun') {
609
+ result.push(current.param.tag === 'TVar' ? current.param.id : undefined);
610
+ current = current.result;
611
+ }
612
+ else if (current.tag === 'TCon' && current.name === '->') {
613
+ const param = current.args[0];
614
+ result.push(param.tag === 'TVar' ? param.id : undefined);
615
+ current = current.args[1];
616
+ }
617
+ else {
618
+ result.push(undefined);
619
+ }
620
+ }
621
+ return result;
622
+ }
623
+ // ---------------------------------------------------------------------------
624
+ // Type structure helpers
625
+ // ---------------------------------------------------------------------------
626
+ /** Check whether a type contains any of the given quantified variable ids. */
627
+ function containsQuantifiedVar(t, vars) {
628
+ return someType(t, n => n.tag === 'TVar' && vars.has(n.id));
629
+ }
630
+ // ---------------------------------------------------------------------------
631
+ // Carrier-TVar specialisation
632
+ // ---------------------------------------------------------------------------
633
+ /**
634
+ * Locate the id of the "carrier" TVar in a result type — i.e. the
635
+ * element-position TVar inside the innermost `[?]` (Array) wrapper,
636
+ * recursing through any number of TCon wrappers (`Promise [a]`,
637
+ * `RTask r e [a]`, `[a]` itself).
638
+ *
639
+ * Returns null when no Array-element TVar can be located.
640
+ *
641
+ * Used by both inference (`tryConstructorCallable` in `src/infer/index.ts`)
642
+ * and hover (`collectConstructorCallableOverloads` in
643
+ * `src/services/hover.ts`) to specialise an imported value-as-callable
644
+ * overload like `QueryTag :: a -> RTask r e [b]` with the host TCon's row
645
+ * arg, so calling/chaining/displaying the value all see the projected
646
+ * row instead of a bare type variable.
647
+ */
648
+ function findCarrierTVarId(t) {
649
+ if (t.tag === 'TCon') {
650
+ if (t.name === 'Array' && t.args.length === 1) {
651
+ const elem = t.args[0];
652
+ if (elem.tag === 'TVar')
653
+ return elem.id;
654
+ return findCarrierTVarId(elem);
655
+ }
656
+ for (const a of t.args) {
657
+ const found = findCarrierTVarId(a);
658
+ if (found !== null)
659
+ return found;
660
+ }
661
+ }
662
+ return null;
663
+ }
664
+ /**
665
+ * Locate the slots of a value-as-callable overload branch so the
666
+ * surrounding host TCon's args can be substituted into them.
667
+ *
668
+ * - `paramTVarId`: id of the parameter TVar (the `a` in
669
+ * `a -> RTask r e [b]`). Used to substitute the host's
670
+ * parameter-record arg (the `p` in `QueryTag p row`) into the overload's
671
+ * parameter slot. Null when the parameter isn't a bare TVar (e.g.
672
+ * already a concrete record).
673
+ * - `carrierTVarId`: as returned by `findCarrierTVarId` — the
674
+ * element-position TVar inside the innermost `[?]` wrapper of the
675
+ * result type. Used to substitute the host's row arg into the
676
+ * overload's carrier slot.
677
+ */
678
+ function findOverloadSlots(branch) {
679
+ if (branch.tag !== 'TFun')
680
+ return { paramTVarId: null, carrierTVarId: null };
681
+ const paramTVarId = branch.param.tag === 'TVar' ? branch.param.id : null;
682
+ const carrierTVarId = findCarrierTVarId(branch.result) ?? findTrailingTVarId(branch.result);
683
+ return { paramTVarId, carrierTVarId };
684
+ }
685
+ /**
686
+ * Fallback carrier for a result without an Array element: the LAST type
687
+ * argument of the (innermost) wrapper, looking through a union. A single-row
688
+ * query `QueryOne() :: p -> Promise e (o | Null)` or a task
689
+ * `p -> RTask r Error o` carries its row in that position, by the same
690
+ * convention `findHostSlots` uses for the host (`row` is the last arg).
691
+ */
692
+ function findTrailingTVarId(t) {
693
+ if (t.tag === 'TVar')
694
+ return t.id;
695
+ if (t.tag !== 'TCon' || t.args.length === 0)
696
+ return null;
697
+ if (t.name === 'Union') {
698
+ for (const member of t.args) {
699
+ if (member.tag === 'TVar')
700
+ return member.id;
701
+ }
702
+ return null;
703
+ }
704
+ return findTrailingTVarId(t.args[t.args.length - 1]);
705
+ }
706
+ /**
707
+ * Identify the parameter and row args carried by a host TCon (e.g.
708
+ * `QueryTag <param> <row>` or the legacy 1-arg `QueryTag <row>`).
709
+ *
710
+ * Convention: the trailing arg is always the row (the value the
711
+ * container holds); when there are two or more args the second-to-last
712
+ * is the parameter record. Used by hover, signature help and the
713
+ * unification bridge to pump these args into a value-as-callable
714
+ * overload's slots.
715
+ */
716
+ function findHostSlots(host) {
717
+ if (host.tag !== 'TCon' || host.args.length === 0) {
718
+ return { paramArg: null, rowArg: null };
719
+ }
720
+ if (host.args.length === 1)
721
+ return { paramArg: null, rowArg: host.args[0] };
722
+ return {
723
+ paramArg: host.args[host.args.length - 2],
724
+ rowArg: host.args[host.args.length - 1],
725
+ };
726
+ }
727
+ /** Substitute a single TVar id with `replacement` everywhere in `t`. */
728
+ function substTVar(t, id, replacement) {
729
+ if (t.tag === 'TVar')
730
+ return t.id === id ? replacement : t;
731
+ if (t.tag === 'TCon') {
732
+ const newArgs = t.args.map(a => substTVar(a, id, replacement));
733
+ if (newArgs.every((a, i) => a === t.args[i]))
734
+ return t;
735
+ return { ...t, args: newArgs };
736
+ }
737
+ if (t.tag === 'TFun') {
738
+ const p = substTVar(t.param, id, replacement);
739
+ const r = substTVar(t.result, id, replacement);
740
+ if (p === t.param && r === t.result)
741
+ return t;
742
+ return { ...t, param: p, result: r };
743
+ }
744
+ if (t.tag === 'TRecord') {
745
+ const fields = {};
746
+ let changed = false;
747
+ for (const k in t.fields) {
748
+ const nv = substTVar(t.fields[k], id, replacement);
749
+ if (nv !== t.fields[k])
750
+ changed = true;
751
+ fields[k] = nv;
752
+ }
753
+ if (!changed)
754
+ return t;
755
+ return { ...t, fields };
756
+ }
757
+ return t;
758
+ }
759
+ // ---------------------------------------------------------------------------
760
+ // Call-site union narrowing
761
+ // ---------------------------------------------------------------------------
762
+ /**
763
+ * Narrow union parameter→result correlation at a call site.
764
+ * When the actual argument is a single member of a union-typed parameter,
765
+ * narrow the result type accordingly.
766
+ *
767
+ * Example: `(Number | null) -> Number | null` called with `Number`
768
+ * → result narrows to `Number` instead of `Number | null`.
769
+ */
770
+ function narrowCallResultByArgs(result, paramTypes, argTypes) {
771
+ for (let i = 0; i < paramTypes.length && i < argTypes.length; i++) {
772
+ const param = paramTypes[i];
773
+ const arg = argTypes[i];
774
+ // Only narrow if param is a union and arg is NOT a union
775
+ if (!(0, types_1.isUnion)(param))
776
+ continue;
777
+ if ((0, types_1.isUnion)(arg))
778
+ continue;
779
+ // Check if the arg type is a member of the param union
780
+ const isMember = param.args.some(m => (0, types_1.structuralEquals)(m, arg));
781
+ if (!isMember)
782
+ continue;
783
+ // Only the result AS A WHOLE narrows (`(Number | Null) -> Number | Null`
784
+ // called with a Number). A union inside a declared result (a record
785
+ // field `reason :: String | Null` of an annotated `S`) is a promise of
786
+ // that type, not a copy of the argument: narrowing it there made two
787
+ // calls `f ("x")` and `f (null)` disagree on `S`.
788
+ if ((0, types_1.structuralEquals)(result, param))
789
+ result = arg;
790
+ }
791
+ return result;
792
+ }
793
+ /**
794
+ * Replace `TCon('Union', [...])` nodes with fresh TVars throughout a type tree.
795
+ * This prevents infinite-type errors when unifying variant-specific property
796
+ * types (e.g. `e`) against their general union form (e.g. `a | e`).
797
+ */
798
+ function neutralizeUnions(type) {
799
+ return mapType(type, n => (n.tag === 'TCon' && n.name === types_1.T_UNION) ? (0, types_1.tVar)() : undefined);
800
+ }
801
+ // ---------------------------------------------------------------------------
802
+ // Kind-variable TypeRep fixup
803
+ // ---------------------------------------------------------------------------
804
+ /**
805
+ * Collect kv-TCon applications in a type. For each kv-TCon `$kv:m:ID(a)`,
806
+ * maps the embedded varId to the full TCon node.
807
+ * E.g. for `$kv:m:100(a)`, maps 100 → TCon('$kv:m:100', [TVar('a', 101)]).
808
+ */
809
+ function collectKvApplications(t, out) {
810
+ eachType(t, node => {
811
+ if (node.tag === 'TCon') {
812
+ const kv = (0, types_1.parseKvName)(node.name);
813
+ if (kv && node.args.length > 0 && !out.has(kv.varId))
814
+ out.set(kv.varId, node);
815
+ }
816
+ });
817
+ }
818
+ /**
819
+ * Replace bare TVars inside TypeRep nodes with their kv-applied form.
820
+ * When an applied constraint like `Monoid (m a)` creates a kv-TCon `$kv:m:100(a)`
821
+ * for the return/body type, but `TypeRep m` in the parameters uses a bare
822
+ * TVar('m', 100), the shared varId creates circularity during unification.
823
+ * This function fixes `TypeRep(TVar('m', 100))` → `TypeRep($kv:m:100(a))`.
824
+ */
825
+ function fixTypeRepKvVars(t, kvApps) {
826
+ return mapType(t, node => {
827
+ if (node.tag === 'TCon' && node.name === types_1.T_TYPEREP && node.args.length === 1 && node.args[0].tag === 'TVar') {
828
+ const kvApp = kvApps.get(node.args[0].id);
829
+ if (kvApp)
830
+ return (0, types_1.tCon)(types_1.T_TYPEREP, [kvApp]);
831
+ }
832
+ return undefined;
833
+ });
834
+ }
835
+ // ---------------------------------------------------------------------------
836
+ // Function-type decomposition
837
+ // ---------------------------------------------------------------------------
838
+ /**
839
+ * Extract individual parameter types from a function type.
840
+ * (a, b) -> c → [a, b]
841
+ * a -> b → [a]
842
+ * non-TFun → []
843
+ */
844
+ function extractParamList(t) {
845
+ if (t.tag !== 'TFun')
846
+ return [];
847
+ if (t.param.tag === 'TCon' && t.param.name === types_1.T_TUPLE)
848
+ return t.param.args;
849
+ return [t.param];
850
+ }
851
+ /**
852
+ * Discriminate a single overloaded-branch parameter against a concrete
853
+ * argument type, for the purpose of overload SELECTION and signature-help
854
+ * filtering. This is a *discriminator*, not a unifier: it answers "could
855
+ * this argument plausibly have been meant for this parameter, and if so how
856
+ * precisely does it match?" — without the lenient field-merging that ordinary
857
+ * record unification performs (which would let `{ name }` silently satisfy a
858
+ * `{ nam }` parameter and so make every record overload ambiguous).
859
+ *
860
+ * 'reject' — provably the wrong branch: both sides are closed records and
861
+ * the parameter requires a field the argument does not provide.
862
+ * 'exact' — a precise match: equal closed-record field sets, or matching
863
+ * nominal record aliases.
864
+ * 'neutral' — no discriminating signal (open records, label-keyed records,
865
+ * type variables, non-record types, or a structural superset);
866
+ * the caller should fall back to ordinary unification.
867
+ */
868
+ function discriminateRecordArg(argT, paramT) {
869
+ if (argT.tag !== 'TRecord' || paramT.tag !== 'TRecord')
870
+ return 'neutral';
871
+ // Open or label-keyed records carry a row tail / wildcard key and are
872
+ // intentionally lenient — never discriminate on them.
873
+ if (argT.rest || paramT.rest)
874
+ return 'neutral';
875
+ if ((argT.labelFields && argT.labelFields.length) ||
876
+ (paramT.labelFields && paramT.labelFields.length))
877
+ return 'neutral';
878
+ const paramKeys = Object.keys(paramT.fields);
879
+ // A closed parameter requires every one of its fields; if the argument is
880
+ // missing one, it cannot have been meant for this branch.
881
+ for (const pk of paramKeys) {
882
+ if (!(pk in argT.fields))
883
+ return 'reject';
884
+ }
885
+ const argKeys = Object.keys(argT.fields);
886
+ // Nominal match on a shared alias is the strongest precise signal.
887
+ if (argT.alias && paramT.alias && argT.alias === paramT.alias)
888
+ return 'exact';
889
+ // Equal field-name sets → a precise structural match.
890
+ if (argKeys.length === paramKeys.length)
891
+ return 'exact';
892
+ // Argument is a structural superset (has extra fields): compatible, but not
893
+ // a precise discriminator on its own.
894
+ return 'neutral';
895
+ }
896
+ /**
897
+ * Rename kind-variable TCon names in a type tree.
898
+ * Used during instantiation to give kv names fresh IDs.
899
+ */
900
+ function renameKvInType(t, kvMap) {
901
+ return mapType(t, n => (n.tag === 'TCon' && kvMap.has(n.name))
902
+ ? (0, types_1.tCon)(kvMap.get(n.name), n.args.map(a => renameKvInType(a, kvMap)))
903
+ : undefined);
904
+ }
905
+ //# sourceMappingURL=typeUtils.js.map