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,1853 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Hindley-Milner Type System — Core Types
4
+ //
5
+ // WHAT THIS FILE DOES (in plain language)
6
+ // ---------------------------------------------------------------------------
7
+ // This is the foundation of the whole type checker: it defines how a "type"
8
+ // is stored in memory. Everything else in the project builds on the shapes
9
+ // declared here.
10
+ //
11
+ // Think of types as labels describing what kind of value something is
12
+ // ("a Number", "a list of Strings", "a function from Number to Boolean").
13
+ // This file provides:
14
+ //
15
+ // 1. The building blocks (the "Type AST"): TVar (a placeholder for an
16
+ // unknown type), TCon (a named type like Number or Array String),
17
+ // TFun (a function type), TRecord (an object type with named fields),
18
+ // TLabel/TRow (pieces used for "open" objects). See GLOSSARY.md for
19
+ // a plain-language explanation of each term.
20
+ // 2. "Smart constructors" — small helper functions (tVar, tCon, tFun,
21
+ // tRecord, tUnion, ...) that build those blocks correctly, so no other
22
+ // file has to assemble the raw objects by hand.
23
+ // 3. Type schemes — reusable, sealed type templates for polymorphic
24
+ // definitions (e.g. `identity :: a -> a` works for ANY a).
25
+ // 4. Pretty-printing — turning a type back into the human-readable text
26
+ // shown in hover popups and error messages.
27
+ // 5. Small pure helpers for inspecting and combining types.
28
+ //
29
+ // Nothing in this file performs inference itself; it is purely the
30
+ // vocabulary that the inference engine (src/infer/) and the puzzle solver
31
+ // (src/hm/unify.ts) speak.
32
+ // ============================================================================
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.SKOLEM_PREFIX = exports.AUTO_TVAR_NAME_RE = exports.ANNOTATION_NAME_RE = exports.tAny = exports.tSpread = exports.NUMERIC_SUBTYPES = exports.tPositiveInteger = exports.tNonZeroInteger = exports.tNegativeFiniteNumber = exports.tPositiveFiniteNumber = exports.tNonZeroFiniteNumber = exports.tFiniteNumber = exports.tNonZeroValidNumber = exports.tValidNumber = exports.tNegativeNumber = exports.tPositiveNumber = exports.tNegativeInteger = exports.tNonNegativeInteger = exports.tDouble = exports.tFloat = exports.tInteger = exports.tBuffer = exports.tObject = exports.tAnyType = exports.T_ANY_TYPE = exports.tVoid = exports.tUndefined = exports.tNull = exports.tSymbol = exports.tBigInt = exports.tBool = exports.tString = exports.tNumber = exports.T_MERGE = exports.T_PICKED = exports.T_OBJECT = exports.T_FUNCTION = exports.T_TYPEREP = exports.T_BOOLEAN = exports.T_STRING = exports.T_NUMBER = exports.T_ERROR = exports.T_SPREAD_ARRAY = exports.T_UNION = exports.T_TUPLE = exports.T_ARRAY = exports.TypeVarAllocator = void 0;
35
+ exports.getActiveAllocator = getActiveAllocator;
36
+ exports.setActiveAllocator = setActiveAllocator;
37
+ exports.resetTypeVarCounter = resetTypeVarCounter;
38
+ exports.saveTypeVarCounter = saveTypeVarCounter;
39
+ exports.restoreTypeVarCounter = restoreTypeVarCounter;
40
+ exports.freshTypeVarId = freshTypeVarId;
41
+ exports.tVar = tVar;
42
+ exports.tRow = tRow;
43
+ exports.tCon = tCon;
44
+ exports.tFun = tFun;
45
+ exports.tForall = tForall;
46
+ exports.containsForall = containsForall;
47
+ exports.scheme = scheme;
48
+ exports.mono = mono;
49
+ exports.monoFrozen = monoFrozen;
50
+ exports.isTCon = isTCon;
51
+ exports.isUnion = isUnion;
52
+ exports.isTuple = isTuple;
53
+ exports.isErrorType = isErrorType;
54
+ exports.containsErrorType = containsErrorType;
55
+ exports.tStrMap = tStrMap;
56
+ exports.isAnyType = isAnyType;
57
+ exports.isNumericType = isNumericType;
58
+ exports.isNumericSubtypeOf = isNumericSubtypeOf;
59
+ exports.tArray = tArray;
60
+ exports.isSpread = isSpread;
61
+ exports.isWildcard = isWildcard;
62
+ exports.tNamedWildcard = tNamedWildcard;
63
+ exports.wildcardDisplayName = wildcardDisplayName;
64
+ exports.structuralEquals = structuralEquals;
65
+ exports.unionMemberEquivalent = unionMemberEquivalent;
66
+ exports.tUnion = tUnion;
67
+ exports.tTuple = tTuple;
68
+ exports.tMultiFun = tMultiFun;
69
+ exports.isAppliedFunction = isAppliedFunction;
70
+ exports.isAppliedObject = isAppliedObject;
71
+ exports.functionParamList = functionParamList;
72
+ exports.desugarFunctionType = desugarFunctionType;
73
+ exports.desugarObjectType = desugarObjectType;
74
+ exports.tAnyFunction = tAnyFunction;
75
+ exports.tAnyObject = tAnyObject;
76
+ exports.tRecord = tRecord;
77
+ exports.tOpenRecord = tOpenRecord;
78
+ exports.mergeRecordTypes = mergeRecordTypes;
79
+ exports.deepMergeTypes = deepMergeTypes;
80
+ exports.tLabelLit = tLabelLit;
81
+ exports.tLabelVar = tLabelVar;
82
+ exports.isLabel = isLabel;
83
+ exports.isKindVariable = isKindVariable;
84
+ exports.kvName = kvName;
85
+ exports.flattenCurriedType = flattenCurriedType;
86
+ exports.generateCurriedOverloads = generateCurriedOverloads;
87
+ exports.parseKvName = parseKvName;
88
+ exports.constraintBaseName = constraintBaseName;
89
+ exports.isSkolem = isSkolem;
90
+ exports.typeToString = typeToString;
91
+ exports.canonicalSchemeKey = canonicalSchemeKey;
92
+ exports.schemeToString = schemeToString;
93
+ exports.prettyTypeToString = prettyTypeToString;
94
+ exports.prettyTypeToStringWithContext = prettyTypeToStringWithContext;
95
+ exports.buildVarDisplayNameMap = buildVarDisplayNameMap;
96
+ exports.prettyTypeToStringPair = prettyTypeToStringPair;
97
+ exports.canonicalizeDisplayVarsByName = canonicalizeDisplayVarsByName;
98
+ exports.collectAllVarIds = collectAllVarIds;
99
+ exports.getReturnType = getReturnType;
100
+ exports.mergeReturnTypes = mergeReturnTypes;
101
+ exports.decomposeFunParams = decomposeFunParams;
102
+ exports.countFunParams = countFunParams;
103
+ exports.isNumLitName = isNumLitName;
104
+ exports.tNumLit = tNumLit;
105
+ exports.findUnknownTCons = findUnknownTCons;
106
+ exports.collectVarNames = collectVarNames;
107
+ // ---------------------------------------------------------------------------
108
+ // Type Variable Allocator — encapsulates the fresh-ID counter
109
+ //
110
+ // Plain language: every "unknown type" placeholder needs a unique serial
111
+ // number so two unknowns are never confused with each other. This class is
112
+ // the ticket machine that hands out those numbers, one at a time.
113
+ // ---------------------------------------------------------------------------
114
+ /**
115
+ * A `TypeVarAllocator` owns a monotonically-increasing counter that is used to
116
+ * generate unique type-variable IDs via {@link tVar}. Wrapping the counter in
117
+ * an instance makes it possible to run multiple inference sessions without
118
+ * sharing (and accidentally corrupting) a single global counter.
119
+ *
120
+ * For backward compatibility a module-level *active* allocator is maintained
121
+ * and all legacy free-functions (`resetTypeVarCounter`, `saveTypeVarCounter`,
122
+ * `restoreTypeVarCounter`, `freshTypeVarId`) delegate to it.
123
+ */
124
+ class TypeVarAllocator {
125
+ constructor(start = 0) {
126
+ this.nextId = start;
127
+ }
128
+ /** Reset the counter to 0 (or to a specific value). */
129
+ reset(value = 0) {
130
+ this.nextId = value;
131
+ }
132
+ /** Return the current counter value (for later {@link restore}). */
133
+ save() {
134
+ return this.nextId;
135
+ }
136
+ /** Set the counter to a previously saved value. */
137
+ restore(value) {
138
+ this.nextId = value;
139
+ }
140
+ /** Allocate and return the next unique type-variable ID. */
141
+ fresh() {
142
+ return this.nextId++;
143
+ }
144
+ }
145
+ exports.TypeVarAllocator = TypeVarAllocator;
146
+ /** The module-level allocator used by all free-standing helper functions. */
147
+ let _activeAllocator = new TypeVarAllocator();
148
+ /** Return the currently active allocator. */
149
+ function getActiveAllocator() {
150
+ return _activeAllocator;
151
+ }
152
+ /**
153
+ * Replace the active allocator. Returns the previous one so callers can
154
+ * restore it later (e.g. when an import inference finishes).
155
+ */
156
+ function setActiveAllocator(a) {
157
+ const prev = _activeAllocator;
158
+ _activeAllocator = a;
159
+ return prev;
160
+ }
161
+ // Backward-compatible free functions — delegate to the active allocator.
162
+ function resetTypeVarCounter() {
163
+ _activeAllocator.reset();
164
+ }
165
+ function saveTypeVarCounter() {
166
+ return _activeAllocator.save();
167
+ }
168
+ function restoreTypeVarCounter(value) {
169
+ _activeAllocator.restore(value);
170
+ }
171
+ function freshTypeVarId() {
172
+ return _activeAllocator.fresh();
173
+ }
174
+ // ---------------------------------------------------------------------------
175
+ // Smart constructors
176
+ //
177
+ // Plain language: helper functions that assemble the building blocks above.
178
+ // The rest of the codebase calls these instead of writing the raw objects by
179
+ // hand, so invariants (unique ids, default names) live in exactly one place.
180
+ // ---------------------------------------------------------------------------
181
+ /** Create a fresh type variable (a brand-new "unknown type" placeholder)
182
+ * with a unique id. Without an explicit name it gets an auto name like
183
+ * `t42` — the pretty-printer later renames those to `a`, `b`, `c`, … */
184
+ function tVar(name) {
185
+ const id = freshTypeVarId();
186
+ return { tag: 'TVar', id, name: name ?? `t${id}` };
187
+ }
188
+ /** Smart constructor for a fresh row-variable. Used by the parser when
189
+ * it sees `{ ...r }` with a lowercase identifier, and by destructure
190
+ * inference (`{ a, ...rest }` patterns) to allocate the row-tail. */
191
+ function tRow(name) {
192
+ const id = freshTypeVarId();
193
+ return { tag: 'TRow', id, name: name ?? `r${id}` };
194
+ }
195
+ /** Create a named type, e.g. `tCon('Number')` or `tCon('Array', [elem])`. */
196
+ function tCon(name, args = []) {
197
+ return { tag: 'TCon', name, args };
198
+ }
199
+ /** Create a function type `param -> result`. */
200
+ function tFun(param, result) {
201
+ return { tag: 'TFun', param, result };
202
+ }
203
+ /** Create a nested universal quantifier (rank-N position), e.g.
204
+ * `forall a. a -> a` as used inside `(forall a. a -> a) -> b`. */
205
+ function tForall(vars, varNames, body, constraints) {
206
+ const out = { tag: 'TForall', vars, varNames, body };
207
+ if (constraints && constraints.length > 0)
208
+ out.constraints = constraints;
209
+ return out;
210
+ }
211
+ /** Does the type contain a nested {@link TForall} anywhere? */
212
+ function containsForall(t) {
213
+ switch (t.tag) {
214
+ case 'TForall': return true;
215
+ case 'TCon': return t.args.some(containsForall);
216
+ case 'TFun': return containsForall(t.param) || containsForall(t.result);
217
+ case 'TRecord': {
218
+ for (const k in t.fields) {
219
+ if (containsForall(t.fields[k]))
220
+ return true;
221
+ }
222
+ if (t.labelFields) {
223
+ for (const lf of t.labelFields) {
224
+ if (containsForall(lf.type))
225
+ return true;
226
+ }
227
+ }
228
+ return false;
229
+ }
230
+ case 'TVar':
231
+ case 'TLabel':
232
+ case 'TRow':
233
+ return false;
234
+ }
235
+ }
236
+ /** Create a type scheme: `type` with the variable ids in `vars` sealed in
237
+ * (universally quantified — "works for any choice of these variables"). */
238
+ function scheme(vars, type) {
239
+ return { vars, type };
240
+ }
241
+ /** Create a monomorphic scheme (no quantified variables) */
242
+ function mono(type) {
243
+ return { vars: [], type };
244
+ }
245
+ /** Monomorphic scheme carrying a display-only `frozenDisplay` override. Used
246
+ * for annotated function parameters: `type` participates in body inference as
247
+ * usual, while `frozenDisplay` (the annotation) is what hover renders for the
248
+ * parameter and every reference to it. Defaults `frozenDisplay` to `type`. */
249
+ function monoFrozen(type, frozen = type) {
250
+ return { vars: [], type, frozenDisplay: frozen };
251
+ }
252
+ // ---------------------------------------------------------------------------
253
+ // Built-in type name constants (prevent typos, enable rename-refactoring)
254
+ // ---------------------------------------------------------------------------
255
+ exports.T_ARRAY = 'Array';
256
+ // Reserved (`$`-prefixed) so a user type named `Tuple` (FP-library's
257
+ // `Tuple :: (Number, Array a) -> Tuple Number a`) is never mistaken for the
258
+ // internal multi-parameter tuple.
259
+ exports.T_TUPLE = '$Tuple';
260
+ exports.T_UNION = 'Union';
261
+ exports.T_SPREAD_ARRAY = 'SpreadArray';
262
+ exports.T_ERROR = '$error';
263
+ exports.T_NUMBER = 'Number';
264
+ exports.T_STRING = 'String';
265
+ exports.T_BOOLEAN = 'Boolean';
266
+ exports.T_TYPEREP = 'TypeRep';
267
+ /** The two built-ins with mandatory children: `Function [params] result`
268
+ * and `Object k a`. Both are kept in applied `TCon` form for display but
269
+ * are pure sugar over `TFun` / `TRecord` (see `desugarFunctionType` /
270
+ * `desugarObjectType`). */
271
+ exports.T_FUNCTION = 'Function';
272
+ exports.T_OBJECT = 'Object';
273
+ /** Reserved TCon name for inline call-site record projection. A signature
274
+ * such as `[a] -> QueryTag (Picked R a)` tells the call-expression
275
+ * post-processor in `src/infer/calls.ts` to inspect the call's literal
276
+ * array argument and replace `Picked R a` with a record built from the
277
+ * array's elements (string-literal columns become row-field types,
278
+ * identifiers of `Prop T` type contribute named fields, nested calls of
279
+ * type `QueryTag YRow` resolve via the parent row's method-shadows).
280
+ * Generic — not coupled to any one library. */
281
+ exports.T_PICKED = 'Picked';
282
+ /** Reserved TCon name for structural record-union reduction. An
283
+ * annotation such as `QueryTag#concat :: QueryTag p1 r1 ~> QueryTag p2 r2 ->
284
+ * QueryTag (Merge p1 p2) (Merge r1 r2)` tells the call-expression
285
+ * post-processor in `src/infer/calls.ts` to collapse each `Merge a b`
286
+ * whose args resolve to two TRecords into a single structural-union
287
+ * record (alias-stripped). Conflicting field types are unified.
288
+ * Generic — usable by any combinator that merges row + param shapes. */
289
+ exports.T_MERGE = 'Merge';
290
+ // ---------------------------------------------------------------------------
291
+ // Type predicates (common tag+name checks used across the codebase)
292
+ // ---------------------------------------------------------------------------
293
+ /** Is `t` a TCon with the given name? */
294
+ function isTCon(t, name) {
295
+ return t.tag === 'TCon' && t.name === name;
296
+ }
297
+ /** Is `t` a Union type? (`TCon('Union', [...])`) */
298
+ function isUnion(t) {
299
+ return t.tag === 'TCon' && t.name === exports.T_UNION;
300
+ }
301
+ /** Is `t` a Tuple type? (`TCon('Tuple', [...])`) */
302
+ function isTuple(t) {
303
+ return t.tag === 'TCon' && t.name === exports.T_TUPLE;
304
+ }
305
+ /** Is `t` the `$error` sentinel produced by failed property accesses? */
306
+ function isErrorType(t) {
307
+ return t.tag === 'TCon' && t.name === exports.T_ERROR;
308
+ }
309
+ /** Does any subtree of `t` contain the `$error` sentinel? Used by hover
310
+ * to suppress display lines that have been polluted by error recovery
311
+ * poisoning (where free type variables in a failed unification are bound
312
+ * to `$error` to stop diagnostic cascades). */
313
+ function containsErrorType(t) {
314
+ if (t.tag === 'TCon' && t.name === exports.T_ERROR)
315
+ return true;
316
+ if (t.tag === 'TCon')
317
+ return (t.args ?? []).some(containsErrorType);
318
+ if (t.tag === 'TFun')
319
+ return containsErrorType(t.param) || containsErrorType(t.result);
320
+ if (t.tag === 'TRecord')
321
+ return Object.values(t.fields).some(containsErrorType);
322
+ return false;
323
+ }
324
+ // ---------------------------------------------------------------------------
325
+ // Built-in types
326
+ // ---------------------------------------------------------------------------
327
+ exports.tNumber = tCon('Number');
328
+ exports.tString = tCon('String');
329
+ exports.tBool = tCon('Boolean');
330
+ exports.tBigInt = tCon('BigInt');
331
+ exports.tSymbol = tCon('Symbol');
332
+ exports.tNull = tCon('Null');
333
+ exports.tUndefined = tCon('Undefined');
334
+ exports.tVoid = tCon('Void');
335
+ // Sanctuary / HM built-in types
336
+ exports.T_ANY_TYPE = 'Any';
337
+ exports.tAnyType = tCon(exports.T_ANY_TYPE);
338
+ exports.tObject = tCon('Object');
339
+ exports.tBuffer = tCon('Buffer');
340
+ exports.tInteger = tCon('Integer');
341
+ exports.tFloat = tCon('Float');
342
+ exports.tDouble = tCon('Double');
343
+ exports.tNonNegativeInteger = tCon('NonNegativeInteger');
344
+ exports.tNegativeInteger = tCon('NegativeInteger');
345
+ exports.tPositiveNumber = tCon('PositiveNumber');
346
+ exports.tNegativeNumber = tCon('NegativeNumber');
347
+ exports.tValidNumber = tCon('ValidNumber');
348
+ exports.tNonZeroValidNumber = tCon('NonZeroValidNumber');
349
+ exports.tFiniteNumber = tCon('FiniteNumber');
350
+ exports.tNonZeroFiniteNumber = tCon('NonZeroFiniteNumber');
351
+ exports.tPositiveFiniteNumber = tCon('PositiveFiniteNumber');
352
+ exports.tNegativeFiniteNumber = tCon('NegativeFiniteNumber');
353
+ exports.tNonZeroInteger = tCon('NonZeroInteger');
354
+ exports.tPositiveInteger = tCon('PositiveInteger');
355
+ function tStrMap(val) {
356
+ return tCon('StrMap', [val]);
357
+ }
358
+ /** Check if a type is the `Any` top type (unifies with everything, but is a real named type). */
359
+ function isAnyType(t) {
360
+ return t.tag === 'TCon' && t.name === exports.T_ANY_TYPE && t.args.length === 0;
361
+ }
362
+ /** Numeric subtypes of Number. These are Sanctuary refinement types that
363
+ * should unify with `Number` (and with each other) because JS only has a
364
+ * single `number` runtime type. */
365
+ exports.NUMERIC_SUBTYPES = new Set([
366
+ 'Integer', 'Float', 'Double', 'NonNegativeInteger', 'NegativeInteger',
367
+ 'PositiveNumber', 'NegativeNumber', 'ValidNumber', 'NonZeroValidNumber',
368
+ 'FiniteNumber', 'NonZeroFiniteNumber', 'PositiveFiniteNumber', 'NegativeFiniteNumber',
369
+ 'NonZeroInteger', 'PositiveInteger',
370
+ ]);
371
+ /** Is this type `Number` or one of its Sanctuary subtypes? */
372
+ function isNumericType(t) {
373
+ return t.tag === 'TCon' && t.args.length === 0 &&
374
+ (t.name === 'Number' || exports.NUMERIC_SUBTYPES.has(t.name));
375
+ }
376
+ /**
377
+ * Numeric subtype hierarchy (widening direction):
378
+ * NonNegativeInteger, NegativeInteger ⊂ Integer ⊂ Float ≈ Double ⊂ Number
379
+ *
380
+ * Plain language: some number types are more specific versions of others —
381
+ * every PositiveInteger is also an Integer, and every Integer is also a
382
+ * Number. This table lists, for each specific type, all the broader types
383
+ * it may safely be treated as ("widened" to).
384
+ */
385
+ const NUMERIC_SUPERTYPES = new Map([
386
+ // Integer subtypes
387
+ ['PositiveInteger', new Set(['NonNegativeInteger', 'NonZeroInteger', 'Integer', 'PositiveFiniteNumber', 'NonZeroFiniteNumber', 'FiniteNumber', 'NonZeroValidNumber', 'ValidNumber', 'PositiveNumber', 'Float', 'Double', 'Number'])],
388
+ ['NonNegativeInteger', new Set(['Integer', 'FiniteNumber', 'ValidNumber', 'Float', 'Double', 'Number'])],
389
+ ['NegativeInteger', new Set(['NonZeroInteger', 'Integer', 'NegativeFiniteNumber', 'NonZeroFiniteNumber', 'FiniteNumber', 'NonZeroValidNumber', 'ValidNumber', 'NegativeNumber', 'Float', 'Double', 'Number'])],
390
+ ['NonZeroInteger', new Set(['Integer', 'NonZeroFiniteNumber', 'FiniteNumber', 'NonZeroValidNumber', 'ValidNumber', 'Float', 'Double', 'Number'])],
391
+ ['Integer', new Set(['FiniteNumber', 'ValidNumber', 'Float', 'Double', 'Number'])],
392
+ // FiniteNumber subtypes
393
+ ['PositiveFiniteNumber', new Set(['NonZeroFiniteNumber', 'FiniteNumber', 'NonZeroValidNumber', 'ValidNumber', 'PositiveNumber', 'Float', 'Double', 'Number'])],
394
+ ['NegativeFiniteNumber', new Set(['NonZeroFiniteNumber', 'FiniteNumber', 'NonZeroValidNumber', 'ValidNumber', 'NegativeNumber', 'Float', 'Double', 'Number'])],
395
+ ['NonZeroFiniteNumber', new Set(['FiniteNumber', 'NonZeroValidNumber', 'ValidNumber', 'Float', 'Double', 'Number'])],
396
+ ['FiniteNumber', new Set(['ValidNumber', 'Float', 'Double', 'Number'])],
397
+ // ValidNumber subtypes
398
+ ['NonZeroValidNumber', new Set(['ValidNumber', 'Float', 'Double', 'Number'])],
399
+ ['ValidNumber', new Set(['Float', 'Double', 'Number'])],
400
+ // Number subtypes
401
+ ['PositiveNumber', new Set(['Float', 'Double', 'Number'])],
402
+ ['NegativeNumber', new Set(['Float', 'Double', 'Number'])],
403
+ ['Float', new Set(['Double', 'Number'])],
404
+ ['Double', new Set(['Float', 'Number'])],
405
+ ]);
406
+ /** May the numeric type named `sub` be safely treated as `sup`?
407
+ * E.g. `isNumericSubtypeOf('Integer', 'Number')` → true. */
408
+ function isNumericSubtypeOf(sub, sup) {
409
+ if (sub === sup)
410
+ return true;
411
+ return NUMERIC_SUPERTYPES.get(sub)?.has(sup) ?? false;
412
+ }
413
+ /** Create an array type `[elem]` — "a list whose elements are all `elem`". */
414
+ function tArray(elem) {
415
+ return tCon(exports.T_ARRAY, [elem]);
416
+ }
417
+ /** A spread/variadic marker in tuple types: (a, ..., z) */
418
+ exports.tSpread = tCon('...');
419
+ /** Check if a type is a spread marker. */
420
+ function isSpread(t) {
421
+ return t.tag === 'TCon' && t.name === '...' && t.args.length === 0;
422
+ }
423
+ /** A wildcard type that unifies with anything (no substitution produced). */
424
+ exports.tAny = tCon('*');
425
+ /** Wildcard prefix for named wildcards: '*:name' */
426
+ const WILDCARD_PREFIX = '*';
427
+ /** Check if a type is a wildcard (either bare '*' or named '*:name'). */
428
+ function isWildcard(t) {
429
+ return t.tag === 'TCon' && t.name.startsWith(WILDCARD_PREFIX) && t.args.length === 0;
430
+ }
431
+ /** Create a named wildcard for a particular annotation var name. */
432
+ function tNamedWildcard(varName) {
433
+ return tCon(`*:${varName}`);
434
+ }
435
+ /** Extract the display name from a wildcard type. Returns the var name
436
+ * for named wildcards, or '*' for the bare wildcard. */
437
+ function wildcardDisplayName(t) {
438
+ if (t.tag === 'TCon' && t.name.startsWith('*:')) {
439
+ return t.name.slice(2);
440
+ }
441
+ return '*';
442
+ }
443
+ /** Structural equality check: are `a` and `b` the exact same type, compared
444
+ * piece by piece? ("Structural" = we compare the tree contents, not object
445
+ * identity.) O(tree size) but avoids allocating a string representation. */
446
+ function structuralEquals(a, b) {
447
+ if (a === b)
448
+ return true;
449
+ if (a.tag !== b.tag)
450
+ return false;
451
+ switch (a.tag) {
452
+ case 'TVar': return a.id === b.id;
453
+ case 'TCon': {
454
+ const bc = b;
455
+ return a.name === bc.name && a.args.length === bc.args.length &&
456
+ a.args.every((arg, i) => structuralEquals(arg, bc.args[i]));
457
+ }
458
+ case 'TFun': {
459
+ const bf = b;
460
+ return structuralEquals(a.param, bf.param) && structuralEquals(a.result, bf.result);
461
+ }
462
+ case 'TRecord': {
463
+ const br = b;
464
+ const aKeys = Object.keys(a.fields);
465
+ const bKeys = Object.keys(br.fields);
466
+ const sameRest = (a.rest === undefined && br.rest === undefined) ||
467
+ (a.rest !== undefined && br.rest !== undefined && a.rest.id === br.rest.id);
468
+ // Nominal aliases (e.g. `CaregiverRow` vs `EmployeeRow`, both
469
+ // expanding to `{ id :: Number }`) must remain distinct in
470
+ // structural comparisons — otherwise union dedup in `tUnion`
471
+ // collapses `Picked CaregiverRow a` and `Picked EmployeeRow a`
472
+ // into a single member, making subsequent relation-validation
473
+ // see only one of the two rows as "valid".
474
+ if (a.alias !== br.alias)
475
+ return false;
476
+ if (a.pickedFrom !== br.pickedFrom)
477
+ return false;
478
+ return sameRest && aKeys.length === bKeys.length &&
479
+ aKeys.every(k => k in br.fields && structuralEquals(a.fields[k], br.fields[k]));
480
+ }
481
+ case 'TLabel': {
482
+ const bl = b;
483
+ if (a.kind !== bl.kind)
484
+ return false;
485
+ if (a.kind === 'lit')
486
+ return a.value === bl.value;
487
+ return a.id === bl.id;
488
+ }
489
+ case 'TRow': return a.id === b.id;
490
+ case 'TForall': {
491
+ // TForall nodes are created once per annotation and shared by
492
+ // reference, so strict comparison (same binder ids + same body) is
493
+ // sufficient here. Alpha-equivalence across DIFFERENT annotations is
494
+ // handled during unification (binder renaming in unifyCore).
495
+ const bq = b;
496
+ return a.vars.length === bq.vars.length &&
497
+ a.vars.every((v, i) => v === bq.vars[i]) &&
498
+ structuralEquals(a.body, bq.body);
499
+ }
500
+ }
501
+ }
502
+ /** Like {@link structuralEquals}, but two UNBOUND empty-array element variables
503
+ * (see {@link TVar.emptyArray}) compare EQUAL regardless of their id. Used
504
+ * ONLY by {@link tUnion} dedup so union members that differ solely in a fresh
505
+ * empty-array element var collapse to a single member. Kept separate from
506
+ * `structuralEquals` to avoid relaxing equality anywhere else (occurs-checks,
507
+ * general inference comparisons). */
508
+ function unionMemberEquivalent(a, b) {
509
+ if (a === b)
510
+ return true;
511
+ if (a.tag !== b.tag)
512
+ return false;
513
+ switch (a.tag) {
514
+ case 'TVar': {
515
+ const bv = b;
516
+ if (a.id === bv.id)
517
+ return true;
518
+ return a.emptyArray === true && bv.emptyArray === true;
519
+ }
520
+ case 'TCon': {
521
+ const bc = b;
522
+ return a.name === bc.name && a.args.length === bc.args.length &&
523
+ a.args.every((arg, i) => unionMemberEquivalent(arg, bc.args[i]));
524
+ }
525
+ case 'TFun': {
526
+ const bf = b;
527
+ return unionMemberEquivalent(a.param, bf.param) && unionMemberEquivalent(a.result, bf.result);
528
+ }
529
+ case 'TRecord': {
530
+ const br = b;
531
+ const aKeys = Object.keys(a.fields);
532
+ const bKeys = Object.keys(br.fields);
533
+ const sameRest = (a.rest === undefined && br.rest === undefined) ||
534
+ (a.rest !== undefined && br.rest !== undefined && a.rest.id === br.rest.id);
535
+ if (a.alias !== br.alias)
536
+ return false;
537
+ if (a.pickedFrom !== br.pickedFrom)
538
+ return false;
539
+ return sameRest && aKeys.length === bKeys.length &&
540
+ aKeys.every(k => k in br.fields && unionMemberEquivalent(a.fields[k], br.fields[k]));
541
+ }
542
+ case 'TLabel': {
543
+ const bl = b;
544
+ if (a.kind !== bl.kind)
545
+ return false;
546
+ if (a.kind === 'lit')
547
+ return a.value === bl.value;
548
+ return a.id === bl.id;
549
+ }
550
+ case 'TRow': return a.id === b.id;
551
+ case 'TForall': {
552
+ const bq = b;
553
+ return a.vars.length === bq.vars.length &&
554
+ a.vars.every((v, i) => v === bq.vars[i]) &&
555
+ unionMemberEquivalent(a.body, bq.body);
556
+ }
557
+ }
558
+ }
559
+ /**
560
+ * Build a union type (`Number | String | …`) from a list of members.
561
+ *
562
+ * Plain language: a union means "the value is ONE of these types". This
563
+ * builder does three jobs so unions stay small and predictable:
564
+ * 1. flattens unions nested inside unions,
565
+ * 2. removes duplicate members,
566
+ * 3. sorts the members into a canonical order so the same set of types
567
+ * always prints identically.
568
+ * A single-member union collapses to just that member.
569
+ */
570
+ function tUnion(types, opts) {
571
+ // Defensive cap: structural deduplication below is O(n²); on
572
+ // pathological input (auto-union runaway, malformed annotation, ...)
573
+ // an unbounded `types` array would freeze the language server.
574
+ // Real-world query-builder Selector unions can exceed 32 (cols + Prop a +
575
+ // 20+ QueryTag X + 20+ Table X + Limit + Offset + SQLTag a), so the
576
+ // cap is set generously while still bounding worst-case work.
577
+ const MAX_UNION_MEMBERS = 256;
578
+ // Flatten nested unions and deduplicate members structurally. Flattening
579
+ // is essential: members built via substitution/instantiation of a
580
+ // polymorphic result (e.g. Array.concat `[a | b]` where a/b are themselves
581
+ // unions) arrive as nested T_UNION nodes. Without flattening, two nested
582
+ // unions are compared as opaque members and duplicates survive
583
+ // (e.g. `Number | String | Number | Boolean`).
584
+ const unique = [];
585
+ let capped = false;
586
+ let absorbed = false;
587
+ const addMember = (t) => {
588
+ if (capped || absorbed)
589
+ return;
590
+ if (t.tag === 'TCon' && t.name === exports.T_UNION) {
591
+ for (const m of t.args)
592
+ addMember(m);
593
+ return;
594
+ }
595
+ // A bare wildcard absorbs the whole union: `X | *` ≡ `*` (the author
596
+ // explicitly does not care). Annotation style from task libraries
597
+ // (`fork :: (…) -> * | (() -> ())`) would otherwise survive as a
598
+ // union whose members fail downstream checks ("not callable").
599
+ // NAMED wildcards (`*:name`) carry identity and are NOT absorbed.
600
+ if (t.tag === 'TCon' && t.name === WILDCARD_PREFIX && t.args.length === 0) {
601
+ absorbed = true;
602
+ return;
603
+ }
604
+ if (!unique.some(u => unionMemberEquivalent(u, t))) {
605
+ unique.push(t);
606
+ if (unique.length >= MAX_UNION_MEMBERS)
607
+ capped = true;
608
+ }
609
+ };
610
+ for (const t of types) {
611
+ addMember(t);
612
+ if (capped || absorbed)
613
+ break;
614
+ }
615
+ if (absorbed)
616
+ return exports.tAny;
617
+ if (unique.length === 1)
618
+ return unique[0];
619
+ if (unique.length === 0)
620
+ return types[0];
621
+ // An OVERLOAD SET (repeated `name ::` annotations) keeps declaration order:
622
+ // overload resolution tries branches in that order and the first that
623
+ // unifies (and satisfies its constraints) wins — README › Overloading.
624
+ // Every other union is sorted canonically below.
625
+ if (opts?.overloadSet)
626
+ return { tag: 'TCon', name: exports.T_UNION, args: unique, overloadSet: true };
627
+ // Canonical member ordering: sort lexicographically by rendered type so
628
+ // that the *same set* of members always renders identically regardless of
629
+ // the construction order (`mergeUnion(a, b)` vs `mergeUnion(b, a)`,
630
+ // different inference paths, etc.). Array.sort is stable (ES2019+), so
631
+ // members that stringify equally keep their relative encounter order.
632
+ // Decorate-sort-undecorate: render each member once instead of on every
633
+ // comparison (typeToString is expensive on deep types).
634
+ const decorated = unique.map((t, i) => ({ t, key: typeToString(t), i }));
635
+ decorated.sort((a, b) => {
636
+ const c = a.key.localeCompare(b.key);
637
+ return c !== 0 ? c : a.i - b.i;
638
+ });
639
+ return tCon(exports.T_UNION, decorated.map(d => d.t));
640
+ }
641
+ /** A tuple type for multi-parameter functions: (A, B) -> C */
642
+ function tTuple(types) {
643
+ return tCon(exports.T_TUPLE, types);
644
+ }
645
+ /**
646
+ * Build a function type from parameter types and a return type.
647
+ * Single param: A -> R
648
+ * Multi param: (A, B) -> R (uses Tuple internally)
649
+ */
650
+ function tMultiFun(params, result) {
651
+ if (params.length === 0)
652
+ return result;
653
+ if (params.length === 1)
654
+ return tFun(params[0], result);
655
+ return tFun(tTuple(params), result);
656
+ }
657
+ // ---------------------------------------------------------------------------
658
+ // Applied built-in sugar: `Function [params] result` and `Object k a`
659
+ //
660
+ // `Function` and `Object` carry two mandatory children. They stay in their
661
+ // applied `TCon` form for DISPLAY, but are pure sugar over `TFun` / `TRecord`:
662
+ // • `Function [x] a` ≡ `x -> a`
663
+ // • `Function [x, y] a` ≡ `(x, y) -> a`
664
+ // • `Function [] a` ≡ `() -> a`
665
+ // • `Object k a` ≡ `{ [k] :: a }`
666
+ // Unification (src/hm/unify.ts) and the duplicate-overload key
667
+ // (`normalizeOpenObjectsForKey`) desugar them on the fly so the surface form
668
+ // never has to be reconstructed.
669
+ // ---------------------------------------------------------------------------
670
+ /** Is `t` an applied `Function [params] result` (exactly two children)? */
671
+ function isAppliedFunction(t) {
672
+ return t.tag === 'TCon' && t.name === exports.T_FUNCTION && t.args.length === 2;
673
+ }
674
+ /** Is `t` an applied `Object k a` (exactly two children)? */
675
+ function isAppliedObject(t) {
676
+ return t.tag === 'TCon' && t.name === exports.T_OBJECT && t.args.length === 2;
677
+ }
678
+ /** Extract the positional parameter list from a `Function` first child,
679
+ * which must be array-like (`[x]` → Array, `[x, y]` → SpreadArray, `[]` →
680
+ * strict-empty Array). Returns `null` when the child is not array-like — a
681
+ * malformed annotation that the validator reports separately. */
682
+ function functionParamList(params) {
683
+ if (params.tag === 'TCon' && params.name === exports.T_ARRAY && params.args.length === 1) {
684
+ return params.strictEmpty === true ? [] : [params.args[0]];
685
+ }
686
+ if (params.tag === 'TCon' && params.name === exports.T_SPREAD_ARRAY) {
687
+ return params.args.slice();
688
+ }
689
+ return null;
690
+ }
691
+ /** Desugar `Function [params] result` to the equivalent `TFun`. */
692
+ function desugarFunctionType(params, result) {
693
+ const list = functionParamList(params);
694
+ // Lenient fallback: a non-array first child is invalid (flagged by the
695
+ // validator) — treat the whole child as a single parameter so unification
696
+ // still has something structural to work with.
697
+ if (list === null)
698
+ return tFun(params, result);
699
+ if (list.length === 0)
700
+ return tFun(exports.tVoid, result);
701
+ return tMultiFun(list, result);
702
+ }
703
+ /** Desugar `Object k a` to the equivalent `{ [k] :: a }` record. */
704
+ function desugarObjectType(key, val) {
705
+ if (key.tag === 'TLabel') {
706
+ return { tag: 'TRecord', fields: {}, labelFields: [{ label: key, type: val }] };
707
+ }
708
+ // Defensive: a non-label key (malformed) → an arbitrary open object.
709
+ return { tag: 'TRecord', fields: {}, rest: tVar() };
710
+ }
711
+ /** Canonical opaque "any function" — `Function [a] b` with fresh vars. */
712
+ function tAnyFunction() {
713
+ return tCon(exports.T_FUNCTION, [tArray(tVar()), tVar()]);
714
+ }
715
+ /** Canonical opaque "any object" — `Object k a` with a fresh label + value. */
716
+ function tAnyObject() {
717
+ return tCon(exports.T_OBJECT, [tLabelVar(), tVar()]);
718
+ }
719
+ /** A record type, e.g. `{ name :: String, age :: Number }` */
720
+ function tRecord(fields, alias) {
721
+ return alias ? { tag: 'TRecord', fields, alias } : { tag: 'TRecord', fields };
722
+ }
723
+ /** An open (row-polymorphic) record `{ field1 :: T1 | r }`. The optional
724
+ * `rest` argument lets callers reuse an existing row variable (for
725
+ * destructuring patterns where the same row is shared between the
726
+ * parameter and the `rest` binding); when omitted, a fresh TVar is
727
+ * allocated. */
728
+ function tOpenRecord(fields, rest) {
729
+ return { tag: 'TRecord', fields, rest: rest ?? tVar() };
730
+ }
731
+ /**
732
+ * Deep-merge two record types the way `{ ...a, ...b }` spreads them: fields
733
+ * present in only one side are carried over; fields present in BOTH are
734
+ * combined — recursively merged when both are records, otherwise unioned
735
+ * (`Number | String`). Overlapping keys therefore appear exactly once.
736
+ *
737
+ * `labelFields` (index signatures) are concatenated, and the result stays
738
+ * open when either input is open (its row variable is preserved). Inputs
739
+ * are assumed to be already substitution-applied by the caller.
740
+ */
741
+ function mergeRecordTypes(a, b) {
742
+ const fields = { ...a.fields };
743
+ for (const k of Object.keys(b.fields)) {
744
+ const incoming = b.fields[k];
745
+ if (k in fields) {
746
+ fields[k] = deepMergeTypes(fields[k], incoming);
747
+ }
748
+ else {
749
+ fields[k] = incoming;
750
+ }
751
+ }
752
+ const out = { tag: 'TRecord', fields };
753
+ const labelFields = [...(a.labelFields ?? []), ...(b.labelFields ?? [])];
754
+ if (labelFields.length > 0)
755
+ out.labelFields = labelFields;
756
+ // Result is open when either operand was open; reuse b's row first so the
757
+ // "latest spread" row variable drives further absorption.
758
+ const rest = b.rest ?? a.rest;
759
+ if (rest)
760
+ out.rest = rest;
761
+ return out;
762
+ }
763
+ /**
764
+ * Deep-merge two arbitrary types for `{ ...a, ...b }`-style spreads / `Merge`
765
+ * marker reduction. This is the single shared primitive every merge site
766
+ * routes through so overlapping keys are combined consistently:
767
+ *
768
+ * • both records → field-wise `mergeRecordTypes` (recurses here)
769
+ * • same real container TCon → merge arg-wise, so `[String]` + `[Number]`
770
+ * becomes `[String | Number]` and `[{x::A}]` + `[{x::B}]` becomes
771
+ * `[{x :: A | B}]`. Structural markers (Union / Merge / Tuple / TypeRep /
772
+ * Picked / SpreadArray) are NOT treated as containers — merging their
773
+ * positional args would be meaningless — so they fall through to a union.
774
+ * • structurally identical → either side
775
+ * • anything else → `A | B`
776
+ */
777
+ function deepMergeTypes(a, b) {
778
+ if (a.tag === 'TRecord' && b.tag === 'TRecord') {
779
+ return mergeRecordTypes(a, b);
780
+ }
781
+ if (a.tag === 'TCon' && b.tag === 'TCon' &&
782
+ a.name === b.name &&
783
+ a.args.length === b.args.length &&
784
+ a.args.length > 0 &&
785
+ !DEEP_MERGE_OPAQUE_CONS.has(a.name)) {
786
+ return tCon(a.name, a.args.map((arg, i) => deepMergeTypes(arg, b.args[i])));
787
+ }
788
+ if (structuralEquals(a, b))
789
+ return a;
790
+ return tUnion([a, b]);
791
+ }
792
+ /** Constructors whose positional args are NOT container element types, so
793
+ * `deepMergeTypes` must union them rather than merge arg-wise. */
794
+ const DEEP_MERGE_OPAQUE_CONS = new Set([
795
+ exports.T_UNION, exports.T_MERGE, exports.T_TUPLE, exports.T_TYPEREP, exports.T_PICKED, exports.T_SPREAD_ARRAY,
796
+ ]);
797
+ // ---------------------------------------------------------------------------
798
+ // Label smart constructors
799
+ // ---------------------------------------------------------------------------
800
+ /** A concrete field-label literal, e.g. `tLabelLit('x')`. */
801
+ function tLabelLit(value) {
802
+ return { tag: 'TLabel', kind: 'lit', value };
803
+ }
804
+ /** A fresh label variable, optionally with a display name. */
805
+ function tLabelVar(name) {
806
+ const id = freshTypeVarId();
807
+ return { tag: 'TLabel', kind: 'var', id, name: name ?? `k${id}` };
808
+ }
809
+ /** True when `t` is a label type. */
810
+ function isLabel(t) {
811
+ return t.tag === 'TLabel';
812
+ }
813
+ // ---------------------------------------------------------------------------
814
+ // Kind-variable helpers
815
+ // A kind variable is a type variable used as a type constructor (higher-kinded).
816
+ // In TCon names it's encoded as "$kv:name:id", e.g. "$kv:f:42".
817
+ // ---------------------------------------------------------------------------
818
+ const KV_PREFIX = '$kv:';
819
+ /** Check whether a TCon name represents a kind variable. */
820
+ function isKindVariable(name) {
821
+ return name.startsWith(KV_PREFIX);
822
+ }
823
+ /** Create a kind-variable TCon name from the var name and id. */
824
+ function kvName(varName, varId) {
825
+ return `${KV_PREFIX}${varName}:${varId}`;
826
+ }
827
+ // ---------------------------------------------------------------------------
828
+ // Curry overload generation
829
+ // ---------------------------------------------------------------------------
830
+ /**
831
+ * Flatten a curried function type into its individual parameter types and final result.
832
+ * e.g. A -> B -> C -> R → { params: [A, B, C], result: R }
833
+ * e.g. (Tuple [A, B]) -> R → { params: [A, B], result: R } (from multi-param)
834
+ */
835
+ function flattenCurriedType(t) {
836
+ const params = [];
837
+ let current = t;
838
+ while (current.tag === 'TFun') {
839
+ params.push(current.param);
840
+ current = current.result;
841
+ }
842
+ return { params, result: current };
843
+ }
844
+ /**
845
+ * Generate all curried overload types for a set of parameters and a result type.
846
+ * For params [A, B, C] and result R, generates all ordered partitions:
847
+ * - A -> B -> C -> R (fully curried)
848
+ * - (A, B) -> C -> R
849
+ * - A -> (B, C) -> R
850
+ * - (A, B, C) -> R (original uncurried)
851
+ *
852
+ * The number of overloads is 2^(n-1) where n = params.length.
853
+ */
854
+ function generateCurriedOverloads(params, result) {
855
+ if (params.length === 0)
856
+ return [result];
857
+ if (params.length === 1)
858
+ return [tFun(params[0], result)];
859
+ const overloads = [];
860
+ const numGaps = params.length - 1;
861
+ // Each bit pattern represents cuts between adjacent params.
862
+ // bit i = 1 means there is a cut between param[i] and param[i+1].
863
+ for (let mask = 0; mask < (1 << numGaps); mask++) {
864
+ const groups = [[]];
865
+ groups[0].push(params[0]);
866
+ for (let i = 0; i < numGaps; i++) {
867
+ if (mask & (1 << i)) {
868
+ // Cut: start new group
869
+ groups.push([params[i + 1]]);
870
+ }
871
+ else {
872
+ // No cut: add to current group
873
+ groups[groups.length - 1].push(params[i + 1]);
874
+ }
875
+ }
876
+ // Build curried function type from groups (right to left)
877
+ let type = result;
878
+ for (let j = groups.length - 1; j >= 0; j--) {
879
+ const group = groups[j];
880
+ const param = group.length === 1 ? group[0] : tTuple(group);
881
+ type = tFun(param, type);
882
+ }
883
+ overloads.push(type);
884
+ }
885
+ return overloads;
886
+ }
887
+ /** Parse a kind-variable TCon name. Returns null if not a kv name. */
888
+ // Hot path (every `Substitution.apply` on a TCon): reject ordinary names on
889
+ // their first character, and memoise parsed kv names. The returned objects
890
+ // are shared and must not be mutated.
891
+ const kvParseCache = new Map();
892
+ function parseKvName(name) {
893
+ if (name.charCodeAt(0) !== 36 /* '$' */ || !name.startsWith(KV_PREFIX))
894
+ return null;
895
+ const cached = kvParseCache.get(name);
896
+ if (cached !== undefined)
897
+ return cached;
898
+ const rest = name.slice(KV_PREFIX.length);
899
+ const colonIdx = rest.lastIndexOf(':');
900
+ let result = null;
901
+ if (colonIdx >= 0) {
902
+ const varName = rest.slice(0, colonIdx);
903
+ const varId = parseInt(rest.slice(colonIdx + 1), 10);
904
+ if (!isNaN(varId))
905
+ result = Object.freeze({ varName, varId });
906
+ }
907
+ if (kvParseCache.size > 50000)
908
+ kvParseCache.clear(); // bound memory in long LSP sessions
909
+ kvParseCache.set(name, result);
910
+ return result;
911
+ }
912
+ /**
913
+ * Extract the base constraint name from a possibly-applied constraint string.
914
+ * "Monoid (f a)" → "Monoid", "Semigroup" → "Semigroup".
915
+ */
916
+ function constraintBaseName(name) {
917
+ const spaceIdx = name.indexOf(' ');
918
+ return spaceIdx >= 0 && name.includes('(') ? name.slice(0, spaceIdx) : name;
919
+ }
920
+ // ---------------------------------------------------------------------------
921
+ // Regex constants (shared across codebase)
922
+ // ---------------------------------------------------------------------------
923
+ /** Matches single lowercase annotation var names (a, b, c, ... z). */
924
+ exports.ANNOTATION_NAME_RE = /^[a-z]$/;
925
+ /** Matches auto-generated type var names (t0, t1, ...). */
926
+ exports.AUTO_TVAR_NAME_RE = /^t\d+$/;
927
+ /** Prefix used for rigid skolem TCon names (e.g. `§0`, `§1`). A skolem is a
928
+ * rigid type constant standing in for a universally-quantified annotation
929
+ * variable while a function body is checked against its signature. */
930
+ exports.SKOLEM_PREFIX = '§';
931
+ /** True when a type is a rigid skolem constant (a `§N` TCon). */
932
+ function isSkolem(t) {
933
+ return t.tag === 'TCon' && t.name.startsWith(exports.SKOLEM_PREFIX);
934
+ }
935
+ // ---------------------------------------------------------------------------
936
+ // Pretty-printing
937
+ //
938
+ // Plain language: turning a type tree back into readable text such as
939
+ // `Array (Number | String) -> Boolean`. This is what users see in hover
940
+ // popups, completions and error messages, so a lot of care goes into
941
+ // parenthesisation (only where needed) and into giving placeholder
942
+ // variables friendly letters (a, b, c, …) instead of internal names (t42).
943
+ // ---------------------------------------------------------------------------
944
+ /** Does a type need parens when used as a juxtaposition arg?
945
+ * ("Juxtaposition" = type application by adjacency, e.g. the `a` in
946
+ * `Maybe a`. A structured arg like `Maybe (a -> b)` needs the parens.) */
947
+ function needsParens(t) {
948
+ if (t.tag === 'TFun')
949
+ return true;
950
+ if (t.tag === 'TCon' && t.name === exports.T_UNION)
951
+ return true;
952
+ // `Object k a` renders as a record `{ [k] :: a }` — like Array/Tuple it never
953
+ // needs wrapping parens as a juxtaposition arg.
954
+ if (t.tag === 'TCon' && t.args.length > 0 && t.name !== exports.T_ARRAY && t.name !== exports.T_TUPLE && t.name !== exports.T_SPREAD_ARRAY && !isAppliedObject(t))
955
+ return true;
956
+ return false;
957
+ }
958
+ /** Does a union member need parens to disambiguate `|` precedence? */
959
+ function unionMemberNeedsParens(t) {
960
+ // `|` binds tighter than `->`, so `A | B -> C` parses as `(A | B) -> C`.
961
+ // A function as union member therefore needs parens: `A | (B -> C)`.
962
+ // `Function […] …` renders as an arrow, so it needs parens too.
963
+ return t.tag === 'TFun' || t.tag === 'TForall' || isAppliedFunction(t);
964
+ }
965
+ /** Does a function param need parens to keep `->` right-associative & unambiguous? */
966
+ function funParamNeedsParens(t) {
967
+ // Nested function: `(a -> b) -> c` differs from `a -> b -> c`.
968
+ // Union as param needs NO parens: `A | B -> C` already parses as
969
+ // `(A | B) -> C` since `|` binds tighter than `->`. Adding parens
970
+ // here would silently rewrite what the user wrote.
971
+ // `Function […] …` renders as an arrow, so it needs parens like TFun.
972
+ // A nested quantifier extends maximally right, so `(forall a. a -> a) -> b`
973
+ // needs parens around the forall in param position.
974
+ return t.tag === 'TFun' || t.tag === 'TForall' || isAppliedFunction(t);
975
+ }
976
+ /**
977
+ * Shared implementation for type-to-string conversion.
978
+ * When `names` is provided, TVar ids are resolved through the map (for pretty-printing).
979
+ * When omitted, the TVar's own `.name` property is used.
980
+ */
981
+ function typeToStringImpl(t, names, singletonIds) {
982
+ switch (t.tag) {
983
+ case 'TVar':
984
+ return names?.get(t.id) ?? t.name;
985
+ case 'TCon': {
986
+ const kv = parseKvName(t.name);
987
+ const displayName = kv ? (names?.get(kv.varId) ?? kv.varName) : t.name;
988
+ if (t.name === 'Void' && t.args.length === 0)
989
+ return '()';
990
+ // Render the `$error` poison sentinel as a wildcard placeholder so
991
+ // it never leaks into hover / signature-help output. The diagnostic
992
+ // for the underlying unification failure is emitted separately.
993
+ if (t.name === exports.T_ERROR)
994
+ return '_';
995
+ if (isWildcard(t))
996
+ return wildcardDisplayName(t);
997
+ if (t.name === exports.T_UNION) {
998
+ return t.args
999
+ .map(a => unionMemberNeedsParens(a)
1000
+ ? `(${typeToStringImpl(a, names, singletonIds)})`
1001
+ : typeToStringImpl(a, names, singletonIds))
1002
+ .join(' | ');
1003
+ }
1004
+ if (t.name === exports.T_ARRAY && t.args.length === 1) {
1005
+ // A strict-empty array annotation `[]` renders as `[]`.
1006
+ if (t.strictEmpty === true)
1007
+ return '[]';
1008
+ return `[${typeToStringImpl(t.args[0], names, singletonIds)}]`;
1009
+ }
1010
+ if (t.name === exports.T_SPREAD_ARRAY) {
1011
+ return `[${t.args.map(a => typeToStringImpl(a, names, singletonIds)).join(', ')}]`;
1012
+ }
1013
+ if (t.name === exports.T_TUPLE) {
1014
+ return `(${t.args.map(a => typeToStringImpl(a, names, singletonIds)).join(', ')})`;
1015
+ }
1016
+ // Spread sugar for Merge: render `Merge a b` / `Merge {x::T} a b`
1017
+ // as `{ ...a, ...b }` / `{ x :: T, ...a, ...b }` when all non-
1018
+ // record args are TVar. Anything more exotic falls through to the
1019
+ // raw `Merge ...` form.
1020
+ if (t.name === exports.T_MERGE && t.args.length > 0) {
1021
+ const segs = [];
1022
+ // Track which segments came from bare row-vars vs concrete
1023
+ // fields, so we can hide the noisy `...a` tails when at least
1024
+ // one concrete record contributed real fields (a free row-var
1025
+ // sibling adds no information in that case).
1026
+ const spreadOnly = [];
1027
+ // Track per-segment row-tail IDs so we can also drop
1028
+ // singly-occurring bare tails (their name is uninformative
1029
+ // when it doesn't bind anything elsewhere in the type).
1030
+ const segRowIds = [];
1031
+ let ok = true;
1032
+ for (const a of t.args) {
1033
+ if (a.tag === 'TVar' || a.tag === 'TRow') {
1034
+ segs.push(`...${typeToStringImpl(a, names, singletonIds)}`);
1035
+ spreadOnly.push(true);
1036
+ segRowIds.push(a.id);
1037
+ }
1038
+ else if (a.tag === 'TRecord' && !a.rest) {
1039
+ // Inline record's field strings.
1040
+ const keys = Object.keys(a.fields).filter(k => k !== 'constructor');
1041
+ for (const k of keys) {
1042
+ segs.push(`${k} :: ${typeToStringImpl(a.fields[k], names, singletonIds)}`);
1043
+ spreadOnly.push(false);
1044
+ segRowIds.push(null);
1045
+ }
1046
+ if (a.labelFields) {
1047
+ for (const { label, type: vt } of a.labelFields) {
1048
+ const labelStr = label.kind === 'lit'
1049
+ ? `'${label.value}'`
1050
+ : (names?.get(label.id) ?? label.name);
1051
+ segs.push(`[${labelStr}] :: ${typeToStringImpl(vt, names, singletonIds)}`);
1052
+ spreadOnly.push(false);
1053
+ segRowIds.push(null);
1054
+ }
1055
+ }
1056
+ }
1057
+ else {
1058
+ ok = false;
1059
+ break;
1060
+ }
1061
+ }
1062
+ if (ok) {
1063
+ const hasConcrete = spreadOnly.some(s => !s);
1064
+ if (hasConcrete) {
1065
+ const concreteSegs = segs.filter((_, i) => !spreadOnly[i]);
1066
+ return `{ ${concreteSegs.join(', ')} }`;
1067
+ }
1068
+ // All spread — drop any bare-row segment whose id occurs only
1069
+ // once in the whole type (its name doesn't tie back to any
1070
+ // other position, so it carries no information). When the
1071
+ // caller didn't pass a `singletonIds` set (raw `typeToString`
1072
+ // calls), keep all segments to preserve the existing
1073
+ // user-facing annotation surface.
1074
+ const filtered = [];
1075
+ for (let i = 0; i < segs.length; i++) {
1076
+ const rid = segRowIds[i];
1077
+ if (rid !== null && singletonIds && singletonIds.has(rid))
1078
+ continue;
1079
+ filtered.push(segs[i]);
1080
+ }
1081
+ if (filtered.length === 0) {
1082
+ // All segments were bare-row singletons that we just
1083
+ // dropped. Rather than collapsing to a meaningless `{}`,
1084
+ // surface a single bare polymorphic variable so a `Merge p1
1085
+ // p2` of two zero-param tags displays the same way as a
1086
+ // single zero-param tag would: `a` instead of `{}`.
1087
+ for (let i = 0; i < t.args.length; i++) {
1088
+ const a = t.args[i];
1089
+ if (a.tag === 'TVar' || a.tag === 'TRow') {
1090
+ return typeToStringImpl(a, names, singletonIds);
1091
+ }
1092
+ }
1093
+ return '{}';
1094
+ }
1095
+ return `{ ${filtered.join(', ')} }`;
1096
+ }
1097
+ }
1098
+ // Sugar: `Function [x] a` -> `x -> a`, `Function [x, y] a` -> `(x, y) -> a`,
1099
+ // `Function [] a` -> `() -> a`. Nested `Function [x] (Function [y] a)`
1100
+ // renders as `x -> y -> a` because the result recurses through here.
1101
+ if (t.name === exports.T_FUNCTION && t.args.length === 2) {
1102
+ const list = functionParamList(t.args[0]);
1103
+ if (list !== null) {
1104
+ const resultStr = typeToStringImpl(t.args[1], names, singletonIds);
1105
+ if (list.length === 1) {
1106
+ const p = list[0];
1107
+ const pStr = funParamNeedsParens(p)
1108
+ ? `(${typeToStringImpl(p, names, singletonIds)})`
1109
+ : typeToStringImpl(p, names, singletonIds);
1110
+ return `${pStr} -> ${resultStr}`;
1111
+ }
1112
+ const paramsStr = list
1113
+ .map(a => typeToStringImpl(a, names, singletonIds))
1114
+ .join(', ');
1115
+ return `(${paramsStr}) -> ${resultStr}`;
1116
+ }
1117
+ }
1118
+ // Sugar: `Object k a` -> `{ [k] :: a }`.
1119
+ if (t.name === exports.T_OBJECT && t.args.length === 2) {
1120
+ const key = t.args[0];
1121
+ const keyStr = key.tag === 'TLabel'
1122
+ ? (key.kind === 'lit' ? `'${key.value}'` : (names?.get(key.id) ?? key.name))
1123
+ : typeToStringImpl(key, names, singletonIds);
1124
+ return `{ [${keyStr}] :: ${typeToStringImpl(t.args[1], names, singletonIds)} }`;
1125
+ }
1126
+ if (t.args.length === 0)
1127
+ return displayName;
1128
+ return `${displayName} ${t.args.map(a => needsParens(a) ? `(${typeToStringImpl(a, names, singletonIds)})` : typeToStringImpl(a, names, singletonIds)).join(' ')}`;
1129
+ }
1130
+ case 'TFun': {
1131
+ const paramStr = funParamNeedsParens(t.param)
1132
+ ? `(${typeToStringImpl(t.param, names, singletonIds)})`
1133
+ : typeToStringImpl(t.param, names, singletonIds);
1134
+ return `${paramStr} -> ${typeToStringImpl(t.result, names, singletonIds)}`;
1135
+ }
1136
+ case 'TRecord': {
1137
+ if (t.alias)
1138
+ return t.alias;
1139
+ // Hide the implicit `constructor` field that `Object.create(prototype)`
1140
+ // inherits — it carries no useful display info and clutters the type.
1141
+ // Also hide fields marked via `::hidden` / `::private` so enumerating the
1142
+ // host record (e.g. hover over `builtIn`) does not surface them.
1143
+ const keys = Object.keys(t.fields)
1144
+ .filter(k => k !== 'constructor' && !t.hiddenFields?.has(k));
1145
+ const fieldStrs = keys
1146
+ .map(k => {
1147
+ const override = t.fieldDisplays?.[k];
1148
+ return override
1149
+ ? `${k} :: ${override}`
1150
+ : `${k} :: ${typeToStringImpl(t.fields[k], names, singletonIds)}`;
1151
+ });
1152
+ if (t.labelFields) {
1153
+ for (const { label, type: vt } of t.labelFields) {
1154
+ const labelStr = label.kind === 'lit'
1155
+ ? `'${label.value}'`
1156
+ : (names?.get(label.id) ?? label.name);
1157
+ fieldStrs.push(`[${labelStr}] :: ${typeToStringImpl(vt, names, singletonIds)}`);
1158
+ }
1159
+ }
1160
+ const joined = fieldStrs.join(', ');
1161
+ if (t.rest) {
1162
+ const restStr = typeToStringImpl(t.rest, names, singletonIds);
1163
+ // A row-only open record (`{...a}`) renders with the `{a}` shorthand;
1164
+ // when concrete fields are also present we keep the explicit `...a`
1165
+ // tail so the field/row boundary stays readable (`{ x :: T, ...a }`).
1166
+ return fieldStrs.length === 0 ? `{ ${restStr} }` : `{ ${joined}, ...${restStr} }`;
1167
+ }
1168
+ if (fieldStrs.length === 0)
1169
+ return '{}';
1170
+ return `{ ${joined} }`;
1171
+ }
1172
+ case 'TLabel': {
1173
+ if (t.kind === 'lit')
1174
+ return `'${t.value}'`;
1175
+ return names?.get(t.id) ?? t.name;
1176
+ }
1177
+ case 'TRow':
1178
+ // Standalone TRow renders as `...r` — but TRow normally only
1179
+ // appears inside a TRecord's rest position where the record's
1180
+ // pretty-printer already prefixes `...`. Bare display is mainly
1181
+ // for diagnostic messages.
1182
+ return names?.get(t.id) ?? t.name;
1183
+ case 'TForall': {
1184
+ const varsStr = t.vars
1185
+ .map((id, i) => names?.get(id) ?? t.varNames[i] ?? `t${id}`)
1186
+ .join(' ');
1187
+ const cs = t.constraints && t.constraints.length > 0
1188
+ ? (t.constraints.length === 1
1189
+ ? `${renderConstraintStr(t.constraints[0], names)} => `
1190
+ : `(${t.constraints.map(c => renderConstraintStr(c, names)).join(', ')}) => `)
1191
+ : '';
1192
+ return `forall ${varsStr}. ${cs}${typeToStringImpl(t.body, names, singletonIds)}`;
1193
+ }
1194
+ }
1195
+ }
1196
+ /** Render a single constraint (`Functor f`, `Monoid (f a)`, `(A | B) v`) as
1197
+ * annotation text. Shared by {@link schemeToString} and the nested-forall
1198
+ * case of {@link typeToStringImpl}. */
1199
+ function renderConstraintStr(c, names) {
1200
+ const renderArg = (t) => {
1201
+ const s = typeToStringImpl(t, names);
1202
+ return (t.tag === 'TFun' || (t.tag === 'TCon' && t.args.length > 0)) ? `(${s})` : s;
1203
+ };
1204
+ if (c.unionAlternatives && c.unionAlternatives.length > 0) {
1205
+ const alts = c.unionAlternatives.map(a => {
1206
+ const s = typeToStringImpl(a, names);
1207
+ return a.tag === 'TFun' ? `(${s})` : s;
1208
+ }).join(' | ');
1209
+ return `(${alts}) ${c.typeVarName}`;
1210
+ }
1211
+ if (c.positionalArgs && c.positionalArgs.length > 0) {
1212
+ return `${c.className} ${c.positionalArgs.map(renderArg).join(' ')}`;
1213
+ }
1214
+ return `${c.className} ${c.typeVarName}`;
1215
+ }
1216
+ /** Render a type as text using each variable's own stored name (no
1217
+ * re-lettering). For user-facing output prefer {@link prettyTypeToString},
1218
+ * which renames variables to friendly sequential letters. */
1219
+ function typeToString(t) {
1220
+ return typeToStringImpl(t);
1221
+ }
1222
+ /**
1223
+ * Is `r` an "open object" annotation form — one whose declared shape places
1224
+ * no constraint on the concrete keys/values? Three syntactic spellings all
1225
+ * mean "an arbitrary object" and must canonicalize to the same overload key:
1226
+ *
1227
+ * • `Object` — handled by the caller (already a `TCon`).
1228
+ * • `{ a }` / `{ ...r }` — empty fields + a bare row/var tail.
1229
+ * • `{ [k] :: a }` — only polymorphic-label fields whose label AND
1230
+ * value are both type variables.
1231
+ *
1232
+ * A record with any concrete field (`{ x :: Number }`), a concrete index
1233
+ * value (`{ [k] :: Number }`), or the strict-empty `{}` form is NOT open and
1234
+ * keeps its own distinct key.
1235
+ */
1236
+ function isOpenObjectRecord(r) {
1237
+ if (Object.keys(r.fields).length > 0)
1238
+ return false;
1239
+ if (r.strictEmpty)
1240
+ return false;
1241
+ const labels = r.labelFields ?? [];
1242
+ if (labels.length === 0) {
1243
+ // `{ a }` / `{ ...r }`: an empty record with an open row/var tail.
1244
+ return r.rest !== undefined;
1245
+ }
1246
+ // `{ [k] :: a }`: only polymorphic-label fields, no concrete tail, and every
1247
+ // label and value must be a bare variable (so `{ [k] :: Number }` stays
1248
+ // distinct).
1249
+ if (r.rest !== undefined)
1250
+ return false;
1251
+ return labels.every(lf => lf.label.kind === 'var' && lf.type.tag === 'TVar');
1252
+ }
1253
+ /**
1254
+ * Rewrite every "open object" record (see {@link isOpenObjectRecord}) to the
1255
+ * canonical `Object` constructor, recursing through function and constructor
1256
+ * positions. Used ONLY to build the duplicate-overload key in
1257
+ * {@link canonicalSchemeKey} — it never touches the real scheme type, so
1258
+ * unification and hover rendering are unaffected.
1259
+ */
1260
+ function normalizeOpenObjectsForKey(t) {
1261
+ switch (t.tag) {
1262
+ case 'TRecord':
1263
+ return isOpenObjectRecord(t) ? exports.tObject : t;
1264
+ case 'TFun':
1265
+ return tFun(normalizeOpenObjectsForKey(t.param), normalizeOpenObjectsForKey(t.result));
1266
+ case 'TCon':
1267
+ // Applied `Function`/`Object` are sugar — desugar so an overload spelled
1268
+ // `Function [x, y] a` keys identically to `(x, y) -> a`, and `Object k a`
1269
+ // keys identically to `{ [k] :: a }`.
1270
+ if (t.name === exports.T_FUNCTION && t.args.length === 2)
1271
+ return normalizeOpenObjectsForKey(desugarFunctionType(t.args[0], t.args[1]));
1272
+ if (t.name === exports.T_OBJECT && t.args.length === 2)
1273
+ return normalizeOpenObjectsForKey(desugarObjectType(t.args[0], t.args[1]));
1274
+ return t.args.length === 0 ? t : tCon(t.name, t.args.map(normalizeOpenObjectsForKey));
1275
+ default:
1276
+ return t;
1277
+ }
1278
+ }
1279
+ /**
1280
+ * Produce an alpha-canonical key string for a scheme: every distinct type /
1281
+ * row / label / kind variable is renamed to a positional canonical name
1282
+ * (`a`, `b`, `c`, …) in order of first appearance, and the (sorted) constraint
1283
+ * list is appended. Two schemes that are identical up to consistent variable
1284
+ * renaming therefore produce the SAME key. Used to detect duplicate overload
1285
+ * signatures regardless of which variable letters the author happened to use.
1286
+ *
1287
+ * Plain language: a "fingerprint" for a signature that ignores the author's
1288
+ * choice of letter names — `a -> a` and `x -> x` get the same fingerprint.
1289
+ */
1290
+ function canonicalSchemeKey(scheme) {
1291
+ const keyType = normalizeOpenObjectsForKey(scheme.type);
1292
+ const ids = [];
1293
+ const names = new Map(); // id -> source name (first wins)
1294
+ collectVarIdsAndNames(keyType, names, ids);
1295
+ if (scheme.constraints) {
1296
+ for (const c of scheme.constraints) {
1297
+ if (c.positionalArgs)
1298
+ for (const a of c.positionalArgs)
1299
+ collectVarIdsAndNames(a, names, ids);
1300
+ if (c.unionAlternatives)
1301
+ for (const a of c.unionAlternatives)
1302
+ collectVarIdsAndNames(a, names, ids);
1303
+ }
1304
+ }
1305
+ const canonical = new Map(); // id -> canonical name
1306
+ const byOrigName = new Map(); // source name -> canonical name
1307
+ let next = 0;
1308
+ for (const id of ids) {
1309
+ if (canonical.has(id))
1310
+ continue;
1311
+ const cn = varNameFromIndex(next++);
1312
+ canonical.set(id, cn);
1313
+ const orig = names.get(id);
1314
+ if (orig !== undefined && !byOrigName.has(orig))
1315
+ byOrigName.set(orig, cn);
1316
+ }
1317
+ const typeStr = typeToStringImpl(keyType, canonical);
1318
+ if (!scheme.constraints || scheme.constraints.length === 0)
1319
+ return typeStr;
1320
+ const renderC = (c) => {
1321
+ const tv = byOrigName.get(c.typeVarName) ?? c.typeVarName;
1322
+ if (c.unionAlternatives && c.unionAlternatives.length > 0) {
1323
+ return '(' + c.unionAlternatives.map(a => typeToStringImpl(a, canonical)).join('|') + ') ' + tv;
1324
+ }
1325
+ if (c.positionalArgs && c.positionalArgs.length > 0) {
1326
+ return c.className + ' ' + c.positionalArgs.map(a => typeToStringImpl(a, canonical)).join(' ');
1327
+ }
1328
+ return c.className + ' ' + tv;
1329
+ };
1330
+ const cs = scheme.constraints.map(renderC).sort().join(',');
1331
+ return cs + ' => ' + typeStr;
1332
+ }
1333
+ /** Render a scheme as annotation text, constraints included —
1334
+ * e.g. `Functor f => f a -> f b`. */
1335
+ function schemeToString(s) {
1336
+ const renderConstraint = (c) => {
1337
+ const renderArg = (t) => {
1338
+ const s = typeToString(t);
1339
+ return (t.tag === 'TFun' || (t.tag === 'TCon' && t.args.length > 0)) ? `(${s})` : s;
1340
+ };
1341
+ if (c.unionAlternatives && c.unionAlternatives.length > 0) {
1342
+ const alts = c.unionAlternatives.map(a => {
1343
+ const s = typeToString(a);
1344
+ return a.tag === 'TFun' ? `(${s})` : s;
1345
+ }).join(' | ');
1346
+ return `(${alts}) ${c.typeVarName}`;
1347
+ }
1348
+ if (c.positionalArgs && c.positionalArgs.length > 0) {
1349
+ return `${c.className} ${c.positionalArgs.map(renderArg).join(' ')}`;
1350
+ }
1351
+ return `${c.className} ${c.typeVarName}`;
1352
+ };
1353
+ const constraintStr = s.constraints && s.constraints.length > 0
1354
+ ? (s.constraints.length === 1
1355
+ ? `${renderConstraint(s.constraints[0])} => `
1356
+ : `(${s.constraints.map(renderConstraint).join(', ')}) => `)
1357
+ : '';
1358
+ return constraintStr + typeToString(s.type);
1359
+ }
1360
+ /**
1361
+ * Build a pretty name map from collected variable IDs and their original names.
1362
+ * Preserves user-chosen annotation names (like a, b, a1); replaces
1363
+ * auto-generated names (t0, t1, ...) with sequential letters.
1364
+ */
1365
+ function buildPrettyNameMap(varIds, varNamesById, shareByName = false) {
1366
+ const nameMap = new Map();
1367
+ const usedNames = new Set();
1368
+ // When shareByName is set, distinct ids carrying the same source name
1369
+ // collapse to the same displayed letter (used by pair-printing so
1370
+ // "annotation a" lines up with "inferred a" even after instantiation
1371
+ // produced fresh TVar ids on each side).
1372
+ const nameToFirstId = new Map();
1373
+ // First pass: preserve original annotation names
1374
+ for (const id of varIds) {
1375
+ if (nameMap.has(id))
1376
+ continue;
1377
+ const origName = varNamesById.get(id);
1378
+ if (!origName || exports.AUTO_TVAR_NAME_RE.test(origName))
1379
+ continue;
1380
+ if (usedNames.has(origName)) {
1381
+ if (shareByName && nameToFirstId.has(origName)) {
1382
+ const firstId = nameToFirstId.get(origName);
1383
+ nameMap.set(id, nameMap.get(firstId));
1384
+ }
1385
+ continue;
1386
+ }
1387
+ nameMap.set(id, origName);
1388
+ usedNames.add(origName);
1389
+ nameToFirstId.set(origName, id);
1390
+ }
1391
+ // Second pass: assign sequential names to remaining vars
1392
+ let idx = 0;
1393
+ for (const id of varIds) {
1394
+ if (nameMap.has(id))
1395
+ continue;
1396
+ let name;
1397
+ do {
1398
+ name = varNameFromIndex(idx++);
1399
+ } while (usedNames.has(name));
1400
+ nameMap.set(id, name);
1401
+ usedNames.add(name);
1402
+ }
1403
+ return nameMap;
1404
+ }
1405
+ /**
1406
+ * Pretty-print a type, renaming type variables to a, b, c, ... in order of
1407
+ * first appearance. Produces human-friendly output for hover display.
1408
+ */
1409
+ function prettyTypeToString(t) {
1410
+ const varIds = [];
1411
+ const varNamesById = new Map();
1412
+ collectVarIdsAndNames(t, varNamesById, varIds);
1413
+ // A row-tail TVar/TRow id that appears exactly once across the whole
1414
+ // type carries no information beyond "open record" — its name binds
1415
+ // nothing else. Track them so the Merge spread-printer can drop
1416
+ // such uninformative tails when no concrete fields are present
1417
+ // (e.g. `Merge a p2` rendering as `{}` instead of `{ ...a, ...p2 }`).
1418
+ const counts = new Map();
1419
+ for (const id of varIds)
1420
+ counts.set(id, (counts.get(id) ?? 0) + 1);
1421
+ const singletonIds = new Set();
1422
+ for (const [id, c] of counts)
1423
+ if (c === 1)
1424
+ singletonIds.add(id);
1425
+ return typeToStringImpl(t, buildPrettyNameMap(varIds, varNamesById), singletonIds);
1426
+ }
1427
+ /**
1428
+ * Pretty-print `t` using a letter assignment SEEDED from `context` so that a
1429
+ * type variable shared between the two renders with the SAME letter in both.
1430
+ *
1431
+ * Used for hover: when the cursor is on a sub-expression inside a function,
1432
+ * `context` is the enclosing function's type. Without this, each hover
1433
+ * canonicalizes letters from scratch, so a variable shared by `f :: a -> b`
1434
+ * and its result `result` would render as `b` when hovering `f` but `a` when
1435
+ * hovering `result` in isolation. Seeding from `context` first pins the
1436
+ * shared variable to the letter it has in the enclosing scope.
1437
+ */
1438
+ function prettyTypeToStringWithContext(t, context) {
1439
+ const varIds = [];
1440
+ const varNamesById = new Map();
1441
+ // Seed with the context's variables first (establishes letter order), then
1442
+ // append any variables unique to `t`.
1443
+ collectVarIdsAndNames(context, varNamesById, varIds);
1444
+ collectVarIdsAndNames(t, varNamesById, varIds);
1445
+ // Singleton detection is based on `t` alone (drives the Merge open-row tail
1446
+ // elision), independent of the seeding order.
1447
+ const tIds = [];
1448
+ collectVarIdsAndNames(t, new Map(), tIds);
1449
+ const counts = new Map();
1450
+ for (const id of tIds)
1451
+ counts.set(id, (counts.get(id) ?? 0) + 1);
1452
+ const singletonIds = new Set();
1453
+ for (const [id, c] of counts)
1454
+ if (c === 1)
1455
+ singletonIds.add(id);
1456
+ // `shareByName` collapses distinct ids carrying the SAME source name onto one
1457
+ // letter. A variable that flows from the enclosing scope into a
1458
+ // sub-expression (e.g. the higher-kinded `f` of `Pair Number (f a)` re-read
1459
+ // as `pair.snd :: f a`) may arrive with a freshly-instantiated id; without
1460
+ // this, the context's `f` claims the letter `f` and the sub-expression's copy
1461
+ // is bumped to a sequential letter (`b a`). Auto-generated names (`t0`, …)
1462
+ // are exempt, so genuinely distinct body-local vars keep distinct letters.
1463
+ return typeToStringImpl(t, buildPrettyNameMap(varIds, varNamesById, /* shareByName */ true), singletonIds);
1464
+ }
1465
+ /**
1466
+ * Build the type-variable → display-letter map that {@link prettyTypeToString}
1467
+ * (or {@link prettyTypeToStringWithContext} when `context` is given) uses to
1468
+ * render `t`. Exposed so callers that render a constraint prefix separately
1469
+ * from the type body (e.g. hover) can label the constrained variable with the
1470
+ * SAME letter the body shows for it, instead of the variable's raw internal
1471
+ * name.
1472
+ */
1473
+ function buildVarDisplayNameMap(t, context) {
1474
+ const varIds = [];
1475
+ const varNamesById = new Map();
1476
+ if (context)
1477
+ collectVarIdsAndNames(context, varNamesById, varIds);
1478
+ collectVarIdsAndNames(t, varNamesById, varIds);
1479
+ // When seeded from a context, share letters across ids with the same source
1480
+ // name so a variable shared between context and `t` (e.g. the higher-kinded
1481
+ // `f`) renders with ONE letter instead of the second copy being re-lettered.
1482
+ return buildPrettyNameMap(varIds, varNamesById, /* shareByName */ !!context);
1483
+ }
1484
+ /**
1485
+ * Pretty-print two types using a shared name map so that the same TVar id
1486
+ * gets the same letter in both. Used for error messages like
1487
+ * "Cannot unify X with Y" to keep variable names readable and consistent.
1488
+ *
1489
+ * Distinct TVar ids that originated from the same source name (e.g. both
1490
+ * sides of a comparison reference an annotation's `a`) collapse to the same
1491
+ * displayed letter so the two type strings line up visually. This matters
1492
+ * for the "X has type ... but annotation expects ..." family of messages,
1493
+ * where instantiation produces fresh TVar ids on each side.
1494
+ */
1495
+ function prettyTypeToStringPair(t1, t2) {
1496
+ const varIds = [];
1497
+ const varNamesById = new Map();
1498
+ collectVarIdsAndNames(t1, varNamesById, varIds);
1499
+ collectVarIdsAndNames(t2, varNamesById, varIds);
1500
+ const nameMap = buildPrettyNameMap(varIds, varNamesById, /* shareByName */ true);
1501
+ return [typeToStringImpl(t1, nameMap), typeToStringImpl(t2, nameMap)];
1502
+ }
1503
+ /**
1504
+ * Rewrite a type so that distinct variables (TVar / TRow / TLabel-var)
1505
+ * carrying the SAME user-chosen source name collapse onto a single
1506
+ * representative id — a DISPLAY-ONLY normalization. Used when combining
1507
+ * independently-instantiated overload branches into one union for hover: each
1508
+ * branch wrote e.g. `a`, but `mergeOverloadSchemes` refreshed them to distinct
1509
+ * ids, so the pretty-printer would otherwise rename the second `a` to `b`
1510
+ * (e.g. `[a] | { b }`). Sharing the id per source name makes it render as the
1511
+ * source name in every branch (`[a] | { a }`).
1512
+ *
1513
+ * Auto-generated names (`t0`, `t1`, …) are left untouched so genuinely
1514
+ * distinct inference vars keep distinct letters. The result must be used for
1515
+ * display only — it deliberately conflates ids that are NOT semantically equal.
1516
+ */
1517
+ function canonicalizeDisplayVarsByName(t) {
1518
+ const repIdByName = new Map();
1519
+ const collect = (ty) => {
1520
+ switch (ty.tag) {
1521
+ case 'TVar':
1522
+ case 'TRow':
1523
+ if (!exports.AUTO_TVAR_NAME_RE.test(ty.name) && !repIdByName.has(ty.name)) {
1524
+ repIdByName.set(ty.name, ty.id);
1525
+ }
1526
+ break;
1527
+ case 'TCon': {
1528
+ // Higher-kinded variables are encoded in the TCon name as `$kv:f:id`.
1529
+ // Track them by source name too so a repeated kind-variable across
1530
+ // overload branches (e.g. `f a` and `Function [a] (f a)`) collapses
1531
+ // onto ONE id and renders with the same letter in every branch.
1532
+ const kv = parseKvName(ty.name);
1533
+ if (kv && !exports.AUTO_TVAR_NAME_RE.test(kv.varName) && !repIdByName.has(kv.varName)) {
1534
+ repIdByName.set(kv.varName, kv.varId);
1535
+ }
1536
+ ty.args.forEach(collect);
1537
+ break;
1538
+ }
1539
+ case 'TFun':
1540
+ collect(ty.param);
1541
+ collect(ty.result);
1542
+ break;
1543
+ case 'TRecord':
1544
+ for (const k in ty.fields)
1545
+ collect(ty.fields[k]);
1546
+ if (ty.rest)
1547
+ collect(ty.rest);
1548
+ if (ty.labelFields)
1549
+ for (const lf of ty.labelFields) {
1550
+ collect(lf.label);
1551
+ collect(lf.type);
1552
+ }
1553
+ break;
1554
+ case 'TLabel':
1555
+ if (ty.kind === 'var' && !exports.AUTO_TVAR_NAME_RE.test(ty.name) && !repIdByName.has(ty.name)) {
1556
+ repIdByName.set(ty.name, ty.id);
1557
+ }
1558
+ break;
1559
+ case 'TForall':
1560
+ // Do NOT descend: the binders are scoped and may reuse an outer
1561
+ // var's source name — conflating them would capture the bound var.
1562
+ break;
1563
+ }
1564
+ };
1565
+ const rewrite = (ty) => {
1566
+ switch (ty.tag) {
1567
+ case 'TVar': {
1568
+ const rep = repIdByName.get(ty.name);
1569
+ return rep != null && rep !== ty.id ? { ...ty, id: rep } : ty;
1570
+ }
1571
+ case 'TRow': {
1572
+ const rep = repIdByName.get(ty.name);
1573
+ return rep != null && rep !== ty.id ? { ...ty, id: rep } : ty;
1574
+ }
1575
+ case 'TCon': {
1576
+ const args = ty.args.map(rewrite);
1577
+ const kv = parseKvName(ty.name);
1578
+ if (kv) {
1579
+ const rep = repIdByName.get(kv.varName);
1580
+ if (rep != null && rep !== kv.varId) {
1581
+ return { ...ty, name: kvName(kv.varName, rep), args };
1582
+ }
1583
+ }
1584
+ return { ...ty, args };
1585
+ }
1586
+ case 'TFun':
1587
+ return { ...ty, param: rewrite(ty.param), result: rewrite(ty.result) };
1588
+ case 'TRecord': {
1589
+ const fields = {};
1590
+ for (const k in ty.fields)
1591
+ fields[k] = rewrite(ty.fields[k]);
1592
+ const out = { ...ty, fields };
1593
+ if (ty.rest)
1594
+ out.rest = rewrite(ty.rest);
1595
+ if (ty.labelFields) {
1596
+ out.labelFields = ty.labelFields.map(lf => ({ label: rewrite(lf.label), type: rewrite(lf.type) }));
1597
+ }
1598
+ return out;
1599
+ }
1600
+ case 'TLabel': {
1601
+ if (ty.kind === 'var') {
1602
+ const rep = repIdByName.get(ty.name);
1603
+ return rep != null && rep !== ty.id ? { ...ty, id: rep } : ty;
1604
+ }
1605
+ return ty;
1606
+ }
1607
+ default:
1608
+ return ty;
1609
+ }
1610
+ };
1611
+ collect(t);
1612
+ return rewrite(t);
1613
+ }
1614
+ /** Collect TVar ids and name mappings from a type.
1615
+ * When `ids` is provided, each encountered TVar id is pushed into it (preserving order of first appearance).
1616
+ * `names` always receives `id → name` mappings. */
1617
+ function collectVarIdsAndNames(t, names, ids) {
1618
+ switch (t.tag) {
1619
+ case 'TVar':
1620
+ ids?.push(t.id);
1621
+ if (!names.has(t.id))
1622
+ names.set(t.id, t.name);
1623
+ break;
1624
+ case 'TCon': {
1625
+ // Track kind-variable ids as type variable ids too
1626
+ const kv = parseKvName(t.name);
1627
+ if (kv) {
1628
+ ids?.push(kv.varId);
1629
+ if (!names.has(kv.varId))
1630
+ names.set(kv.varId, kv.varName);
1631
+ }
1632
+ t.args.forEach(a => collectVarIdsAndNames(a, names, ids));
1633
+ break;
1634
+ }
1635
+ case 'TFun':
1636
+ collectVarIdsAndNames(t.param, names, ids);
1637
+ collectVarIdsAndNames(t.result, names, ids);
1638
+ break;
1639
+ case 'TRecord':
1640
+ for (const k in t.fields)
1641
+ collectVarIdsAndNames(t.fields[k], names, ids);
1642
+ if (t.rest)
1643
+ collectVarIdsAndNames(t.rest, names, ids);
1644
+ if (t.labelFields)
1645
+ for (const lf of t.labelFields) {
1646
+ collectVarIdsAndNames(lf.label, names, ids);
1647
+ collectVarIdsAndNames(lf.type, names, ids);
1648
+ }
1649
+ break;
1650
+ case 'TLabel':
1651
+ if (t.kind === 'var') {
1652
+ ids?.push(t.id);
1653
+ if (!names.has(t.id))
1654
+ names.set(t.id, t.name);
1655
+ }
1656
+ break;
1657
+ case 'TRow':
1658
+ ids?.push(t.id);
1659
+ if (!names.has(t.id))
1660
+ names.set(t.id, t.name);
1661
+ break;
1662
+ case 'TForall':
1663
+ // Register the bound variables (so pretty-printing letters them with
1664
+ // their annotation names) and recurse into the body. Bound ids are
1665
+ // globally fresh, so registering them can never clash with outer vars.
1666
+ for (let i = 0; i < t.vars.length; i++) {
1667
+ ids?.push(t.vars[i]);
1668
+ if (!names.has(t.vars[i]))
1669
+ names.set(t.vars[i], t.varNames[i] ?? `t${t.vars[i]}`);
1670
+ }
1671
+ collectVarIdsAndNames(t.body, names, ids);
1672
+ break;
1673
+ }
1674
+ }
1675
+ /** The i-th friendly variable letter: a, b, c, … z, a1, b1, … */
1676
+ function varNameFromIndex(i) {
1677
+ const letter = String.fromCharCode(97 + (i % 26));
1678
+ const suffix = i >= 26 ? String(Math.floor(i / 26)) : '';
1679
+ return letter + suffix;
1680
+ }
1681
+ /**
1682
+ * Collect every display-relevant variable id in `t` (ordinary TVars, row-tail
1683
+ * TRow vars, TLabel vars, and higher-kinded `$kv:name:id` ids baked into TCon
1684
+ * names). Used by hover scope-seeding to decide whether a piece of enclosing
1685
+ * context genuinely SHARES a variable with the hovered type — only then may it
1686
+ * influence letter assignment.
1687
+ */
1688
+ function collectAllVarIds(t) {
1689
+ const ids = [];
1690
+ collectVarIdsAndNames(t, new Map(), ids);
1691
+ return new Set(ids);
1692
+ }
1693
+ // ---------------------------------------------------------------------------
1694
+ // Pure type utility functions (no inference engine state)
1695
+ //
1696
+ // Plain language: small stand-alone helpers for taking function types apart
1697
+ // (parameters vs. return type) and combining several types into one.
1698
+ // "Pure" = they only look at their inputs; they read no global state.
1699
+ // ---------------------------------------------------------------------------
1700
+ /** Get the final return type of a (possibly curried) function type:
1701
+ * for `a -> b -> c` that is `c`. */
1702
+ function getReturnType(t) {
1703
+ if (t.tag === 'TFun')
1704
+ return getReturnType(t.result);
1705
+ return t;
1706
+ }
1707
+ /**
1708
+ * Merge a list of return types into a unified type.
1709
+ * When all types share the same outer TCon, merges inner type args
1710
+ * position-by-position. Otherwise produces a flat Union.
1711
+ */
1712
+ function mergeReturnTypes(types) {
1713
+ if (types.every(t => t.tag === 'TCon' && t.args.length > 0)) {
1714
+ const first = types[0];
1715
+ const firstName = first.name;
1716
+ if (types.every(t => t.name === firstName)) {
1717
+ const arity = first.args.length;
1718
+ const mergedArgs = [];
1719
+ for (let i = 0; i < arity; i++) {
1720
+ const argTypes = [];
1721
+ const seenArgs = new Set();
1722
+ for (const t of types) {
1723
+ const arg = t.args[i];
1724
+ const key = typeToString(arg);
1725
+ if (!seenArgs.has(key)) {
1726
+ seenArgs.add(key);
1727
+ argTypes.push(arg);
1728
+ }
1729
+ }
1730
+ // Wildcards absorb anything: if some args are wildcards and others
1731
+ // are concrete, drop the wildcards and keep the concretes (the
1732
+ // wildcard branch's return type is unconstrained in this slot, so
1733
+ // it conforms to whatever the concrete branches produce).
1734
+ const hasWildcard = argTypes.some(isWildcard);
1735
+ const hasConcrete = argTypes.some(a => !isWildcard(a));
1736
+ const filteredArgs = hasWildcard && hasConcrete
1737
+ ? argTypes.filter(a => !isWildcard(a))
1738
+ : argTypes;
1739
+ mergedArgs.push(filteredArgs.length === 1 ? filteredArgs[0] : tUnion(filteredArgs));
1740
+ }
1741
+ return tCon(firstName, mergedArgs);
1742
+ }
1743
+ }
1744
+ return tUnion(types);
1745
+ }
1746
+ /**
1747
+ * Decompose a function type into its parameter slot types for N params.
1748
+ * Handles Tuple-encoded multi-param functions, spread/variadic tuples, and
1749
+ * JS's "fewer params than expected" convention.
1750
+ *
1751
+ * For curried: a -> b -> c with N=1 → params=[a], rest=(b -> c)
1752
+ * For tuple: (a, b) -> c with N=2 → params=[a, b], rest=c
1753
+ */
1754
+ function decomposeFunParams(t, numParams) {
1755
+ if (t.tag !== 'TFun')
1756
+ return null;
1757
+ if (isTuple(t.param) && t.param.args.length === numParams) {
1758
+ return { paramTypes: t.param.args, restType: t.result };
1759
+ }
1760
+ if (isTuple(t.param) &&
1761
+ t.param.args.some(a => isSpread(a)) && numParams === 1) {
1762
+ return { paramTypes: [t.param], restType: t.result };
1763
+ }
1764
+ if (isTuple(t.param) &&
1765
+ numParams >= 0 && numParams < t.param.args.length) {
1766
+ return {
1767
+ paramTypes: t.param.args.slice(0, numParams),
1768
+ restType: t.result,
1769
+ extraParamTypes: t.param.args.slice(numParams),
1770
+ };
1771
+ }
1772
+ if (numParams >= 1) {
1773
+ // A parameter aligned with the `...` region of a spread arrow chain
1774
+ // (`a -> b -> ... -> z`) must not receive the literal spread marker as its
1775
+ // type — a value parameter can never BE a spread. The middle params the
1776
+ // spread absorbs are unconstrained, so hand the parameter a fresh variable
1777
+ // and continue with the terminal/result. This prevents `...` leaking into
1778
+ // the inferred function type (which would spuriously clash with the param's
1779
+ // real usage, e.g. `z` in `x => y => z => x + y + z`).
1780
+ if (isSpread(t.param)) {
1781
+ return { paramTypes: [tVar()], restType: t.result };
1782
+ }
1783
+ return { paramTypes: [t.param], restType: t.result };
1784
+ }
1785
+ // Zero-param function used where a function is expected: treat the
1786
+ // expected parameter as an extra (ignored) param so the function type
1787
+ // still wraps the return type (e.g. `() => expr` passed as `a -> b`
1788
+ // becomes `a -> exprType` rather than bare `exprType`).
1789
+ if (numParams === 0) {
1790
+ return { paramTypes: [], restType: t.result, extraParamTypes: [t.param] };
1791
+ }
1792
+ return null;
1793
+ }
1794
+ /** Count how many parameters a function type expects (returns a display string). */
1795
+ function countFunParams(t) {
1796
+ if (t.tag !== 'TFun')
1797
+ return '0 parameters';
1798
+ if (isTuple(t.param)) {
1799
+ return `${t.param.args.length} parameter(s)`;
1800
+ }
1801
+ let count = 1;
1802
+ let current = t.result;
1803
+ while (current.tag === 'TFun') {
1804
+ count++;
1805
+ current = current.result;
1806
+ }
1807
+ return `${count} parameter(s)`;
1808
+ }
1809
+ /** Find TCon names in a type not present in `known` (skipping kind-variable names). */
1810
+ /**
1811
+ * Numeric literal (singleton) types — `2` in `_Tuple :: 2 -> …`. Encoded as
1812
+ * a nullary nominal constructor named by the canonical number text, so `2`
1813
+ * unifies only with `2`: NOT with `Number` (a `Number` value of unknown value
1814
+ * cannot pick a literal overload — it falls through to a `Number` branch). A
1815
+ * number literal EXPRESSION takes the literal type only where one is expected
1816
+ * (see `inferLiteral`); everywhere else it is plain `Number`.
1817
+ */
1818
+ const NUM_LIT_RE = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;
1819
+ function isNumLitName(name) {
1820
+ return NUM_LIT_RE.test(name);
1821
+ }
1822
+ function tNumLit(value) {
1823
+ return { tag: 'TCon', name: String(value), args: [] };
1824
+ }
1825
+ function findUnknownTCons(t, known, out = []) {
1826
+ switch (t.tag) {
1827
+ case 'TCon':
1828
+ if (!parseKvName(t.name) && !isWildcard(t) && !isSpread(t) && !known.has(t.name) && !isNumLitName(t.name))
1829
+ out.push(t.name);
1830
+ for (const arg of t.args)
1831
+ findUnknownTCons(arg, known, out);
1832
+ break;
1833
+ case 'TFun':
1834
+ findUnknownTCons(t.param, known, out);
1835
+ findUnknownTCons(t.result, known, out);
1836
+ break;
1837
+ case 'TRecord':
1838
+ for (const k in t.fields)
1839
+ findUnknownTCons(t.fields[k], known, out);
1840
+ if (t.rest)
1841
+ findUnknownTCons(t.rest, known, out);
1842
+ break;
1843
+ case 'TForall':
1844
+ findUnknownTCons(t.body, known, out);
1845
+ break;
1846
+ }
1847
+ return out;
1848
+ }
1849
+ /** Collect all TVar id→name mappings from a type (for preserving var names across instantiation). */
1850
+ function collectVarNames(t, names) {
1851
+ collectVarIdsAndNames(t, names);
1852
+ }
1853
+ //# sourceMappingURL=types.js.map