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,1208 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Constraint-aware instantiation & validation
4
+ //
5
+ // Plain language: when a constrained template like `Functor f => (a -> b) ->
6
+ // f a -> f b` is used, the requirement "f must support mapping" cannot be
7
+ // checked immediately — f may still be a placeholder. So the requirement is
8
+ // parked on a pending list, and once inference has filled the placeholders
9
+ // in, this file checks each parked requirement: does the concrete type have
10
+ // the methods the constraint demands? Unsatisfied requirements become
11
+ // diagnostics.
12
+ //
13
+ // Extracted from the InferenceEngine class. Implements constrained-scheme
14
+ // instantiation (pending-constraint registration, kv bookkeeping, structural
15
+ // and constructor-style constraints) plus the post-inference validation
16
+ // passes over pending (union) constraints.
17
+ // ============================================================================
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.collectKvNamesInType = collectKvNamesInType;
20
+ exports.typeConstructorArity = typeConstructorArity;
21
+ exports.registerKvConstraint = registerKvConstraint;
22
+ exports.instantiateWithConstraints = instantiateWithConstraints;
23
+ exports.registerStaticMethodConstraints = registerStaticMethodConstraints;
24
+ exports.countViolatedPendingConstraints = countViolatedPendingConstraints;
25
+ exports.validateMissingConstraints = validateMissingConstraints;
26
+ exports.validatePendingConstraints = validatePendingConstraints;
27
+ exports.validatePendingUnionConstraints = validatePendingUnionConstraints;
28
+ exports.applyConstraintConstructorRewrites = applyConstraintConstructorRewrites;
29
+ exports.bakeCtorConstraintsOnAnnotation = bakeCtorConstraintsOnAnnotation;
30
+ const types_1 = require("../hm/types");
31
+ const types_2 = require("../hm/types");
32
+ const substitution_1 = require("../hm/substitution");
33
+ const env_1 = require("../hm/env");
34
+ const unify_1 = require("../hm/unify");
35
+ const methodRegistry_1 = require("../registries/methodRegistry");
36
+ const constraintRegistry_1 = require("../registries/constraintRegistry");
37
+ const dataTypeRegistry_1 = require("../registries/dataTypeRegistry");
38
+ const typeUtils_1 = require("../hm/typeUtils");
39
+ const annotations_1 = require("./annotations");
40
+ /** Collect kv-encoded TCon varIds from a type tree (varName → old varId). */
41
+ function collectKvNamesInType(t, out) {
42
+ (0, typeUtils_1.eachType)(t, node => {
43
+ if (node.tag === 'TCon') {
44
+ const kv = (0, types_1.parseKvName)(node.name);
45
+ if (kv && !out.has(kv.varName))
46
+ out.set(kv.varName, kv.varId);
47
+ }
48
+ });
49
+ }
50
+ /**
51
+ * Check whether a constraint type variable (e.g. `m`) appears as a bare TVar
52
+ * in the parameter types of an annotation like `(m, f a) -> m a`, without
53
+ * being wrapped in `TypeRep m`. Used to suggest `TypeRep m` when the
54
+ * constraint has static methods.
55
+ */
56
+ function hasBareConstraintVarInParams(annotationType, constraintVarName, varNames) {
57
+ // Extract parameter types from the TFun
58
+ const params = (0, typeUtils_1.extractParamList)(annotationType);
59
+ // Walk each param type looking for a bare TVar matching the constraint var
60
+ function isBareVar(t) {
61
+ if (t.tag === 'TVar') {
62
+ return varNames.get(t.id) === constraintVarName;
63
+ }
64
+ if (t.tag === 'TCon') {
65
+ // TypeRep m — the m inside TypeRep is fine, skip it
66
+ if (t.name === types_1.T_TYPEREP)
67
+ return false;
68
+ // Tuple / other containers — check args
69
+ return t.args.some(isBareVar);
70
+ }
71
+ if (t.tag === 'TFun') {
72
+ return isBareVar(t.param) || isBareVar(t.result);
73
+ }
74
+ if (t.tag === 'TRecord') {
75
+ for (const k in t.fields) {
76
+ if (isBareVar(t.fields[k]))
77
+ return true;
78
+ }
79
+ return false;
80
+ }
81
+ return false;
82
+ }
83
+ return params.some(isBareVar);
84
+ }
85
+ /**
86
+ * Number of mandatory type arguments a known type-constructor name carries.
87
+ * Returns 0 for nullary/scalar types (`String`, `Number`, …) and unknown
88
+ * names; >0 for parametric constructors (`Array`=1, `Either`=2, `StrMap`=1, …).
89
+ */
90
+ function typeConstructorArity(name) {
91
+ const dt = (0, dataTypeRegistry_1.getDataType)(name);
92
+ if (dt)
93
+ return dt.decl.typeVars.length;
94
+ const reg = (0, methodRegistry_1.getTypeArity)(name);
95
+ if (reg > 0)
96
+ return reg;
97
+ return annotations_1.BUILTIN_TYPE_ARITIES.get(name) ?? 0;
98
+ }
99
+ /**
100
+ * Record a constraint on a kind-variable, splitting between applied
101
+ * (constructor) and unapplied (constraint) buckets. When `unique` is
102
+ * true, the constraint name is only added if not already present.
103
+ */
104
+ function registerKvConstraint(engine, varId, constraint, unique = false) {
105
+ const map = constraint.isApplied ? engine.kvConstructorConstraints : engine.kvConstraints;
106
+ const existing = map.get(varId) ?? [];
107
+ if (unique && existing.includes(constraint.className))
108
+ return;
109
+ existing.push(constraint.className);
110
+ map.set(varId, existing);
111
+ }
112
+ /**
113
+ * Instantiate a scheme and register pending constraint checks for any
114
+ * constrained type variables. When the scheme has constraints like
115
+ * `Functor f => (a -> b) -> f a -> f b`, the fresh type variable created
116
+ * for `f` is tracked so we can verify the constraint once `f` is resolved.
117
+ */
118
+ function instantiateWithConstraints(engine, scheme, node, annotation, skipPendingConstraints, preBindings, asGiven) {
119
+ if (!scheme.constraints || scheme.constraints.length === 0) {
120
+ return (0, env_1.instantiate)(scheme);
121
+ }
122
+ // We need to manually instantiate so we can track the var mapping
123
+ const varNames = new Map();
124
+ (0, types_1.collectVarNames)(scheme.type, varNames);
125
+ const subst = new substitution_1.Substitution();
126
+ const varIdMap = new Map(); // original varName -> fresh var id
127
+ const kvRenameMap = new Map(); // old $kv:name:oldId -> new $kv:name:freshId
128
+ const schemeVarSet = new Set(scheme.vars);
129
+ for (const v of scheme.vars) {
130
+ const name = varNames.get(v);
131
+ let fresh = (0, types_1.tVar)(name);
132
+ while (schemeVarSet.has(fresh.id)) {
133
+ fresh = (0, types_1.tVar)(name);
134
+ }
135
+ subst.set(v, fresh);
136
+ if (name) {
137
+ varIdMap.set(name, fresh.id);
138
+ // Track kv renaming for constraint vars
139
+ kvRenameMap.set((0, types_1.kvName)(name, v), (0, types_1.kvName)(name, fresh.id));
140
+ }
141
+ }
142
+ // Pre-bind specified scheme vars to concrete types. Used by constrained
143
+ // instance method calls where the receiver TCon args determine some of
144
+ // the scheme vars (e.g. `Prop t a ~> ...` with receiver `Prop Tag Number`
145
+ // pre-binds t→Tag, a→Number) so constraints referencing those vars are
146
+ // checked against the concrete types.
147
+ if (preBindings) {
148
+ for (const [name, concrete] of preBindings) {
149
+ const freshId = varIdMap.get(name);
150
+ if (freshId !== undefined) {
151
+ subst.set(freshId, concrete);
152
+ }
153
+ }
154
+ }
155
+ // Also collect kv-encoded TCon names baked into the type at parse time.
156
+ // The kv varId in the TCon name may differ from scheme.vars (which only
157
+ // lists free TVars, not IDs embedded in TCon name strings).
158
+ const existingKvNames = new Map(); // varName -> old kv varId
159
+ collectKvNamesInType(scheme.type, existingKvNames);
160
+ for (const [varName, oldKvId] of existingKvNames) {
161
+ const freshId = varIdMap.get(varName);
162
+ if (freshId !== undefined) {
163
+ const oldKvName = (0, types_1.kvName)(varName, oldKvId);
164
+ if (!kvRenameMap.has(oldKvName)) {
165
+ kvRenameMap.set(oldKvName, (0, types_1.kvName)(varName, freshId));
166
+ }
167
+ }
168
+ }
169
+ // Register pending constraints and kvConstraints mapping
170
+ const appliedConstraintVarIds = new Set();
171
+ // freshVarId -> the applied constraint's own arg signature (null = two
172
+ // applied constraints on the same var disagree).
173
+ const appliedConstraintSigs = new Map();
174
+ // Resolve a constraint's target fresh var id. Prefer the branch-specific
175
+ // `varId` recorded by `mergeOverloadSchemes` (mapped through `subst` to the
176
+ // instantiation-fresh id): overload branches may share a var letter, and
177
+ // resolving by NAME alone would collapse both onto one id and mis-attach a
178
+ // branch's constraint to the wrong branch's var. Falls back to the name
179
+ // map for ordinary (non-merged) constrained schemes.
180
+ const resolveConstraintVarId = (constraint) => {
181
+ if (constraint.varId !== undefined && schemeVarSet.has(constraint.varId)) {
182
+ const applied = subst.apply({ tag: 'TVar', id: constraint.varId, name: constraint.typeVarName });
183
+ if (applied.tag === 'TVar')
184
+ return applied.id;
185
+ }
186
+ return varIdMap.get(constraint.typeVarName);
187
+ };
188
+ // Constructor-style constraints (`Pair p => ... -> p c a`) where the
189
+ // constrained var IS a named type constructor: freshVarId -> className.
190
+ // Resolved into the instantiated type below (`p c a` -> `Pair c a`).
191
+ const ctorConstraintBindings = new Map();
192
+ for (const constraint of scheme.constraints) {
193
+ // Structural-union constraint: register a pending union check.
194
+ // No nominal class lookup, no kv-constraint registration — these
195
+ // are purely structural (the constrained var must unify with one
196
+ // of the alternatives).
197
+ if (constraint.unionAlternatives && constraint.unionAlternatives.length > 0) {
198
+ const freshId = resolveConstraintVarId(constraint);
199
+ if (freshId !== undefined && !skipPendingConstraints) {
200
+ const freshAlternatives = constraint.unionAlternatives.map(alt => subst.apply(alt));
201
+ engine.pendingUnionConstraints.push({
202
+ varId: freshId,
203
+ alternatives: freshAlternatives,
204
+ displayName: constraint.className,
205
+ node,
206
+ });
207
+ }
208
+ continue;
209
+ }
210
+ // Validate that the constraint is defined
211
+ const def = (0, constraintRegistry_1.lookupConstraint)(constraint.className);
212
+ if (!def) {
213
+ // `TypeRep` is a witness marker, not a `::constraint` class. The bake
214
+ // normally binds the var to `TypeRep <arg>` and drops the constraint;
215
+ // if it survived to here (degenerate form) skip it silently rather
216
+ // than report it as an unknown constraint.
217
+ if (constraint.className === types_1.T_TYPEREP) {
218
+ continue;
219
+ }
220
+ // Fallback: if `className` names a known concrete type (built-in
221
+ // like Number/String/Boolean, a registered data type, or a
222
+ // constructor/class declared or imported in scope), treat the
223
+ // constraint as naming a type constructor. This makes signatures
224
+ // such as `f :: Number r => r -> r` (type-equality assertion) and
225
+ // `m :: Pair p => ... -> p c a` (the var IS the named constructor)
226
+ // work without requiring an explicit `::constraint` definition.
227
+ const namesKnownConstructor = (0, methodRegistry_1.isBuiltinType)(constraint.className) ||
228
+ (0, dataTypeRegistry_1.isDataType)(constraint.className) ||
229
+ engine.annotationMap.has(constraint.className) ||
230
+ engine.importedConstructors.has(constraint.className) ||
231
+ typeConstructorArity(constraint.className) > 0;
232
+ if (namesKnownConstructor) {
233
+ const freshId = resolveConstraintVarId(constraint);
234
+ if (freshId !== undefined && existingKvNames.has(constraint.typeVarName)) {
235
+ // Higher-kinded constructor constraint: the constrained var
236
+ // appears applied (e.g. `Pair p => ... -> p c a`), so the var
237
+ // IS the named type constructor. Record the binding so every
238
+ // kv-encoded `$kv:p:freshId` usage resolves to the constructor
239
+ // (`p c a` -> `Pair c a`) in the instantiated type below.
240
+ ctorConstraintBindings.set(freshId, constraint.className);
241
+ }
242
+ else if (freshId !== undefined && !skipPendingConstraints) {
243
+ // Scalar / type-equality form (`Number r => r -> r`): defer to
244
+ // a pending union check that binds `r ~ TCon(className)`.
245
+ // For the applied form `Array String r =>`
246
+ // (positionalArgs = [String, r]) we drop the trailing bound
247
+ // var and use the rest as TCon args.
248
+ let typeArgs = [];
249
+ if (constraint.positionalArgs && constraint.positionalArgs.length > 0) {
250
+ const last = constraint.positionalArgs[constraint.positionalArgs.length - 1];
251
+ const dropLast = last.tag === 'TVar' && last.name === constraint.typeVarName;
252
+ const argsRaw = dropLast
253
+ ? constraint.positionalArgs.slice(0, -1)
254
+ : constraint.positionalArgs;
255
+ typeArgs = argsRaw.map(t => subst.apply(t));
256
+ }
257
+ const alt = { tag: 'TCon', name: constraint.className, args: typeArgs };
258
+ engine.pendingUnionConstraints.push({
259
+ varId: freshId,
260
+ alternatives: [alt],
261
+ displayName: constraint.className,
262
+ node,
263
+ });
264
+ }
265
+ continue;
266
+ }
267
+ // Structural annotation diagnostic — emit only at the declaration site
268
+ // (where `annotation` is supplied), never at bare value references, so it
269
+ // is not duplicated on `module.exports = f` / `const g = f`.
270
+ if (!skipPendingConstraints && annotation) {
271
+ const sigLoc = annotation?.signatureNameStart !== undefined && annotation?.signatureNameEnd !== undefined
272
+ ? { start: annotation.signatureNameStart, end: annotation.signatureNameEnd }
273
+ : { start: annotation?.commentStart ?? node.start, end: annotation?.commentEnd ?? node.end };
274
+ engine.addDiag(`Unknown constraint '${constraint.className}'. Define it with \`// ::constraint ${constraint.className} ${constraint.typeVarName} { ... }\``, sigLoc);
275
+ }
276
+ continue;
277
+ }
278
+ // Structural constraint:
279
+ // `::constraint Name p1 p2 … pN = self1 is body1 [, self2 is body2 …]`
280
+ // Each self-clause is checked independently. The use-site supplies
281
+ // positional arguments matching `headerParams`. For every clause:
282
+ // - The slot of `selfParam` in positionalArgs is the type that must
283
+ // satisfy the clause body (one of the union alternatives, or the
284
+ // body itself when not a union).
285
+ // - If that slot is concrete (TCon/TFun/etc.), check eagerly via
286
+ // speculative unify. If it's a use-site TVar, register a pending
287
+ // union check.
288
+ // - Body free vars not in headerParams are existential: each
289
+ // instantiation gets a fresh TVar.
290
+ if (def.selfClauses && def.headerParams) {
291
+ const headerParams = def.headerParams;
292
+ const selfClauses = def.selfClauses;
293
+ // Resolve positional args. When the constraint was written as the
294
+ // simple bare-var form `Name v =>` (no positionalArgs), synthesise
295
+ // a single positional arg pointing to the use-site var.
296
+ let positional;
297
+ if (constraint.positionalArgs && constraint.positionalArgs.length > 0) {
298
+ positional = constraint.positionalArgs.map(t => subst.apply(t));
299
+ }
300
+ else {
301
+ // Bare form: requires arity 1.
302
+ const freshId = resolveConstraintVarId(constraint);
303
+ if (freshId === undefined) {
304
+ continue;
305
+ }
306
+ positional = [{ tag: 'TVar', id: freshId, name: constraint.typeVarName }];
307
+ }
308
+ if (positional.length !== headerParams.length) {
309
+ // Structural annotation diagnostic — declaration site only (see above).
310
+ if (!skipPendingConstraints && annotation) {
311
+ engine.addDiag(`Constraint '${constraint.className}' expects ${headerParams.length} positional type argument(s) but got ${positional.length}`, { start: annotation?.commentStart ?? node.start, end: annotation?.commentEnd ?? node.end });
312
+ }
313
+ continue;
314
+ }
315
+ // Map header param name → positional arg type.
316
+ const headerByName = new Map();
317
+ for (let i = 0; i < headerParams.length; i++) {
318
+ headerByName.set(headerParams[i], positional[i]);
319
+ }
320
+ if (skipPendingConstraints) {
321
+ continue;
322
+ }
323
+ for (const clause of selfClauses) {
324
+ // Build per-clause id remap: header-named TVars → corresponding
325
+ // positional arg; everything else → fresh existential TVar.
326
+ const idMap = new Map();
327
+ (0, typeUtils_1.eachType)(clause.body, n => {
328
+ if (n.tag === 'TVar' && !idMap.has(n.id)) {
329
+ const pos = headerByName.get(n.name);
330
+ idMap.set(n.id, pos !== undefined ? pos : (0, types_1.tVar)(n.name));
331
+ }
332
+ });
333
+ const instantiatedBody = (0, typeUtils_1.mapType)(clause.body, n => {
334
+ if (n.tag === 'TVar' && idMap.has(n.id))
335
+ return idMap.get(n.id);
336
+ return undefined;
337
+ });
338
+ const finalBody = subst.apply(instantiatedBody);
339
+ const alternatives = (finalBody.tag === 'TCon' && finalBody.name === 'Union')
340
+ ? finalBody.args
341
+ : [finalBody];
342
+ const selfType = subst.apply(headerByName.get(clause.selfParam));
343
+ // Determine whether to check eagerly or defer.
344
+ // - selfType still a fresh TVar belonging to a use-site bound name
345
+ // → defer (pending union constraint).
346
+ // - selfType is a TVar but anonymous (no name in source) → still a
347
+ // use-site var; defer.
348
+ // - selfType has any concrete shape → check eagerly.
349
+ if (selfType.tag === 'TVar') {
350
+ engine.pendingUnionConstraints.push({
351
+ varId: selfType.id,
352
+ alternatives,
353
+ displayName: constraint.className,
354
+ node,
355
+ });
356
+ continue;
357
+ }
358
+ // Eager: try to unify selfType against each alternative.
359
+ let matched = false;
360
+ for (const alt of alternatives) {
361
+ const snapshot = subst.snapshot();
362
+ try {
363
+ const delta = (0, unify_1.unify)(selfType, alt);
364
+ for (const [k, v] of delta.entries())
365
+ subst.set(k, v);
366
+ matched = true;
367
+ break;
368
+ }
369
+ catch (e) {
370
+ if (!(e instanceof unify_1.UnificationError))
371
+ throw e;
372
+ subst.restore(snapshot);
373
+ }
374
+ }
375
+ if (!matched) {
376
+ engine.addDiag(`Type '${(0, types_1.prettyTypeToString)(selfType)}' does not satisfy constraint '${constraint.className}'`, { start: annotation?.commentStart ?? node.start, end: annotation?.commentEnd ?? node.end });
377
+ }
378
+ }
379
+ continue;
380
+ }
381
+ // Kind validation: check that the constraint usage matches the expected kind.
382
+ // These are structural diagnostics about how the annotation is *written*
383
+ // (kind mismatch, TypeRep placement, unused applied-arg vars). They belong
384
+ // to the annotation's declaration site only: a bare value reference to a
385
+ // constrained binding (e.g. `module.exports = drop`) instantiates the scheme
386
+ // with no `annotation` argument, and must NOT re-emit them — otherwise the
387
+ // definition-site diagnostic is duplicated at every reference.
388
+ if (!skipPendingConstraints && annotation) {
389
+ const varUsedAsConstructor = existingKvNames.has(constraint.typeVarName);
390
+ if (constraint.isApplied && def.expectedKind === '* -> *') {
391
+ // e.g. Functor (f a) — Functor expects * -> *, but (f a) is *
392
+ engine.addDiag(`Constraint kind mismatch: '${constraint.className}' expects kind * -> * (a type constructor), but '(${constraint.typeVarName} ...)' is kind * (a concrete type). Use '${constraint.className} ${constraint.typeVarName}' instead`, { start: annotation?.commentStart ?? node.start, end: annotation?.commentEnd ?? node.end });
393
+ }
394
+ else if (!constraint.isApplied && def.expectedKind === '*' && varUsedAsConstructor) {
395
+ // e.g. Monoid f where f is used as f a — Monoid expects *, but f is * -> *
396
+ engine.addDiag(`Constraint kind mismatch: '${constraint.className}' expects kind * (a concrete type), but '${constraint.typeVarName}' is used as a type constructor (kind * -> *). Use '${constraint.className} (${constraint.typeVarName} ...)' instead`, { start: annotation?.commentStart ?? node.start, end: annotation?.commentEnd ?? node.end });
397
+ }
398
+ // Applied constraint with static methods: bare type-constructor var
399
+ // in parameter list needs TypeRep wrapping.
400
+ // e.g. Monoid (m a) has static method `empty :: () -> m`. If `m`
401
+ // appears as a bare parameter, the user should write `TypeRep m`.
402
+ if (constraint.isApplied && varUsedAsConstructor) {
403
+ const allMethods = (0, constraintRegistry_1.getEffectiveMethods)(constraint.className);
404
+ const hasStatic = allMethods.some(m => !m.signature.includes('~>'));
405
+ if (hasStatic && hasBareConstraintVarInParams(scheme.type, constraint.typeVarName, varNames)) {
406
+ engine.addDiag(`Constraint '${constraint.className}' has static methods, but type variable '${constraint.typeVarName}' appears as a bare parameter. Use 'TypeRep ${constraint.typeVarName}' to pass the type constructor`, { start: annotation?.commentStart ?? node.start, end: annotation?.commentEnd ?? node.end });
407
+ }
408
+ }
409
+ // Applied constraint inner arg validation: check that inner type
410
+ // variables like 'b' in Monoid (m b) actually appear in the function type.
411
+ // A compound (nested) arg like '(t a)' is checked per component var.
412
+ if (constraint.isApplied && constraint.appliedArgNames) {
413
+ const typeVarNameSet = new Set(varNames.values());
414
+ for (const argName of constraint.appliedArgNames) {
415
+ const componentNames = argName.startsWith('(')
416
+ ? argName.match(/[a-z][A-Za-z0-9]*/g) ?? []
417
+ : [argName];
418
+ for (const component of componentNames) {
419
+ if (!typeVarNameSet.has(component)) {
420
+ engine.addDiag(`Type variable '${component}' in constraint '${constraint.className} (${constraint.typeVarName} ${constraint.appliedArgNames.join(' ')})' does not appear in the function type`, { start: annotation?.commentStart ?? node.start, end: annotation?.commentEnd ?? node.end });
421
+ }
422
+ }
423
+ }
424
+ }
425
+ }
426
+ const freshId = resolveConstraintVarId(constraint);
427
+ if (freshId !== undefined) {
428
+ if (!skipPendingConstraints) {
429
+ engine.pendingConstraints.push({
430
+ varId: freshId,
431
+ constraintName: constraint.className,
432
+ node,
433
+ reps: scheme.reps,
434
+ given: asGiven,
435
+ typeVarName: constraint.typeVarName,
436
+ appliedArgNames: constraint.isApplied ? constraint.appliedArgNames : undefined,
437
+ // For givens (the enclosing function's own signature), remember the
438
+ // annotation comment range so the missing-constraint diagnostic can
439
+ // point back at (and quick-fix) the signature.
440
+ annStart: asGiven ? annotation?.commentStart : undefined,
441
+ annEnd: asGiven ? annotation?.commentEnd : undefined,
442
+ });
443
+ }
444
+ if (constraint.isApplied) {
445
+ appliedConstraintVarIds.add(freshId);
446
+ // Record the constraint's OWN application signature (`Setoid (f b)`
447
+ // applies `f` to `b`) so the pin-consistency check below can compare
448
+ // it against the applications found in the type — the constraint app
449
+ // itself may not occur in the type at all (interchange's `f (a -> b)`).
450
+ if (constraint.appliedArgNames && constraint.appliedArgNames.length > 0) {
451
+ const sig = constraint.appliedArgs
452
+ ? constraint.appliedArgs
453
+ .map(t => (0, types_1.typeToString)((0, typeUtils_1.renameKvInType)(subst.apply(t), kvRenameMap)))
454
+ .join(',')
455
+ : constraint.appliedArgNames.map(n => {
456
+ const id = varIdMap.get(n);
457
+ return id !== undefined ? (0, types_1.typeToString)({ tag: 'TVar', id, name: n }) : n;
458
+ }).join(',');
459
+ const prev = appliedConstraintSigs.get(freshId);
460
+ if (prev === undefined)
461
+ appliedConstraintSigs.set(freshId, sig);
462
+ else if (prev !== sig)
463
+ appliedConstraintSigs.set(freshId, null);
464
+ }
465
+ }
466
+ registerKvConstraint(engine, freshId, constraint);
467
+ }
468
+ }
469
+ // Apply substitution (handles TVar renaming) then rename kv TCon names
470
+ let result = subst.apply(scheme.type);
471
+ result = (0, typeUtils_1.renameKvInType)(result, kvRenameMap);
472
+ // Resolve constructor-style constraints (`Pair p => ... -> p c a`):
473
+ // bind each constrained var to its named constructor so kv usages
474
+ // (`$kv:p:freshId c a`) collapse to `Pair c a`. Done after the kv
475
+ // rename so the ids match the instantiated type. Also commit the
476
+ // binding to the engine subst (when not a display-only instantiation)
477
+ // so body unification agrees.
478
+ if (ctorConstraintBindings.size > 0) {
479
+ const ctorSubst = new substitution_1.Substitution();
480
+ for (const [id, cname] of ctorConstraintBindings) {
481
+ const ctor = { tag: 'TCon', name: cname, args: [] };
482
+ ctorSubst.set(id, ctor);
483
+ }
484
+ result = ctorSubst.apply(result);
485
+ }
486
+ // When an applied constraint like `Monoid (m a)` produces a kv-TCon
487
+ // `$kv:m:ID(a)` in the return type, but `TypeRep m` in the parameters
488
+ // still wraps a bare TVar, functions receiving the TypeRep (like
489
+ // `empty :: Monoid m => TypeRep m -> m`) would return the bare TVar `m`
490
+ // instead of the full applied `m a`. Fix this by replacing the bare
491
+ // TVar inside TypeRep with the applied kv-TCon found elsewhere in the type.
492
+ // Only do this for vars from *applied* constraints (e.g. `Monoid (m a)`),
493
+ // not non-applied constraints (e.g. `Applicative f`) where `f` appears
494
+ // as a constructor naturally (in `f b`) but TypeRep should stay `TypeRep f`.
495
+ const kvApps = new Map();
496
+ (0, typeUtils_1.collectKvApplications)(result, kvApps);
497
+ if (kvApps.size > 0) {
498
+ // NOTE: non-applied constraint vars (e.g. the `f` of
499
+ // `of :: Applicative f => TypeRep f -> a -> f a`) are intentionally NOT
500
+ // pinned: unifyTypeRep binds a bare `TypeRep f` var to the witness's
501
+ // *bare* constructor (stripping the witness's own element params), so
502
+ // `f a` collapses correctly AND the rep stays usable at multiple element
503
+ // types in one body. Pinning remains only for *applied* constraints
504
+ // (e.g. `Monoid (m a) => TypeRep m -> m`) where the kv application in the
505
+ // rest of the type must be mirrored into the TypeRep parameter.
506
+ //
507
+ // Even then, pinning is only SAFE when the var is kv-applied to a single,
508
+ // consistent argument across the whole type. When applied to *varying*
509
+ // args (e.g. `(ChainRec m, Setoid (m b)) => TypeRep m -> (a -> m a) ->
510
+ // (a -> m b) -> ...`), picking one application to bake into the TypeRep
511
+ // would be unsound — a callee's bare `TypeRep m` would bind to the
512
+ // applied form and later collapse `m c` into the ill-kinded `m b c`.
513
+ const argSigByVar = new Map();
514
+ for (const [id, sig] of appliedConstraintSigs)
515
+ argSigByVar.set(id, sig);
516
+ (0, typeUtils_1.eachType)(result, node => {
517
+ if (node.tag !== 'TCon')
518
+ return;
519
+ const kv = (0, types_1.parseKvName)(node.name);
520
+ if (!kv || node.args.length === 0)
521
+ return;
522
+ if (!appliedConstraintVarIds.has(kv.varId))
523
+ return;
524
+ const sig = node.args.map(a => (0, types_1.typeToString)(a)).join(',');
525
+ const prev = argSigByVar.get(kv.varId);
526
+ if (prev === undefined)
527
+ argSigByVar.set(kv.varId, sig);
528
+ else if (prev !== sig)
529
+ argSigByVar.set(kv.varId, null); // inconsistent
530
+ });
531
+ for (const varId of [...kvApps.keys()]) {
532
+ if (!appliedConstraintVarIds.has(varId) || argSigByVar.get(varId) === null) {
533
+ kvApps.delete(varId);
534
+ }
535
+ }
536
+ if (kvApps.size > 0) {
537
+ result = (0, typeUtils_1.fixTypeRepKvVars)(result, kvApps);
538
+ }
539
+ }
540
+ return result;
541
+ }
542
+ /**
543
+ * Register constraint info for static method body parameter TVars.
544
+ * Matches annotation param positions with body param TVars and registers
545
+ * kvConstraints so hover and autocomplete work on constraint-typed params
546
+ * (e.g. M in `static of(M, value)` when annotation says `Monad m => (m, a) -> ...`).
547
+ */
548
+ function registerStaticMethodConstraints(engine, scheme, bodyType) {
549
+ if (!scheme.constraints || scheme.constraints.length === 0)
550
+ return;
551
+ // Build a map of annotation var names
552
+ const annVarNames = new Map();
553
+ (0, types_1.collectVarNames)(scheme.type, annVarNames);
554
+ // Find which annotation vars correspond to constraint type vars
555
+ const constraintVarIds = new Map(); // varName -> [varIds]
556
+ for (const constraint of scheme.constraints) {
557
+ const ids = [];
558
+ for (const [vid, vname] of annVarNames) {
559
+ if (vname === constraint.typeVarName)
560
+ ids.push(vid);
561
+ }
562
+ constraintVarIds.set(constraint.typeVarName, ids);
563
+ }
564
+ // Extract annotation param types and body param types from TFun
565
+ const annParamTypes = (0, typeUtils_1.extractParamList)(scheme.type);
566
+ const bodyParamTypes = (0, typeUtils_1.extractParamList)(bodyType);
567
+ for (let i = 0; i < annParamTypes.length && i < bodyParamTypes.length; i++) {
568
+ const bodyParam = engine.subst.apply(bodyParamTypes[i]);
569
+ if (bodyParam.tag !== 'TVar')
570
+ continue;
571
+ // Check if this annotation param position uses a constraint var
572
+ for (const constraint of scheme.constraints) {
573
+ const cVarIds = constraintVarIds.get(constraint.typeVarName) ?? [];
574
+ const annParam = annParamTypes[i];
575
+ // If the annotation param IS the constraint var (e.g. m in (m, a))
576
+ if (annParam.tag === 'TVar' && cVarIds.includes(annParam.id)) {
577
+ registerKvConstraint(engine, bodyParam.id, constraint, true);
578
+ }
579
+ }
580
+ }
581
+ }
582
+ /**
583
+ * Count pending constraints whose variable has resolved (under the CURRENT
584
+ * substitution) to a concrete type that does NOT satisfy the constraint.
585
+ * Read-only mirror of {@link validatePendingConstraints} (emits no
586
+ * diagnostics). Used by overload selection to reject a branch that would
587
+ * pin a constraint variable to an incompatible type (e.g. selecting the
588
+ * `Category c => TypeRep c -> c` overload of `id` for `id(Function)` when
589
+ * `Function` does not satisfy `Category`).
590
+ */
591
+ function countViolatedPendingConstraints(engine) {
592
+ let violations = 0;
593
+ for (const pending of engine.pendingConstraints) {
594
+ const resolved = engine.subst.apply({ tag: 'TVar', id: pending.varId, name: '' });
595
+ if (resolved.tag === 'TVar')
596
+ continue;
597
+ if ((0, types_2.isAnyType)(resolved))
598
+ continue;
599
+ if ((0, types_1.containsErrorType)(resolved))
600
+ continue;
601
+ if (resolved.tag === 'TCon' && (0, types_1.parseKvName)(resolved.name))
602
+ continue;
603
+ let typeToCheck = null;
604
+ if (resolved.tag === 'TCon')
605
+ typeToCheck = resolved.name;
606
+ else if (resolved.tag === 'TFun') {
607
+ const ret = (0, types_1.getReturnType)(resolved);
608
+ if (ret.tag === 'TCon')
609
+ typeToCheck = ret.name;
610
+ }
611
+ else if (resolved.tag === 'TRecord')
612
+ typeToCheck = 'Object';
613
+ if (typeToCheck === null)
614
+ continue;
615
+ if (typeToCheck === types_1.T_SPREAD_ARRAY)
616
+ typeToCheck = 'Array';
617
+ if (!(0, constraintRegistry_1.lookupConstraint)(pending.constraintName))
618
+ continue;
619
+ const { missing } = (0, constraintRegistry_1.checkConstraint)(pending.constraintName, typeToCheck);
620
+ const applicableReps = [...(pending.reps ?? []), ...engine.fileReps, ...engine.importedReps];
621
+ const repMethodNames = new Set(applicableReps
622
+ .filter((r) => r.constraint === pending.constraintName && r.typeName === typeToCheck)
623
+ .map((r) => r.methodName));
624
+ if (missing.some((m) => !repMethodNames.has(m)))
625
+ violations++;
626
+ }
627
+ return violations;
628
+ }
629
+ /**
630
+ * Report constraints that a callee REQUIRES on an enclosing function's own
631
+ * (still-polymorphic) type variable but which the enclosing signature never
632
+ * DECLARES. Haskell's "No instance for (C a) arising from a use of …".
633
+ *
634
+ * Mechanism: an annotated constrained function body instantiates its OWN
635
+ * signature as the authoritative expected type (`asGiven` → pending
636
+ * constraints tagged `given`). Callees referenced in the body push their
637
+ * required constraints (wanted, `given` unset) onto vars that unify with the
638
+ * enclosing function's declared type vars — so both givens and wanteds share
639
+ * the same resolved var id (a bare TVar or a still-polymorphic `$kv:name:id`
640
+ * higher-kinded TCon). A wanted whose class is not entailed by the given
641
+ * closure on that var (via `extends` superclasses) is an under-declared
642
+ * constraint. Only fires when the var carries at least one given, i.e. it
643
+ * belongs to an annotated constrained function — never on inferred /
644
+ * unconstrained polymorphic code.
645
+ */
646
+ function validateMissingConstraints(engine) {
647
+ // Resolve a pending constraint's var to a canonical polymorphic var id:
648
+ // a bare TVar id, or the id embedded in a still-unresolved `$kv:name:id`
649
+ // higher-kinded TCon. Returns null when the var resolved to a concrete
650
+ // type (handled by validatePendingConstraints) or anything else.
651
+ const canonicalVarId = (varId) => {
652
+ const r = engine.subst.apply({ tag: 'TVar', id: varId, name: '' });
653
+ if (r.tag === 'TVar')
654
+ return r.id;
655
+ if (r.tag === 'TCon') {
656
+ const kv = (0, types_1.parseKvName)(r.name);
657
+ if (kv)
658
+ return kv.varId;
659
+ }
660
+ return null;
661
+ };
662
+ // Given-constraint closure per canonical var: union of superclass closures
663
+ // of every declared (given) constraint resolving onto that var. Also
664
+ // remember the declaring annotation's comment range per var so the
665
+ // missing-constraint diagnostic can point at the signature to fix.
666
+ const givenClosureByVar = new Map();
667
+ const givenAnnotationByVar = new Map();
668
+ for (const p of engine.pendingConstraints) {
669
+ if (!p.given)
670
+ continue;
671
+ if (!(0, constraintRegistry_1.lookupConstraint)(p.constraintName))
672
+ continue;
673
+ const cid = canonicalVarId(p.varId);
674
+ if (cid === null)
675
+ continue;
676
+ let set = givenClosureByVar.get(cid);
677
+ if (!set) {
678
+ set = new Set();
679
+ givenClosureByVar.set(cid, set);
680
+ }
681
+ for (const c of (0, constraintRegistry_1.constraintSuperclassClosure)(p.constraintName))
682
+ set.add(c);
683
+ if (p.annStart !== undefined && p.annEnd !== undefined && !givenAnnotationByVar.has(cid)) {
684
+ givenAnnotationByVar.set(cid, { start: p.annStart, end: p.annEnd });
685
+ }
686
+ }
687
+ if (givenClosureByVar.size === 0)
688
+ return;
689
+ // For each wanted constraint on a given-carrying var, require entailment.
690
+ const reported = new Set();
691
+ for (const p of engine.pendingConstraints) {
692
+ if (p.given)
693
+ continue;
694
+ if (!(0, constraintRegistry_1.lookupConstraint)(p.constraintName))
695
+ continue;
696
+ const cid = canonicalVarId(p.varId);
697
+ if (cid === null)
698
+ continue;
699
+ const given = givenClosureByVar.get(cid);
700
+ if (!given)
701
+ continue; // var is not a declared var of an annotated function
702
+ if (given.has(p.constraintName))
703
+ continue; // entailed by a declared constraint
704
+ const varLetter = p.typeVarName ?? '';
705
+ const key = `${cid}:${p.constraintName}:${p.node.start}:${p.node.end}`;
706
+ if (reported.has(key))
707
+ continue;
708
+ reported.add(key);
709
+ // Applied constraints (e.g. `Monoid (f a)`) keep their applied form in
710
+ // the label so the user can copy it verbatim into the signature.
711
+ const varDisplay = varLetter && p.appliedArgNames && p.appliedArgNames.length > 0
712
+ ? `(${varLetter} ${p.appliedArgNames.join(' ')})`
713
+ : varLetter;
714
+ const label = varDisplay ? `${p.constraintName} ${varDisplay}` : p.constraintName;
715
+ const ann = givenAnnotationByVar.get(cid);
716
+ engine.addDiag(`Missing constraint '${label}' required here; add it to the enclosing function's signature.`, p.node, ann ? [{ message: "The enclosing function's signature", start: ann.start, end: ann.end }] : undefined);
717
+ }
718
+ }
719
+ /**
720
+ * Validate all pending constraints after inference is complete.
721
+ * Checks that each constrained type variable resolved to a concrete type
722
+ * that satisfies the constraint (i.e., has all required methods registered).
723
+ */
724
+ function validatePendingConstraints(engine) {
725
+ for (const pending of engine.pendingConstraints) {
726
+ const resolved = engine.subst.apply({ tag: 'TVar', id: pending.varId, name: '' });
727
+ // If still a type variable, the constraint can't be checked yet — skip
728
+ if (resolved.tag === 'TVar')
729
+ continue;
730
+ // `Any` is the dynamic type: like unification, constraint checks accept it.
731
+ if ((0, types_2.isAnyType)(resolved))
732
+ continue;
733
+ // If the resolved type is poisoned by a prior $error, skip — the
734
+ // originating diagnostic already informs the user; cascading a
735
+ // "Type '$error' does not satisfy constraint" message just adds
736
+ // noise.
737
+ if ((0, types_1.containsErrorType)(resolved))
738
+ continue;
739
+ // If still a kind-variable TCon (not resolved to a concrete type), skip
740
+ if (resolved.tag === 'TCon' && (0, types_1.parseKvName)(resolved.name))
741
+ continue;
742
+ // Must be a TCon to check methods.
743
+ // Special case: when the constraint var resolves to a function type
744
+ // (common in JS where constructor functions serve as type constructor
745
+ // representatives, e.g. Identity :: a -> Identity a), extract the
746
+ // return type's TCon and check that against the constraint.
747
+ let typeToCheck = null;
748
+ if (resolved.tag === 'TCon') {
749
+ typeToCheck = resolved.name;
750
+ }
751
+ else if (resolved.tag === 'TFun') {
752
+ const ret = (0, types_1.getReturnType)(resolved);
753
+ // A function that does not return a constructor's type is a plain
754
+ // function VALUE: check the user-declared `Function` instances
755
+ // (`::rep Setoid Function#equals`).
756
+ typeToCheck = ret.tag === 'TCon' && !(0, types_1.isSkolem)(ret) ? ret.name : 'Function';
757
+ }
758
+ else if (resolved.tag === 'TRecord') {
759
+ // Records have no kind-parameter; structurally they all share the
760
+ // outer kind `Object`. Map TRecord → 'Object' so constraint
761
+ // dispatch consults user-declared Object instance methods (e.g.
762
+ // `// Object#concat :: { ...a } ~> { ...b } -> { ...a, ...b }`).
763
+ // No class names are hardcoded here.
764
+ typeToCheck = 'Object';
765
+ }
766
+ // A SpreadArray (`[a, b, ...]`) is array-like: it satisfies the same
767
+ // constraints and exposes the same methods/`::rep` bindings as `Array`.
768
+ // Normalize it here so constraint resolution, `::rep` lookup, and the
769
+ // method shape-check all consult the `Array` instance (mirrors the
770
+ // SpreadArray→Array normalization in the method registry).
771
+ if (typeToCheck === types_1.T_SPREAD_ARRAY) {
772
+ typeToCheck = 'Array';
773
+ }
774
+ if (typeToCheck === null) {
775
+ engine.addDiag(`Type '${(0, types_1.prettyTypeToString)(resolved)}' cannot satisfy constraint '${pending.constraintName}'`, pending.node);
776
+ continue;
777
+ }
778
+ // Rank-N skolem promise: the `forall` that minted this skolem declared
779
+ // the constraint (e.g. `forall f. Functor f => …`), so the methods are
780
+ // guaranteed by the callee's annotation — nothing to check here.
781
+ const promised = engine.rankNSkolemPromises.get(typeToCheck);
782
+ if (promised && promised.has(pending.constraintName))
783
+ continue;
784
+ const { missing } = (0, constraintRegistry_1.checkConstraint)(pending.constraintName, typeToCheck);
785
+ // Consult `::rep` representations carried by the constraining scheme.
786
+ // A `::rep Constraint Type#method` entry declares that the local
787
+ // instance-method annotation `Type#method` satisfies the constraint's
788
+ // requirement for `method` even though that method is not registered as
789
+ // a normal (autocomplete-visible) method. These are call-scoped: they
790
+ // only apply when the scheme carrying them is used here. Schemes that
791
+ // crossed an import boundary carry their reps explicitly; for a
792
+ // constrained function used locally in the same file the reps are not
793
+ // attached to the scheme, so fall back to the file-level `::rep` set.
794
+ const applicableReps = [...(pending.reps ?? []), ...engine.fileReps, ...engine.importedReps];
795
+ // `missing` includes the superclasses' methods (Plus → Alt → Functor), so
796
+ // a superclass instance (`::rep Alt Array#alt`) counts as well.
797
+ const repConstraints = new Set([pending.constraintName, ...(0, constraintRegistry_1.constraintSuperclassClosure)(pending.constraintName)]);
798
+ const repMethodNames = new Set(applicableReps
799
+ .filter((r) => repConstraints.has(r.constraint) && r.typeName === typeToCheck)
800
+ .map((r) => r.methodName));
801
+ const trueMissing = missing.filter((m) => !repMethodNames.has(m));
802
+ if (trueMissing.length > 0) {
803
+ const def = (0, constraintRegistry_1.lookupConstraint)(pending.constraintName);
804
+ if (!def) {
805
+ engine.addDiag(`Unknown constraint '${pending.constraintName}'`, pending.node);
806
+ }
807
+ else {
808
+ engine.addDiag(`Type '${typeToCheck}' does not satisfy constraint '${pending.constraintName}': missing method${trueMissing.length > 1 ? 's' : ''} ${trueMissing.map(m => `'${m}'`).join(', ')}`, pending.node);
809
+ }
810
+ }
811
+ else {
812
+ // When the constraint var resolved to a function type (e.g. a -> Identity a),
813
+ // rebind it to the type constructor name (Identity) so that result types
814
+ // display as e.g. EitherT e Identity String instead of EitherT e (a -> Identity a) String.
815
+ // This matches Haskell/PureScript convention where m is a type constructor, not a function.
816
+ // Walk the substitution chain to find the deepest TVar bound to the function type,
817
+ // since unification may have created intermediate TVar links.
818
+ if (resolved.tag === 'TFun' && typeToCheck !== null) {
819
+ const constructorType = (0, types_1.tCon)(typeToCheck, []);
820
+ let curId = pending.varId;
821
+ // Chase through TVar → TVar chains to find the one that directly
822
+ // holds the TFun binding.
823
+ for (;;) {
824
+ const cur = engine.subst.lookup(curId);
825
+ if (cur && cur.tag === 'TVar') {
826
+ curId = cur.id;
827
+ }
828
+ else {
829
+ break;
830
+ }
831
+ }
832
+ engine.subst.set(curId, constructorType);
833
+ // Also collect the rewrite so types that already have the function
834
+ // type baked in (not via a TVar) can be post-processed.
835
+ engine.constraintConstructorRewrites.push({ from: resolved, to: constructorType });
836
+ }
837
+ // Methods exist — also verify their signature shapes match the constraint
838
+ const def = (0, constraintRegistry_1.lookupConstraint)(pending.constraintName);
839
+ if (def) {
840
+ for (const req of def.methods) {
841
+ // Rep-covered methods are validated at `::rep` registration time
842
+ // against the local annotation; skip the registry shape check
843
+ // here (the registered method, if any, may be hidden/builtin and
844
+ // is intentionally not the satisfying implementation).
845
+ if (repMethodNames.has(req.name))
846
+ continue;
847
+ const entry = (0, methodRegistry_1.lookupMethod)(typeToCheck, req.name);
848
+ if (!entry)
849
+ continue;
850
+ const shapeMismatch = (0, constraintRegistry_1.checkConstraintMethodShape)(def.typeVar, req.signature, typeToCheck, entry);
851
+ if (shapeMismatch) {
852
+ engine.addDiag(`Type '${typeToCheck}' does not satisfy constraint '${pending.constraintName}': method '${req.name}' ${shapeMismatch}`, pending.node);
853
+ }
854
+ }
855
+ }
856
+ }
857
+ }
858
+ }
859
+ /**
860
+ * Validate pending structural-union constraints. Each constrained type
861
+ * variable must unify with at least one of the listed alternatives.
862
+ * The first alternative that successfully unifies wins; its substitution
863
+ * is committed to the engine. If none unify, a diagnostic is emitted.
864
+ * Variables still unresolved at this point are left alone (no diagnostic).
865
+ */
866
+ function validatePendingUnionConstraints(engine) {
867
+ for (const pending of engine.pendingUnionConstraints) {
868
+ const resolved = engine.subst.apply({ tag: 'TVar', id: pending.varId, name: '' });
869
+ // If still a free type variable, the constraint cannot constrain
870
+ // anything yet — leave it alone (matches nominal-constraint behaviour).
871
+ if (resolved.tag === 'TVar')
872
+ continue;
873
+ // Suppress cascade diagnostics when the resolved type is poisoned
874
+ // by a prior $error: the originating error already informs the user,
875
+ // and `Type '$error' does not satisfy union constraint 'X'` is noise.
876
+ if ((0, types_1.containsErrorType)(resolved))
877
+ continue;
878
+ // Resolved to a union (e.g. when an array literal `[1, "3"]` was
879
+ // bound to a free element TVar and widened to `Number | String`):
880
+ // EVERY member of the resolved union must satisfy at least one
881
+ // alternative, otherwise the constraint is violated. Without this,
882
+ // `unify(Number | String, String)` would succeed (because String is
883
+ // in the union) and a constraint like `(String | Boolean) b` would
884
+ // be silently satisfied even though Number is not allowed.
885
+ if (resolved.tag === 'TCon' && resolved.name === 'Union' && resolved.args.length > 0) {
886
+ const offending = [];
887
+ for (const member of resolved.args) {
888
+ const memResolved = engine.subst.apply(member);
889
+ // Free TVars inside the union are non-determinative — skip.
890
+ if (memResolved.tag === 'TVar')
891
+ continue;
892
+ let memMatched = false;
893
+ for (const alt of pending.alternatives) {
894
+ const altResolved = engine.subst.apply(alt);
895
+ const snap = engine.subst.snapshot();
896
+ try {
897
+ (0, unify_1.unify)(memResolved, altResolved);
898
+ memMatched = true;
899
+ engine.subst.restore(snap); // don't commit — purely a check
900
+ break;
901
+ }
902
+ catch (e) {
903
+ if (!(e instanceof unify_1.UnificationError))
904
+ throw e;
905
+ engine.subst.restore(snap);
906
+ }
907
+ }
908
+ if (!memMatched)
909
+ offending.push(memResolved);
910
+ }
911
+ if (offending.length > 0) {
912
+ const offDisp = offending.length === 1
913
+ ? `'${(0, types_1.prettyTypeToString)(offending[0])}'`
914
+ : offending.map(o => `'${(0, types_1.prettyTypeToString)(o)}'`).join(', ');
915
+ engine.addDiag(`Type ${offDisp} does not satisfy union constraint '${pending.displayName}'`, pending.node);
916
+ }
917
+ continue;
918
+ }
919
+ let matched = false;
920
+ for (const alt of pending.alternatives) {
921
+ const altResolved = engine.subst.apply(alt);
922
+ const snapshot = engine.subst.snapshot();
923
+ try {
924
+ const delta = (0, unify_1.unify)(resolved, altResolved);
925
+ // Commit: merge delta into engine subst.
926
+ for (const [k, v] of delta.entries()) {
927
+ engine.subst.set(k, v);
928
+ }
929
+ matched = true;
930
+ break;
931
+ }
932
+ catch (e) {
933
+ if (!(e instanceof unify_1.UnificationError))
934
+ throw e;
935
+ // Restore and try next alternative.
936
+ engine.subst.restore(snapshot);
937
+ }
938
+ }
939
+ if (!matched) {
940
+ engine.addDiag(`Type '${(0, types_1.prettyTypeToString)(resolved)}' does not satisfy union constraint '${pending.displayName}'`, pending.node);
941
+ }
942
+ }
943
+ }
944
+ /**
945
+ * Post-process a type by replacing constrained function types with their
946
+ * constructor names. E.g. replaces `a -> Identity a` with `Identity`
947
+ * inside `EitherT e (a -> Identity a) String` → `EitherT e Identity String`.
948
+ * Only rewrites nested occurrences (type args, function params/results,
949
+ * record fields) — not the top-level type itself, so that a standalone
950
+ * variable like `Identity :: a -> Identity a` keeps its function type.
951
+ */
952
+ function applyConstraintConstructorRewrites(engine, t) {
953
+ if (engine.constraintConstructorRewrites.length === 0)
954
+ return t;
955
+ return applyConstraintConstructorRewritesInner(engine, t, false);
956
+ }
957
+ function applyConstraintConstructorRewritesInner(engine, t, nested) {
958
+ // Only replace when this is a nested occurrence (inside a TCon arg, TFun, etc.)
959
+ if (nested) {
960
+ for (const rw of engine.constraintConstructorRewrites) {
961
+ if (typesStructurallyMatch(t, rw.from)) {
962
+ return rw.to;
963
+ }
964
+ }
965
+ }
966
+ switch (t.tag) {
967
+ case 'TCon':
968
+ return (0, types_1.tCon)(t.name, t.args.map(a => applyConstraintConstructorRewritesInner(engine, a, true)));
969
+ case 'TFun':
970
+ return { tag: 'TFun', param: applyConstraintConstructorRewritesInner(engine, t.param, true), result: applyConstraintConstructorRewritesInner(engine, t.result, true) };
971
+ case 'TRecord': {
972
+ const fields = {};
973
+ for (const k in t.fields) {
974
+ fields[k] = applyConstraintConstructorRewritesInner(engine, t.fields[k], true);
975
+ }
976
+ return (0, types_1.tRecord)(fields);
977
+ }
978
+ default:
979
+ return t;
980
+ }
981
+ }
982
+ /**
983
+ * Check if two types are structurally identical using a consistent TVar mapping.
984
+ * TVars don't need the same ID — they just need to appear in corresponding positions.
985
+ * E.g. `TVar(1) -> Identity TVar(1)` matches `TVar(99) -> Identity TVar(99)`.
986
+ */
987
+ function typesStructurallyMatch(a, b) {
988
+ const mapping = new Map(); // a-TVar-id → b-TVar-id
989
+ const check = (x, y) => {
990
+ if (x.tag !== y.tag)
991
+ return false;
992
+ if (x.tag === 'TVar' && y.tag === 'TVar') {
993
+ const mapped = mapping.get(x.id);
994
+ if (mapped !== undefined)
995
+ return mapped === y.id;
996
+ mapping.set(x.id, y.id);
997
+ return true;
998
+ }
999
+ if (x.tag === 'TCon' && y.tag === 'TCon') {
1000
+ if (x.name !== y.name || x.args.length !== y.args.length)
1001
+ return false;
1002
+ return x.args.every((arg, i) => check(arg, y.args[i]));
1003
+ }
1004
+ if (x.tag === 'TFun' && y.tag === 'TFun') {
1005
+ return check(x.param, y.param) && check(x.result, y.result);
1006
+ }
1007
+ return false;
1008
+ };
1009
+ return check(a, b);
1010
+ }
1011
+ /**
1012
+ * Bake constructor-style constraints into a type. When a constraint such as
1013
+ * `Pair p => ...` names a known type constructor (not a `::constraint`
1014
+ * class), the constrained variable `p` IS that constructor, so every
1015
+ * occurrence — bare `p` (a TVar) or applied `p c a` (a kv-encoded TCon
1016
+ * `$kv:p:id c a`) — is rewritten to the constructor (`Pair` / `Pair c a`).
1017
+ * The ids of rewritten variables are collected in `bakedIds` so the caller
1018
+ * can drop them from the scheme's quantified-variable list.
1019
+ *
1020
+ * `nameToType` carries BARE (non-applied) type-constraint rewrites where the
1021
+ * target is an arbitrary type rather than a constructor name — used for bare
1022
+ * scalar constraints (`String p` → `p := String`) and structural-union
1023
+ * constraints (`(Number | Undefined) x` → `x := Number | Undefined`).
1024
+ */
1025
+ function bakeCtorConstraintsInType(t, nameToClass, bakedIds, nameToType) {
1026
+ switch (t.tag) {
1027
+ case 'TVar':
1028
+ if (t.name && nameToClass.has(t.name)) {
1029
+ bakedIds.add(t.id);
1030
+ return { tag: 'TCon', name: nameToClass.get(t.name), args: [] };
1031
+ }
1032
+ if (t.name && nameToType && nameToType.has(t.name)) {
1033
+ bakedIds.add(t.id);
1034
+ return nameToType.get(t.name);
1035
+ }
1036
+ return t;
1037
+ case 'TCon': {
1038
+ const newArgs = t.args.map((a) => bakeCtorConstraintsInType(a, nameToClass, bakedIds, nameToType));
1039
+ const kv = (0, types_1.parseKvName)(t.name);
1040
+ if (kv && nameToClass.has(kv.varName)) {
1041
+ bakedIds.add(kv.varId);
1042
+ return { tag: 'TCon', name: nameToClass.get(kv.varName), args: newArgs };
1043
+ }
1044
+ if (newArgs.every((a, i) => a === t.args[i]))
1045
+ return t;
1046
+ return { tag: 'TCon', name: t.name, args: newArgs };
1047
+ }
1048
+ case 'TFun': {
1049
+ const param = bakeCtorConstraintsInType(t.param, nameToClass, bakedIds, nameToType);
1050
+ const result = bakeCtorConstraintsInType(t.result, nameToClass, bakedIds, nameToType);
1051
+ if (param === t.param && result === t.result)
1052
+ return t;
1053
+ return { tag: 'TFun', param, result };
1054
+ }
1055
+ case 'TRecord': {
1056
+ const fields = {};
1057
+ let changed = false;
1058
+ for (const k in t.fields) {
1059
+ const nf = bakeCtorConstraintsInType(t.fields[k], nameToClass, bakedIds, nameToType);
1060
+ if (nf !== t.fields[k])
1061
+ changed = true;
1062
+ fields[k] = nf;
1063
+ }
1064
+ if (!changed)
1065
+ return t;
1066
+ return { ...t, fields };
1067
+ }
1068
+ default:
1069
+ return t;
1070
+ }
1071
+ }
1072
+ /**
1073
+ * Compute the witness type arguments for a `TypeRep <T> v` constraint: the
1074
+ * positional args with the trailing bound variable (`v`) removed. E.g.
1075
+ * `TypeRep Array k` → `[Array]`, so the var binds to `TypeRep Array`.
1076
+ */
1077
+ function typeRepWitnessArgs(c) {
1078
+ if (!c.positionalArgs || c.positionalArgs.length === 0)
1079
+ return [];
1080
+ const last = c.positionalArgs[c.positionalArgs.length - 1];
1081
+ const dropLast = last.tag === 'TVar' && last.name === c.typeVarName;
1082
+ return dropLast ? c.positionalArgs.slice(0, -1) : c.positionalArgs;
1083
+ }
1084
+ /**
1085
+ * Bake constructor-style constraints (`Pair p => ... -> p c a`) into a single
1086
+ * annotation's types, mutating it in place. When a constraint names a known
1087
+ * type CONSTRUCTOR (builtin, `::data`, locally-annotated, or imported) rather
1088
+ * than a `::constraint` class, the constrained variable IS that constructor,
1089
+ * so `p`/`p c a` are rewritten to `Pair`/`Pair c a` and the constraint is
1090
+ * dropped. Applied centrally to every `annotationMap` and `annotationByOffset`
1091
+ * entry so instantiation, the rigid check, the skolemizing method-body path,
1092
+ * hover, and completion all observe the same concrete type. Bare scalar
1093
+ * constraints (var NOT used applied, e.g. `Number run => run -> LimitA run`)
1094
+ * are left intact so they keep their pending-union type-equality semantics.
1095
+ */
1096
+ function bakeCtorConstraintsOnAnnotation(engine, ann) {
1097
+ const cons = ann.scheme?.constraints;
1098
+ if (!cons || cons.length === 0)
1099
+ return;
1100
+ const kvVarNames = new Map();
1101
+ collectKvNamesInType(ann.scheme.type, kvVarNames);
1102
+ if (ann.receiver)
1103
+ collectKvNamesInType(ann.receiver, kvVarNames);
1104
+ if (ann.methodType)
1105
+ collectKvNamesInType(ann.methodType, kvVarNames);
1106
+ const nameToClass = new Map();
1107
+ const nameToType = new Map();
1108
+ const keptConstraints = [];
1109
+ // Variables that occur in the final return type keep their deferred
1110
+ // behaviour for unions, so per-call resolution stays precise
1111
+ // (e.g. `pick :: (String | Number) v => v -> v` ⇒ `pick(5) : Number`).
1112
+ const returnVarNames = new Set();
1113
+ {
1114
+ const retNames = new Map();
1115
+ (0, types_1.collectVarNames)((0, types_1.getReturnType)(ann.scheme.type), retNames);
1116
+ for (const nm of retNames.values())
1117
+ returnVarNames.add(nm);
1118
+ }
1119
+ for (const c of cons) {
1120
+ // Structural-union constraint: `(Number | Undefined) x => … -> …`.
1121
+ // Bake `x := Number | Undefined` only when `x` never appears in the
1122
+ // return type; otherwise leave it as a deferred union constraint so
1123
+ // each call site can resolve to its precise alternative.
1124
+ if (c.unionAlternatives && c.unionAlternatives.length > 0) {
1125
+ if (!returnVarNames.has(c.typeVarName)) {
1126
+ nameToType.set(c.typeVarName, (0, types_1.tUnion)(c.unionAlternatives));
1127
+ }
1128
+ else {
1129
+ keptConstraints.push(c);
1130
+ }
1131
+ continue;
1132
+ }
1133
+ // TypeRep witness constraint: `TypeRep Array k => k -> …` means the
1134
+ // constrained var IS the type representative of the preceding type
1135
+ // (`k := TypeRep Array`), exposing static constructor methods (`.of`, …)
1136
+ // on it. `TypeRep` is a witness marker, not a `::constraint` class, so
1137
+ // bake the binding here and drop the constraint.
1138
+ if (c.className === types_1.T_TYPEREP) {
1139
+ const witnessArgs = typeRepWitnessArgs(c);
1140
+ if (witnessArgs.length === 1) {
1141
+ nameToType.set(c.typeVarName, (0, types_1.tCon)(types_1.T_TYPEREP, witnessArgs));
1142
+ }
1143
+ continue;
1144
+ }
1145
+ // Saturated/partial instance constructor constraint:
1146
+ // `Array String k => k -> …` means the constrained var IS the instance
1147
+ // `Array String` — the leading positional args applied to the named
1148
+ // constructor — not the bare constructor. Bake `k := Array String`.
1149
+ // (`Array k =>`, with no leading args, has no `positionalArgs` and falls
1150
+ // through to the bare-constructor branch below.)
1151
+ if (c.positionalArgs && c.positionalArgs.length >= 2 &&
1152
+ !(0, constraintRegistry_1.lookupConstraint)(c.className) &&
1153
+ ((0, methodRegistry_1.isBuiltinType)(c.className) ||
1154
+ (0, dataTypeRegistry_1.isDataType)(c.className) ||
1155
+ engine.annotationMap.has(c.className) ||
1156
+ engine.importedConstructors.has(c.className) ||
1157
+ typeConstructorArity(c.className) > 0)) {
1158
+ const last = c.positionalArgs[c.positionalArgs.length - 1];
1159
+ if (last.tag === 'TVar' && last.name === c.typeVarName) {
1160
+ const leading = c.positionalArgs.slice(0, -1);
1161
+ nameToType.set(c.typeVarName, (0, types_1.tCon)(c.className, leading));
1162
+ continue;
1163
+ }
1164
+ }
1165
+ const isKnownType = !(0, constraintRegistry_1.lookupConstraint)(c.className) &&
1166
+ ((0, methodRegistry_1.isBuiltinType)(c.className) ||
1167
+ (0, dataTypeRegistry_1.isDataType)(c.className) ||
1168
+ engine.annotationMap.has(c.className) ||
1169
+ engine.importedConstructors.has(c.className) ||
1170
+ typeConstructorArity(c.className) > 0);
1171
+ // Applied constructor constraint: `Pair p => … p c a …`.
1172
+ if (isKnownType && kvVarNames.has(c.typeVarName)) {
1173
+ nameToClass.set(c.typeVarName, c.className);
1174
+ continue;
1175
+ }
1176
+ // Bare type-constraint head: `String p => p -> [p]` or `Array k => k -> k`.
1177
+ // A NULLARY type (String, Number, …) binds the var to that type itself
1178
+ // (`p := String`). A PARAMETRIC constructor used bare (`Array k =>`)
1179
+ // denotes the *constructor*, so bind the var to its `TypeRep` witness
1180
+ // (`k := TypeRep Array`) — exposing static methods and matching the
1181
+ // explicit `TypeRep Array k =>` form.
1182
+ if (isKnownType && !c.isApplied) {
1183
+ if (typeConstructorArity(c.className) > 0) {
1184
+ nameToType.set(c.typeVarName, (0, types_1.tCon)(types_1.T_TYPEREP, [(0, types_1.tCon)(c.className, [])]));
1185
+ }
1186
+ else {
1187
+ nameToType.set(c.typeVarName, { tag: 'TCon', name: c.className, args: [] });
1188
+ }
1189
+ continue;
1190
+ }
1191
+ keptConstraints.push(c);
1192
+ }
1193
+ if (nameToClass.size === 0 && nameToType.size === 0)
1194
+ return;
1195
+ const bakedIds = new Set();
1196
+ const newType = bakeCtorConstraintsInType(ann.scheme.type, nameToClass, bakedIds, nameToType);
1197
+ if (ann.receiver)
1198
+ ann.receiver = bakeCtorConstraintsInType(ann.receiver, nameToClass, bakedIds, nameToType);
1199
+ if (ann.methodType)
1200
+ ann.methodType = bakeCtorConstraintsInType(ann.methodType, nameToClass, bakedIds, nameToType);
1201
+ ann.scheme = {
1202
+ ...ann.scheme,
1203
+ type: newType,
1204
+ constraints: keptConstraints,
1205
+ vars: ann.scheme.vars.filter((id) => !bakedIds.has(id)),
1206
+ };
1207
+ }
1208
+ //# sourceMappingURL=constraints.js.map