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,1127 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Inference — Algorithm W for JavaScript AST nodes
4
+ //
5
+ // Plain language: this is the conductor of the whole analysis. The
6
+ // `InferenceEngine` class owns all shared state for one file's analysis —
7
+ // the environment (names → types), the substitution (placeholder answers),
8
+ // the diagnostics list and the annotation maps — and drives the passes:
9
+ // 1. setup — read all comments/annotations/directives (setupPass.ts)
10
+ // 2. walk — visit every statement and expression, inferring types
11
+ // (statements.ts, expressions.ts, calls.ts, …)
12
+ // 3. finish — validate parked constraints, check annotation promises,
13
+ // and pack up the result (constraints.ts, results.ts)
14
+ // The heavy logic lives in the sibling modules, which receive the engine as
15
+ // their first argument; this file wires them together.
16
+ //
17
+ // "Algorithm W" is the name of the classic Hindley–Milner inference recipe
18
+ // this engine follows.
19
+ // ============================================================================
20
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ var desc = Object.getOwnPropertyDescriptor(m, k);
23
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
24
+ desc = { enumerable: true, get: function() { return m[k]; } };
25
+ }
26
+ Object.defineProperty(o, k2, desc);
27
+ }) : (function(o, m, k, k2) {
28
+ if (k2 === undefined) k2 = k;
29
+ o[k2] = m[k];
30
+ }));
31
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
32
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
33
+ }) : function(o, v) {
34
+ o["default"] = v;
35
+ });
36
+ var __importStar = (this && this.__importStar) || (function () {
37
+ var ownKeys = function(o) {
38
+ ownKeys = Object.getOwnPropertyNames || function (o) {
39
+ var ar = [];
40
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
41
+ return ar;
42
+ };
43
+ return ownKeys(o);
44
+ };
45
+ return function (mod) {
46
+ if (mod && mod.__esModule) return mod;
47
+ var result = {};
48
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
49
+ __setModuleDefault(result, mod);
50
+ return result;
51
+ };
52
+ })();
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ exports.InferenceEngine = exports.defaultEnv = exports.exportsToRecord = exports.findConstructor = exports.computeRestType = exports.freshVars = exports.isOpenWorldExports = exports.markOpenWorldExports = exports.UNTYPED_MODULE = void 0;
55
+ const parsing_1 = require("../parsing");
56
+ const types_1 = require("../hm/types");
57
+ const substitution_1 = require("../hm/substitution");
58
+ const env_1 = require("../hm/env");
59
+ Object.defineProperty(exports, "defaultEnv", { enumerable: true, get: function () { return env_1.defaultEnv; } });
60
+ const session_1 = require("../registries/session");
61
+ const typeUtils_1 = require("../hm/typeUtils");
62
+ const annotations_1 = require("./annotations");
63
+ const types_2 = require("./types");
64
+ Object.defineProperty(exports, "UNTYPED_MODULE", { enumerable: true, get: function () { return types_2.UNTYPED_MODULE; } });
65
+ const helpers_1 = require("./helpers");
66
+ Object.defineProperty(exports, "freshVars", { enumerable: true, get: function () { return helpers_1.freshVars; } });
67
+ Object.defineProperty(exports, "computeRestType", { enumerable: true, get: function () { return helpers_1.computeRestType; } });
68
+ Object.defineProperty(exports, "findConstructor", { enumerable: true, get: function () { return helpers_1.findConstructor; } });
69
+ Object.defineProperty(exports, "exportsToRecord", { enumerable: true, get: function () { return helpers_1.exportsToRecord; } });
70
+ const stmtFns = __importStar(require("./statements"));
71
+ const constraintFns = __importStar(require("./constraints"));
72
+ const resultFns = __importStar(require("./results"));
73
+ const moduleReps_1 = require("./moduleReps");
74
+ const setupFns = __importStar(require("./setupPass"));
75
+ const unifyDiag = __importStar(require("./unifyDiag"));
76
+ const unify_1 = require("../hm/unify");
77
+ const exprFns = __importStar(require("./expressions"));
78
+ const exprMemberFns = __importStar(require("./expr-member"));
79
+ const callFns = __importStar(require("./calls"));
80
+ const modFns = __importStar(require("./modules"));
81
+ var types_3 = require("./types");
82
+ Object.defineProperty(exports, "markOpenWorldExports", { enumerable: true, get: function () { return types_3.markOpenWorldExports; } });
83
+ Object.defineProperty(exports, "isOpenWorldExports", { enumerable: true, get: function () { return types_3.isOpenWorldExports; } });
84
+ // -----------------------------------------------------------------------
85
+ // Import deduplication — offset-preserving preprocessing
86
+ // -----------------------------------------------------------------------
87
+ /** Blank duplicate import lines with spaces so the parser doesn't throw
88
+ * "Identifier 'X' has already been declared" while keeping all offsets stable. */
89
+ function deduplicateImports(source) {
90
+ const seen = new Set();
91
+ const re = /^(import\s+(?:(\w+)|(?:\{([^}]+)\})|(?:\*\s+as\s+(\w+)))\s+from\s+['"][^'"]+['"];?\s*)$/gm;
92
+ return source.replace(re, (match, _full, def, named, ns) => {
93
+ const names = [];
94
+ if (def)
95
+ names.push(def);
96
+ if (ns)
97
+ names.push(ns);
98
+ if (named) {
99
+ for (const part of named.split(',')) {
100
+ const t = part.trim();
101
+ const as = t.match(/\w+\s+as\s+(\w+)/);
102
+ names.push(as ? as[1] : t);
103
+ }
104
+ }
105
+ if (names.some(n => seen.has(n)))
106
+ return match.replace(/[^\n]/g, ' ');
107
+ names.forEach(n => seen.add(n));
108
+ return match;
109
+ });
110
+ }
111
+ // -----------------------------------------------------------------------
112
+ // Helpers
113
+ // -----------------------------------------------------------------------
114
+ /**
115
+ * Collect `[start, end]` source ranges of every top-level binding in the
116
+ * program — `VariableDeclarator` (incl. inside exports), `FunctionDeclaration`,
117
+ * and `ClassDeclaration`. Each entry is tagged with whether the binding
118
+ * name matches an entry in the supplied annotation map so the diagnostics
119
+ * service can distinguish "annotated body" vs "any body" suppression.
120
+ *
121
+ * Nested members (class methods, inner functions, deeply-nested
122
+ * declarators) are intentionally NOT enumerated — they are already covered
123
+ * by their enclosing top-level binding's extent.
124
+ */
125
+ function collectTopLevelBindingExtents(ast, annotations) {
126
+ const out = [];
127
+ const hasAnyAnnotation = (name) => {
128
+ if (annotations.has(name))
129
+ return true;
130
+ // Method/sumtype style: `Foo#bar`, `Foo.bar`, `Foo$prototype$bar`.
131
+ for (const key of annotations.keys()) {
132
+ if (key.startsWith(name + '#') || key.startsWith(name + '.') || key.startsWith(name + '$prototype$')) {
133
+ return true;
134
+ }
135
+ }
136
+ return false;
137
+ };
138
+ for (const rawStmt of ast.body) {
139
+ const stmt = (rawStmt.type === 'ExportNamedDeclaration' || rawStmt.type === 'ExportDefaultDeclaration')
140
+ && rawStmt.declaration ? rawStmt.declaration : rawStmt;
141
+ if (stmt.type === 'VariableDeclaration') {
142
+ for (const declarator of stmt.declarations) {
143
+ if (!declarator.init)
144
+ continue;
145
+ const id = declarator.id;
146
+ const name = id?.name;
147
+ if (!name)
148
+ continue;
149
+ out.push({ start: declarator.start, end: declarator.end, annotated: hasAnyAnnotation(name) });
150
+ }
151
+ continue;
152
+ }
153
+ if (stmt.type === 'FunctionDeclaration' && stmt.id?.name) {
154
+ out.push({ start: stmt.start, end: stmt.end, annotated: hasAnyAnnotation(stmt.id.name) });
155
+ continue;
156
+ }
157
+ if (stmt.type === 'ClassDeclaration' && stmt.id?.name) {
158
+ out.push({ start: stmt.start, end: stmt.end, annotated: hasAnyAnnotation(stmt.id.name) });
159
+ continue;
160
+ }
161
+ }
162
+ return out;
163
+ }
164
+ // -----------------------------------------------------------------------
165
+ // The inference engine
166
+ // -----------------------------------------------------------------------
167
+ class InferenceEngine {
168
+ constructor() {
169
+ /** @internal */ this.subst = new substitution_1.Substitution();
170
+ /** @internal */ this.diagnostics = [];
171
+ /** @internal */ this.nodeTypes = new Map();
172
+ /** @internal Map from a top-level binding declaration's start offset to its
173
+ * generalized scheme. Hover uses this to display the generic type of a
174
+ * polymorphic binding at its declaration site, instead of the live
175
+ * substitution-applied node type which downstream call sites may have
176
+ * specialized (e.g. a generic `getPath` shown with a concrete record). */
177
+ this.declaredSchemes = new Map();
178
+ /** @internal */ this.annotationMap = new Map();
179
+ /** @internal */ this.annotationByOffset = new Map();
180
+ /** @internal */ this.methodSignatures = new Map();
181
+ /** @internal Maps every rigid skolem name (`§N`) minted while checking an
182
+ * annotated function body back to the annotation's display letter, so
183
+ * skolems can be scrubbed out of hover types and diagnostic messages. */
184
+ this.skolemDisplayNames = new Map();
185
+ /** @internal Origin (annotation name + comment range) of each rigid skolem.
186
+ * Used to attach related-information to a diagnostic when two DISTINCT
187
+ * skolems carrying the SAME display letter (e.g. the `a` of a method
188
+ * annotation vs the `a` of the enclosing factory's signature) collide in
189
+ * one message. */
190
+ this.skolemOrigins = new Map();
191
+ /** @internal Stack of the annotated RETURN types of the function(s) whose
192
+ * bodies are currently being inferred. Lets a nested method annotation
193
+ * (`Type#m :: Type e a ~> …` above a const inside a factory returning
194
+ * `Type e a`) link its receiver variables to the factory's own signature
195
+ * variables — the record under construction IS the receiver. */
196
+ this.enclosingAnnotatedReturns = [];
197
+ /** @internal */ this.importResolver = null;
198
+ /** @internal */ this.typeDirectiveResolver = null;
199
+ /** @internal */ this.importTypeAliasResolver = null;
200
+ /** @internal Names explicitly exported via `export`, `module.exports`, or `exports.X`. */
201
+ this.exportedNames = new Set();
202
+ /** @internal Inferred RHS type for `exports.X = expr` assignments — used when X is not bound in env. */
203
+ this.cjsExportTypes = new Map();
204
+ /**
205
+ * @internal Names exported through `module.exports = { key: <expr> }` whose
206
+ * value is NOT the same-named identifier: the export's type is the
207
+ * property VALUE's type (from {@link cjsExportTypes}), never an unrelated
208
+ * env binding that happens to share the key's name.
209
+ */
210
+ this.cjsValueExports = new Set();
211
+ /** @internal Type of `module.exports = { … }` — the CommonJS module value, exported as `default` for ESM interop. */
212
+ this.cjsObjectExportType = null;
213
+ /** @internal The module uses CommonJS exports (`module.exports…` / `exports.X`). */
214
+ this.usesCjsExports = false;
215
+ /**
216
+ * @internal Unannotated static-member assignments `Obj.prop = <fn>` keyed by
217
+ * object identifier name -> (property name -> resolved function type). Used
218
+ * by `buildExportMap` so a default export's static factories (e.g.
219
+ * `Response.Redirect = _Redirect;`) are exported cross-file even without an
220
+ * explicit `// Response.Redirect :: ...` annotation.
221
+ */
222
+ this.staticMemberTypes = new Map();
223
+ /** @internal Pending constraint checks: maps fresh type var id -> { constraintName, node } */
224
+ this.pendingConstraints = [];
225
+ /** @internal `::rep` directives parsed from the current file (constraint representations). */
226
+ this.fileReps = [];
227
+ /** @internal `::rep` representatives collected from imported schemes. These
228
+ * let an imported constrained function's reps satisfy constraint checks in
229
+ * the importing file (and propagate further on re-export). */
230
+ this.importedReps = [];
231
+ /** @internal Pending structural-union constraint checks. The constrained
232
+ * type variable must unify with one of the listed alternatives. */
233
+ this.pendingUnionConstraints = [];
234
+ /** @internal Map from kind-variable id to constraint names (for hover/completion). */
235
+ this.kvConstraints = new Map();
236
+ /** @internal Rank-N: skolem name → constraint classes promised by the
237
+ * `forall` that minted it (incl. superclass closure). A pending
238
+ * constraint that resolves to such a skolem and is promised is satisfied. */
239
+ this.rankNSkolemPromises = new Map();
240
+ /** @internal Map from kind-variable id to applied constraint names (constraints on the constructor, e.g. Monoid (f a)). */
241
+ this.kvConstructorConstraints = new Map();
242
+ /** @internal Constraint constructor rewrites: function types to replace with constructors in post-processing. */
243
+ this.constraintConstructorRewrites = [];
244
+ /** @internal When true, auto-union is suppressed (inside annotated declarations). */
245
+ this.suppressAutoUnion = false;
246
+ /** @internal Var ids that must survive per-element freshening of expanded
247
+ * union element types in array literals. Set by call inference to the
248
+ * free vars of the callee's result type: a var occurring both in the
249
+ * element union and the result (e.g. the params var `p` in
250
+ * `[Selector p] -> Tag p o`) threads element contributions into the
251
+ * result, so freshening it per element would sever the link. */
252
+ this.pinnedElementVarIds = null;
253
+ /** @internal Stack of yielded-type collectors, one frame per generator
254
+ * function currently being inferred. The `YieldExpression` inference case
255
+ * pushes each yielded value type onto the top frame so the function's
256
+ * caller-visible return type can be modelled as `Generator <yield>`. */
257
+ this.generatorYieldStack = [];
258
+ /** @internal Names of bindings that are generator functions (`function* f`,
259
+ * `const f = function* () {}`). A call to one of these names yields a
260
+ * `Generator <element>` value rather than the function's element type. */
261
+ this.generatorFunctionNames = new Set();
262
+ /** @internal When true, suppress "Infinite type" diagnostics (annotated constrained self-recursion). */
263
+ this.suppressInfiniteType = false;
264
+ /** @internal When >0, `poisonFreeVars` is a no-op. Set during speculative
265
+ * overload-branch trials so a nested unification failure does not bake the
266
+ * `$error` sentinel into a captured branch remainder (the substitution is
267
+ * rolled back anyway; any genuine failure re-surfaces when a branch is
268
+ * actually committed). */
269
+ this.suppressPoisonDepth = 0;
270
+ /** @internal Name of the top-level binding whose initializer is currently being inferred.
271
+ * Used to attribute an infinite-type (occurs-check) diagnostic to the binding
272
+ * (e.g. "applyArgs has an infinite type ..."). */
273
+ this.currentBindingName = undefined;
274
+ /** @internal Set when an infinite type error was suppressed during constrained annotation body inference. */
275
+ this.infiniteTypeSuppressedDuringAnnotation = false;
276
+ /** @internal Monotonic counter bumped each time the occurs check (infinite type)
277
+ * fires in `unifyWithDiagnostic`. Used to detect whether a binding's body
278
+ * inference produced an infinite type so the signature can overrule the
279
+ * downstream annotation-vs-body mismatch. */
280
+ this.occursCheckCount = 0;
281
+ /** @internal applyArgs-style peeling side-table. When a concrete curried
282
+ * function is applied to a combinator whose parameter is a spread arrow
283
+ * chain `(a -> b -> ... -> z)` and whose result is a spread-array applier
284
+ * `[a, b, ...] -> z`, we record the function's flattened parameter list and
285
+ * terminal result keyed by the (inner) call node. The subsequent array
286
+ * application looks this up via `node.callee` to derive the peeled result
287
+ * type (partial application) and flag over-application. */
288
+ this.spreadChainPeel = new Map();
289
+ /** @internal Type aliases: uppercase names mapped to their aliased type (e.g. Person -> { name: String, age: Number }). */
290
+ this.typeAliases = new Map();
291
+ /** @internal Type alias var names for polymorphic expansion (e.g. TypedArray -> ['a', 'b']). */
292
+ this.typeAliasVars = new Map();
293
+ /** @internal Constructor / callable-value annotations imported from
294
+ * sidecars or project overrides. Consulted by `tryConstructorCallable`
295
+ * when a value of an uppercase TCon is invoked but the local
296
+ * `annotationMap` has no entry for that name (typical for values
297
+ * returned from a third-party package and called locally). */
298
+ this.importedConstructors = new Map();
299
+ /** @internal Instance-callable schemes, declared via `Name() :: T`.
300
+ * An entry's array contains every overload declared for that name in
301
+ * declaration order, merged from the local source and any imported
302
+ * sidecars (local entries take precedence on name collision).
303
+ * Consulted by `tryConstructorCallable` and by hover / signature help
304
+ * when a value of an uppercase TCon (e.g. `QueryTag {row}`) is invoked
305
+ * or its overloads are surfaced. */
306
+ this.instanceCallables = new Map();
307
+ /** @internal `[start, end]` source ranges of every top-level binding the
308
+ * engine recognizes (`VariableDeclarator`, `FunctionDeclaration`,
309
+ * `ClassDeclaration`). Populated from the AST after a successful parse
310
+ * and surfaced on the result for `trustAnnotations: 'all-bodies'`. */
311
+ this.bindingExtents = [];
312
+ /** @internal Map from AST node end offset to its inferred type. Used for completion after call expressions. */
313
+ this.nodeTypesByEnd = new Map();
314
+ /** @internal Map from an arrow/function-expression node's start offset to its
315
+ * inferred FUNCTION type. Recorded separately from {@link nodeTypes}
316
+ * because a function's start offset collides with its first parameter
317
+ * identifier (which wins in `nodeTypes` for hover). Hover uses this map to
318
+ * pick the tightest enclosing function scope when seeding display-letter
319
+ * assignment, so sibling body-local bindings get distinct, source-ordered
320
+ * letters (`n :: b`, `xs :: c`) instead of each independently grabbing the
321
+ * next free letter. */
322
+ this.functionNodeTypes = new Map();
323
+ /** @internal Identifier name from `module.exports = X` or `export default X` for default export resolution. */
324
+ this.defaultExportName = null;
325
+ /** @internal Maps local binding name to the import specifier it came from (for default imports). */
326
+ this.defaultImportSources = new Map();
327
+ /** @internal Names of auto-detected curry wrapper functions (from spread-tuple type signatures). */
328
+ this.curryFunctionNames = new Set();
329
+ /** curryN-style wrappers: name → number of leading arguments. */
330
+ this.curryNFunctionNames = new Map();
331
+ /** @internal Maps a dotted member-assignment name (`Param.Path`) to the
332
+ * 0-based indices of trailing function parameters with JS body defaults.
333
+ * Consulted by call-site arity checks for `obj.prop(...)` so that
334
+ * trailing missing args are accepted when the implementation marks
335
+ * them optional via `(x = …)`. */
336
+ this.optionalParamSlotsByDottedName = new Map();
337
+ /** @internal After a curry wrapper call, this holds true to mark the next variable binding as curried. */
338
+ this.pendingIsCurriedResult = false;
339
+ /** @internal Pending conditional return info detected during function body inference. */
340
+ this.pendingConditionalReturn = null;
341
+ /** @internal Set of node start offsets whose bindings are curried. */
342
+ this.curriedNodes = new Set();
343
+ /** @internal Maps a call's callee start offset to the index of the
344
+ * overload branch that matched the actual arguments (for hover /
345
+ * signature help to surface only the selected overload). */
346
+ this.callSiteOverloadIndex = new Map();
347
+ /** @internal Set of offsets where an unbound-variable diagnostic was raised. */
348
+ this.unboundIdentifiers = new Set();
349
+ /** @internal Set of offsets where property access occurred on an unconstrained type variable. */
350
+ this.unconstrainedPropAccesses = new Set();
351
+ /** @internal Property accesses on a still-unresolved TVar receiver, parked
352
+ * for late re-resolution. When later unification pins the receiver to a
353
+ * concrete type (e.g. the data argument of a curried annotated `map`
354
+ * arriving AFTER the callback), the member is looked up again and its
355
+ * type is unified with the placeholder result var — so `s => s.length`
356
+ * resolves to `String -> Number` instead of staying `s -> b`. */
357
+ this.deferredMemberAccesses = [];
358
+ /** @internal Set of `TypeName#propName` for properties assigned via `this.prop = ...` in constructors. */
359
+ this.constructorProperties = new Set();
360
+ /** @internal Map of `TypeName##privateName` -> Type for private class fields and methods. */
361
+ this.privateClassMembers = new Map();
362
+ /**
363
+ * @internal Provenance of top-level constructor-like bindings, used to
364
+ * decide how `.constructor` should be typed and whether `new` is required.
365
+ * - `'class'` : `class Foo { ... }`
366
+ * - `'function-this'` : `function Foo(){ this.x = ... }` style constructor
367
+ * - `'arrow-factory'` : `const Foo = (...) => ({...})` — runtime returns Object
368
+ * - `'sumtype'` : registered `@sumtype` root name
369
+ * - `'sumtype-variant'` : variant of an `@sumtype` declaration
370
+ */
371
+ this.constructorProvenance = new Map();
372
+ /**
373
+ * @internal Map from a `.constructor` property-node start offset to the
374
+ * parent sumtype name (e.g. `Maybe`). Populated by
375
+ * `inferTConConstructorAccess` so hover can surface the parent sumtype
376
+ * declaration alongside the constructor's type.
377
+ */
378
+ this.constructorParentSumtype = new Map();
379
+ /**
380
+ * @internal Map from a `.constructor` property-node start offset to the
381
+ * built-in type name (`'Array'`, `'Function'`, …) when the access was
382
+ * resolved via `builtinConstructorType`. Used by call-site logic to
383
+ * specialise the return type (e.g. widen `Array(...)` to a union of arg
384
+ * element types) without piping the receiver through unification.
385
+ */
386
+ this.builtinCtorKind = new Map();
387
+ /**
388
+ * @internal Name-keyed propagation of `builtinCtorKind`. When a
389
+ * declarator's init is a `.constructor` access tagged with a builtin
390
+ * kind, the declared name maps to that kind so subsequent call sites
391
+ * (`const ac = [].constructor; ac(1,2)`) can specialise. Names are
392
+ * module-scoped (last write wins) — this is best-effort, not lexical.
393
+ */
394
+ this.builtinCtorByVarName = new Map();
395
+ /** @internal See InferenceResult.frozenPropertyTypeStr. */
396
+ this.frozenPropertyTypeStr = new Map();
397
+ /** @internal See InferenceResult.frozenParamType. */
398
+ this.frozenParamType = new Map();
399
+ /** @internal When set, union-vs-expected diagnostics report on this node (the enclosing annotated method). */
400
+ this.annotationMethodNode = null;
401
+ /** Function node whose annotation is checked by its enclosing `const`
402
+ * binding (body skolemized via annotationByOffset, validated in
403
+ * stmt-bindings like a `function` declaration) — the inline-annotation
404
+ * validation in inferFunctionExpression skips it. */
405
+ this.annotationCheckedByBinding = null;
406
+ /** Lexically scoped annotation type variables (letter → enclosing body
407
+ * skolem); see inferFunctionExpression in expr-functions.ts. */
408
+ this.scopedTypeVars = new Map();
409
+ /** Row variables of the parameters of the functions whose bodies are
410
+ * being checked against their own annotation. Reading a field outside
411
+ * such a row is an error; a row that is not in this set gains the field
412
+ * (see the open-record case in expr-member.ts). */
413
+ this.rigidRowIds = new Set();
414
+ /** Local type equalities in force while inferring the true branch of a
415
+ * `::narrow C` guard on a value of abstract type `f a` (`isArray (xs)`
416
+ * with `xs :: f a`): `f ≡ C` holds INSIDE the branch only. A `return`
417
+ * there of type `C x` is re-expressed as `f x` (see `returnTypeOverrides`)
418
+ * so the branch never pins `f` for the whole function. */
419
+ this.localKindEqs = [];
420
+ /** The inferred type of each `return` statement inferred through the
421
+ * statement path (re-expressed under `localKindEqs` where they apply). */
422
+ this.returnTypeOverrides = new Map();
423
+ /** Each declaration's own annotation (overloads merged), by node start —
424
+ * see `buildAnnotationsByDeclaration`. */
425
+ this.annotationsByDeclaration = new Map();
426
+ /** @internal Bound version of addDiag for passing to helpers. */
427
+ this.boundAddDiag = this.addDiag.bind(this);
428
+ /**
429
+ * Per-engine type-variable allocator. Installed as the *active* allocator
430
+ * at the start of {@link infer} so that every `tVar()` call during this
431
+ * run uses this engine's counter.
432
+ */
433
+ this.allocator = new types_1.TypeVarAllocator();
434
+ /**
435
+ * Project-level globals source (from `globals.hm` or configured file).
436
+ * Set once by the server; used automatically by every `infer()` call.
437
+ */
438
+ this.globalsSource = null;
439
+ /** `::global` members from the globals file (re-registered with aliases
440
+ * expanded during setup). */
441
+ this.globalDirectiveMethods = [];
442
+ }
443
+ /**
444
+ * Infer types for a JavaScript source string.
445
+ * @param source The JavaScript source code
446
+ * @param env Optional base type environment
447
+ * @param importResolver Optional callback to resolve import specifiers to exported types
448
+ * @param typeDirectiveResolver Optional callback to resolve `// ::types` directives to source code
449
+ * @param importTypeAliasResolver Optional callback to resolve import specifiers to type aliases
450
+ */
451
+ infer(source, env, importResolver, typeDirectiveResolver, importTypeAliasResolver) {
452
+ // Unify may expand a bare alias name of this file (a recursive alias,
453
+ // a name inside an imported type) when it would otherwise fail.
454
+ return (0, unify_1.withAliasExpander)(t => this.maybeExpandAlias(t), () => this.inferInScope(source, env, importResolver, typeDirectiveResolver, importTypeAliasResolver));
455
+ }
456
+ inferInScope(source, env, importResolver, typeDirectiveResolver, importTypeAliasResolver) {
457
+ // Pre-process: remove duplicate import declarations so the parser doesn't
458
+ // throw "Identifier 'X' has already been declared". Offsets stay stable.
459
+ source = deduplicateImports(source);
460
+ // Install this engine's allocator as the active one and reset it.
461
+ (0, types_1.setActiveAllocator)(this.allocator);
462
+ this.allocator.reset();
463
+ this.subst = new substitution_1.Substitution();
464
+ this.diagnostics = [];
465
+ this.nodeTypes = new Map();
466
+ this.declaredSchemes = new Map();
467
+ this.nodeTypesByEnd = new Map();
468
+ this.localKindEqs = [];
469
+ this.returnTypeOverrides = new Map();
470
+ this.functionNodeTypes = new Map();
471
+ this.methodSignatures = new Map();
472
+ this.skolemDisplayNames = new Map();
473
+ this.scopedTypeVars = new Map();
474
+ this.rigidRowIds = new Set();
475
+ this.skolemOrigins = new Map();
476
+ this.enclosingAnnotatedReturns = [];
477
+ this.importResolver = importResolver ?? null;
478
+ this.typeDirectiveResolver = typeDirectiveResolver ?? null;
479
+ this.importTypeAliasResolver = importTypeAliasResolver ?? null;
480
+ this.exportedNames = new Set();
481
+ this.cjsExportTypes = new Map();
482
+ this.cjsValueExports = new Set();
483
+ this.cjsObjectExportType = null;
484
+ this.usesCjsExports = false;
485
+ this.staticMemberTypes = new Map();
486
+ this.pendingConstraints = [];
487
+ this.fileReps = [];
488
+ this.importedReps = [];
489
+ this.pendingUnionConstraints = [];
490
+ this.kvConstraints = new Map();
491
+ this.rankNSkolemPromises = new Map();
492
+ this.kvConstructorConstraints = new Map();
493
+ this.constraintConstructorRewrites = [];
494
+ this.defaultExportName = null;
495
+ this.curryFunctionNames = new Set();
496
+ this.curryNFunctionNames = new Map();
497
+ this.optionalParamSlotsByDottedName = new Map();
498
+ this.pendingIsCurriedResult = false;
499
+ this.pendingConditionalReturn = null;
500
+ this.curriedNodes = new Set();
501
+ this.callSiteOverloadIndex = new Map();
502
+ this.unboundIdentifiers = new Set();
503
+ this.unconstrainedPropAccesses = new Set();
504
+ this.deferredMemberAccesses = [];
505
+ this.constructorProperties = new Set();
506
+ this.privateClassMembers = new Map();
507
+ this.constructorProvenance = new Map();
508
+ this.constructorParentSumtype = new Map();
509
+ this.builtinCtorKind = new Map();
510
+ this.builtinCtorByVarName = new Map();
511
+ this.frozenPropertyTypeStr = new Map();
512
+ this.frozenParamType = new Map();
513
+ this.suppressAutoUnion = false;
514
+ this.generatorYieldStack = [];
515
+ this.generatorFunctionNames = new Set();
516
+ this.suppressInfiniteType = false;
517
+ this.suppressPoisonDepth = 0;
518
+ this.infiniteTypeSuppressedDuringAnnotation = false;
519
+ this.currentBindingName = undefined;
520
+ this.spreadChainPeel = new Map();
521
+ this.defaultImportSources = new Map();
522
+ // Clear custom method/constraint/data-type registrations from previous runs
523
+ (0, session_1.clearGlobalRegistries)();
524
+ // Process ::global directives from the project globals file (if provided).
525
+ // Must run before the file's own directives so that file-level annotations
526
+ // can override globals when needed.
527
+ this.globalDirectiveMethods = [];
528
+ if (this.globalsSource) {
529
+ this.globalDirectiveMethods = (0, annotations_1.processGlobalDirectives)(this.globalsSource, () => { });
530
+ // Also process ::constraint directives from the globals file
531
+ (0, annotations_1.processConstraintDirectives)(this.globalsSource, () => { });
532
+ }
533
+ // Annotation & directive setup pass (→ setupPass.ts): annotation maps,
534
+ // `::` directives, import pre-resolution, validation, constraint baking.
535
+ setupFns.runAnnotationSetup(this, source);
536
+ const currentEnv = env ?? (0, env_1.defaultEnv)();
537
+ let ast;
538
+ let parseErrorDiag = null;
539
+ try {
540
+ ast = (0, parsing_1.parseStrict)(source);
541
+ }
542
+ catch (e) {
543
+ // The façade normalizes the parser's error object into a tightly-scoped
544
+ // { message, start, end } so the editor underlines the exact problem
545
+ // token rather than the whole file.
546
+ const { message: cleanMsg, start, end } = (0, parsing_1.describeParseError)(e, source);
547
+ // Try the loose parser so the rest of the file still type-checks and the
548
+ // LSP keeps providing hover/completion/diagnostics for valid portions.
549
+ try {
550
+ ast = (0, parsing_1.parseLoose)(source);
551
+ // Recovered: emit the syntax error WITHOUT the "Parse error:" prefix
552
+ // so the LSP diagnostic filter (which suppresses noisy parse errors
553
+ // while typing) doesn't hide it. We also tighten the range to the
554
+ // first identifier-like token at `start` so editors highlight the
555
+ // offending name rather than the trailing `=`.
556
+ let tightStart = start;
557
+ let tightEnd = end;
558
+ const idMatch = /^[A-Za-z_$][\w$]*/.exec(source.slice(start));
559
+ if (idMatch) {
560
+ tightEnd = start + idMatch[0].length;
561
+ }
562
+ parseErrorDiag = { message: cleanMsg, start: tightStart, end: tightEnd };
563
+ }
564
+ catch {
565
+ return resultFns.buildResult(this, {
566
+ type: types_1.tVoid,
567
+ diagnostics: [{ message: `Parse error: ${cleanMsg}`, start, end }],
568
+ exports: new Map(),
569
+ topLevelBindings: new Map(),
570
+ });
571
+ }
572
+ }
573
+ let finalEnv;
574
+ let resultType;
575
+ try {
576
+ [finalEnv, resultType] = this.inferProgramWithEnv(ast, currentEnv);
577
+ // Collect top-level binding source ranges for the diagnostics service
578
+ // (powers `trustAnnotations: 'all-bodies'` / `'annotated-bodies'`).
579
+ // Done after inference so `this.annotationMap` is fully populated.
580
+ this.bindingExtents = collectTopLevelBindingExtents(ast, this.annotationMap);
581
+ // Validate pending constraints now that type variables are resolved
582
+ exprMemberFns.flushDeferredMemberAccesses(this);
583
+ this.validatePendingConstraints();
584
+ this.validatePendingUnionConstraints();
585
+ this.validateMissingConstraints();
586
+ }
587
+ catch (e) {
588
+ // Catch-all so a single bad file never crashes the server
589
+ const msg = e instanceof Error ? e.message : String(e);
590
+ const diags = [...this.diagnostics];
591
+ if (parseErrorDiag)
592
+ diags.unshift(parseErrorDiag);
593
+ diags.push({ message: `Internal inference error: ${msg}`, start: 0, end: source.length });
594
+ return resultFns.buildResult(this, {
595
+ type: types_1.tVoid,
596
+ diagnostics: diags,
597
+ exports: new Map(),
598
+ topLevelBindings: new Map(),
599
+ });
600
+ }
601
+ // Build exports, top-level bindings, and post-process constraint rewrites
602
+ const exportMap = resultFns.buildExportMap(this, finalEnv, currentEnv);
603
+ (0, moduleReps_1.setModuleReps)(exportMap, [...this.fileReps, ...this.importedReps]);
604
+ const topLevelBindings = resultFns.buildTopLevelBindings(this, finalEnv, currentEnv);
605
+ resultFns.postProcessConstraintRewrites(this);
606
+ resultFns.overrideSumtypeIdentifierTypes(this, source, topLevelBindings);
607
+ const finalDiags = parseErrorDiag
608
+ ? [parseErrorDiag, ...this.diagnostics]
609
+ : this.diagnostics;
610
+ return resultFns.buildResult(this, {
611
+ type: this.subst.apply(resultType),
612
+ diagnostics: finalDiags,
613
+ exports: exportMap,
614
+ topLevelBindings,
615
+ });
616
+ }
617
+ // =======================================================================
618
+ // infer() result helpers → results.ts
619
+ // =======================================================================
620
+ // =======================================================================
621
+ // Statement delegates (→ statements.ts)
622
+ // =======================================================================
623
+ inferProgramWithEnv(program, env) {
624
+ return stmtFns.inferProgramWithEnv(this, program, env);
625
+ }
626
+ inferStatement(node, env) {
627
+ return stmtFns.inferStatement(this, node, env);
628
+ }
629
+ inferVariableDeclaration(node, env) {
630
+ return stmtFns.inferVariableDeclaration(this, node, env);
631
+ }
632
+ inferNamedBinding(name, decl, env, nodeKind, parentStart) {
633
+ return stmtFns.inferNamedBinding(this, name, decl, env, nodeKind, parentStart);
634
+ }
635
+ inferFunctionDeclaration(node, env) {
636
+ return stmtFns.inferFunctionDeclaration(this, node, env);
637
+ }
638
+ inferObjectDestructuring(decl, env, kind) {
639
+ return stmtFns.inferObjectDestructuring(this, decl, env, kind);
640
+ }
641
+ inferDestructuringPattern(pattern, sourceType, env, kind, freezeLeaves = false) {
642
+ return stmtFns.inferDestructuringPattern(this, pattern, sourceType, env, kind, freezeLeaves);
643
+ }
644
+ inferWhileStatement(node, env) {
645
+ return stmtFns.inferWhileStatement(this, node, env);
646
+ }
647
+ inferDoWhileStatement(node, env) {
648
+ return stmtFns.inferDoWhileStatement(this, node, env);
649
+ }
650
+ inferForStatement(node, env) {
651
+ return stmtFns.inferForStatement(this, node, env);
652
+ }
653
+ inferForInStatement(node, env) {
654
+ return stmtFns.inferForInStatement(this, node, env);
655
+ }
656
+ inferForOfStatement(node, env) {
657
+ return stmtFns.inferForOfStatement(this, node, env);
658
+ }
659
+ inferSwitchStatement(node, env) {
660
+ return stmtFns.inferSwitchStatement(this, node, env);
661
+ }
662
+ inferTryStatement(node, env) {
663
+ return stmtFns.inferTryStatement(this, node, env);
664
+ }
665
+ // =======================================================================
666
+ // Expression delegates (→ expressions.ts)
667
+ // =======================================================================
668
+ inferExpression(node, env) {
669
+ return exprFns.inferExpression(this, node, env);
670
+ }
671
+ inferExpressionWithExpected(node, env, expectedType) {
672
+ return exprFns.inferExpressionWithExpected(this, node, env, expectedType);
673
+ }
674
+ inferFunctionExpression(node, env, expectedType) {
675
+ return exprFns.inferFunctionExpression(this, node, env, expectedType);
676
+ }
677
+ inferMemberExpression(node, env) {
678
+ return exprFns.inferMemberExpression(this, node, env);
679
+ }
680
+ tryInferPrototypeMethodAssignment(node, env) {
681
+ return exprFns.tryInferPrototypeMethodAssignment(this, node, env);
682
+ }
683
+ // =======================================================================
684
+ // Call delegates (→ calls.ts)
685
+ // =======================================================================
686
+ inferCallExpression(node, env, expectedResultType) {
687
+ const result = callFns.inferCallExpression(this, node, env, expectedResultType);
688
+ // A call to a generator function (`function* f`) evaluates to a
689
+ // `Generator <element>` value. The function type itself carries the
690
+ // element type as its result, so wrap that here at the call site.
691
+ if (node.callee.type === 'Identifier'
692
+ && this.generatorFunctionNames.has(node.callee.name)) {
693
+ return (0, types_1.tCon)('Generator', [this.subst.apply(result)]);
694
+ }
695
+ return result;
696
+ }
697
+ /** Rank-N subsumption check of an expression against a `forall` type
698
+ * (delegates to calls.ts; also used for record-field construction). */
699
+ inferRankNArgument(node, env, expected, rankNSkolems) {
700
+ return callFns.inferRankNArgument(this, node, env, expected, rankNSkolems);
701
+ }
702
+ // =======================================================================
703
+ // Module delegates (→ modules.ts)
704
+ // =======================================================================
705
+ inferImportDeclaration(node, env) {
706
+ return modFns.inferImportDeclaration(this, node, env);
707
+ }
708
+ inferExportNamedDeclaration(node, env) {
709
+ return modFns.inferExportNamedDeclaration(this, node, env);
710
+ }
711
+ inferExportDefaultDeclaration(node, env) {
712
+ return modFns.inferExportDefaultDeclaration(this, node, env);
713
+ }
714
+ inferExportAllDeclaration(node, env) {
715
+ return modFns.inferExportAllDeclaration(this, node, env);
716
+ }
717
+ inferClassDeclaration(node, env) {
718
+ return modFns.inferClassDeclaration(this, node, env);
719
+ }
720
+ // -----------------------------------------------------------------------
721
+ // Constraint-aware instantiation & validation
722
+ // -----------------------------------------------------------------------
723
+ /** Record a constraint on a kind-variable — see `src/infer/constraints.ts`. */
724
+ registerKvConstraint(varId, constraint, unique = false) {
725
+ constraintFns.registerKvConstraint(this, varId, constraint, unique);
726
+ }
727
+ /**
728
+ * Instantiate a scheme and register pending constraint checks for any
729
+ * constrained type variables — see `src/infer/constraints.ts`.
730
+ */
731
+ instantiateWithConstraints(scheme, node, annotation, skipPendingConstraints, preBindings, asGiven) {
732
+ return constraintFns.instantiateWithConstraints(this, scheme, node, annotation, skipPendingConstraints, preBindings, asGiven);
733
+ }
734
+ /** Register constraint info for static method body parameter TVars — see `src/infer/constraints.ts`. */
735
+ registerStaticMethodConstraints(scheme, bodyType) {
736
+ constraintFns.registerStaticMethodConstraints(this, scheme, bodyType);
737
+ }
738
+ /**
739
+ * Count pending constraints whose variable has resolved (under the CURRENT
740
+ * substitution) to a concrete type that does NOT satisfy the constraint.
741
+ * Read-only mirror of {@link validatePendingConstraints} (emits no
742
+ * diagnostics). Used by overload selection to reject a branch that would
743
+ * pin a constraint variable to an incompatible type (e.g. selecting the
744
+ * `Category c => TypeRep c -> c` overload of `id` for `id(Function)` when
745
+ * `Function` does not satisfy `Category`).
746
+ */
747
+ countViolatedPendingConstraints() {
748
+ return constraintFns.countViolatedPendingConstraints(this);
749
+ }
750
+ /**
751
+ * Report constraints that a callee REQUIRES on an enclosing function's own
752
+ * (still-polymorphic) type variable but which the enclosing signature never
753
+ * DECLARES. Haskell's "No instance for (C a) arising from a use of …".
754
+ *
755
+ * Mechanism: an annotated constrained function body instantiates its OWN
756
+ * signature as the authoritative expected type (`asGiven` → pending
757
+ * constraints tagged `given`). Callees referenced in the body push their
758
+ * required constraints (wanted, `given` unset) onto vars that unify with the
759
+ * enclosing function's declared type vars — so both givens and wanteds share
760
+ * the same resolved var id (a bare TVar or a still-polymorphic `$kv:name:id`
761
+ * higher-kinded TCon). A wanted whose class is not entailed by the given
762
+ * closure on that var (via `extends` superclasses) is an under-declared
763
+ * constraint. Only fires when the var carries at least one given, i.e. it
764
+ * belongs to an annotated constrained function — never on inferred /
765
+ * unconstrained polymorphic code.
766
+ */
767
+ validateMissingConstraints() {
768
+ constraintFns.validateMissingConstraints(this);
769
+ }
770
+ /**
771
+ * Validate all pending constraints after inference is complete.
772
+ * Checks that each constrained type variable resolved to a concrete type
773
+ * that satisfies the constraint (i.e., has all required methods registered).
774
+ */
775
+ validatePendingConstraints() {
776
+ constraintFns.validatePendingConstraints(this);
777
+ }
778
+ /**
779
+ * Validate pending structural-union constraints. Each constrained type
780
+ * variable must unify with at least one of the listed alternatives.
781
+ * The first alternative that successfully unifies wins; its substitution
782
+ * is committed to the engine. If none unify, a diagnostic is emitted.
783
+ * Variables still unresolved at this point are left alone (no diagnostic).
784
+ */
785
+ validatePendingUnionConstraints() {
786
+ constraintFns.validatePendingUnionConstraints(this);
787
+ }
788
+ /**
789
+ * Post-process a type by replacing constrained function types with their
790
+ * constructor names. E.g. replaces `a -> Identity a` with `Identity`
791
+ * inside `EitherT e (a -> Identity a) String` → `EitherT e Identity String`.
792
+ * Only rewrites nested occurrences (type args, function params/results,
793
+ * record fields) — not the top-level type itself, so that a standalone
794
+ * variable like `Identity :: a -> Identity a` keeps its function type.
795
+ */
796
+ applyConstraintConstructorRewrites(t) {
797
+ return constraintFns.applyConstraintConstructorRewrites(this, t);
798
+ }
799
+ // -----------------------------------------------------------------------
800
+ // Utility
801
+ // -----------------------------------------------------------------------
802
+ /** Shorthand for pushing a diagnostic with a message and node location. */
803
+ addDiag(message, loc, relatedInformation, severity) {
804
+ const scrub = this.scrubSkolemStringDetailed(message);
805
+ message = scrub.message;
806
+ // When two distinct same-letter skolems collided in this message, point
807
+ // the user at BOTH declaring annotations so "Cannot unify 'a' with 'a''"
808
+ // is traceable to its two distinct `a`s.
809
+ if (scrub.related.length > 0) {
810
+ relatedInformation = [...(relatedInformation ?? []), ...scrub.related];
811
+ }
812
+ // De-dupe: identical message at the same span happens when several
813
+ // unification call-sites (e.g. callee-type + result-type) all surface
814
+ // the same root-cause error.
815
+ for (const existing of this.diagnostics) {
816
+ if (existing.message === message && existing.start === loc.start && existing.end === loc.end) {
817
+ return;
818
+ }
819
+ }
820
+ this.diagnostics.push({ message, start: loc.start, end: loc.end, relatedInformation, severity });
821
+ }
822
+ /** Record skolem→letter mappings minted while checking an annotated body.
823
+ * `origin` (the declaring annotation's name + comment range) enables the
824
+ * same-letter collision disambiguation in diagnostics. */
825
+ registerSkolemNames(skolemToName, origin) {
826
+ for (const [k, v] of skolemToName) {
827
+ this.skolemDisplayNames.set(k, v);
828
+ if (origin && !this.skolemOrigins.has(k))
829
+ this.skolemOrigins.set(k, origin);
830
+ }
831
+ }
832
+ /** Replace rigid skolem constants in a type with display vars carrying the
833
+ * annotation's letters, so hover never shows `§N`. */
834
+ scrubForDisplay(t) {
835
+ return (0, typeUtils_1.scrubSkolems)(t, this.skolemDisplayNames);
836
+ }
837
+ /** Replace `§N` skolem tokens in a finished diagnostic string with the
838
+ * annotation's display letters (or `_` when unknown). */
839
+ scrubSkolemString(message) {
840
+ return this.scrubSkolemStringDetailed(message).message;
841
+ }
842
+ /** Collision-aware skolem scrubbing. Two DISTINCT skolems carrying the
843
+ * SAME letter (the `a` of a method annotation vs the `a` of the enclosing
844
+ * function's signature) would otherwise render an unreadable
845
+ * "Cannot unify 'a' with 'a'" — the second distinct skolem gets a prime
846
+ * suffix (`a'`), and each collided skolem with a known origin contributes
847
+ * a related-information entry pointing at its declaring annotation. */
848
+ scrubSkolemStringDetailed(message) {
849
+ if (!message.includes(types_1.SKOLEM_PREFIX))
850
+ return { message, related: [] };
851
+ const displayByToken = new Map();
852
+ const usedPerLetter = new Map();
853
+ const collidedTokens = [];
854
+ const scrubbed = message.replace(/§\d+/g, tok => {
855
+ let disp = displayByToken.get(tok);
856
+ if (disp === undefined) {
857
+ const letter = this.skolemDisplayNames.get(tok);
858
+ if (letter === undefined) {
859
+ disp = '_';
860
+ }
861
+ else {
862
+ const n = usedPerLetter.get(letter) ?? 0;
863
+ usedPerLetter.set(letter, n + 1);
864
+ disp = n === 0 ? letter : letter + "'".repeat(n);
865
+ if (n === 1) {
866
+ // First collision on this letter: the token that claimed the
867
+ // plain letter is also part of the collision — report it too.
868
+ for (const [prevTok, prevDisp] of displayByToken) {
869
+ if (prevDisp === letter) {
870
+ collidedTokens.push(prevTok);
871
+ break;
872
+ }
873
+ }
874
+ }
875
+ if (n >= 1)
876
+ collidedTokens.push(tok);
877
+ }
878
+ displayByToken.set(tok, disp);
879
+ }
880
+ return disp;
881
+ });
882
+ const related = [];
883
+ for (const tok of collidedTokens) {
884
+ const origin = this.skolemOrigins.get(tok);
885
+ if (!origin)
886
+ continue;
887
+ const disp = displayByToken.get(tok);
888
+ const label = origin.name ? `'${origin.name}'` : 'this signature';
889
+ related.push({
890
+ message: `'${disp}' is a type variable of ${label}, declared here`,
891
+ start: origin.start,
892
+ end: origin.end,
893
+ });
894
+ }
895
+ return { message: scrubbed, related };
896
+ }
897
+ /** Look up an annotation by name, falling back to offset-based method annotations. */
898
+ lookupAnnotation(name, offset) {
899
+ let annotation = name ? this.annotationMap.get(name) : undefined;
900
+ // A same-named declaration elsewhere: use THIS declaration's annotation.
901
+ if (annotation?.nodeStart !== undefined && annotation.nodeStart !== offset && name) {
902
+ const own = this.annotationsByDeclaration.get(offset);
903
+ if (own?.name === name)
904
+ annotation = own;
905
+ }
906
+ if (!annotation) {
907
+ const annByOffset = this.annotationByOffset.get(offset);
908
+ if (annByOffset?.receiver && annByOffset?.methodType && annByOffset?.scheme
909
+ && !annByOffset.methodNameMismatch) {
910
+ annotation = annByOffset;
911
+ }
912
+ }
913
+ return annotation;
914
+ }
915
+ /** Diagnostic-producing unification — see `src/infer/unifyDiag.ts`. */
916
+ unifyWithDiagnostic(t1, t2, node) {
917
+ unifyDiag.unifyWithDiagnostic(this, t1, t2, node);
918
+ }
919
+ /** Directional variant of `unifyWithDiagnostic` for the call-argument
920
+ * position — see `src/infer/unifyDiag.ts`. */
921
+ unifyArgWithDiagnostic(argType, paramType, node) {
922
+ unifyDiag.unifyArgWithDiagnostic(this, argType, paramType, node);
923
+ }
924
+ /** Shorthand for `checkAnnotationRigid` with bound engine state. */
925
+ checkRigid(inferredType, scheme, node) {
926
+ (0, annotations_1.checkAnnotationRigid)({ subst: this.subst, typeAliases: this.typeAliases, diagnostics: this.diagnostics, addDiag: this.boundAddDiag, aliasVars: this.typeAliasVars, skolemDisplayNames: this.skolemDisplayNames }, inferredType, scheme, node);
927
+ }
928
+ /** Expand a TCon alias if registered, instantiating any free alias vars
929
+ * with fresh TVars when the use-site provides no type arguments. Used
930
+ * by call/array/array-elem code paths where the alias appears bare (e.g.
931
+ * `[Selector]` for `Selector :: (String | Prop a | QueryTag a | ...)`),
932
+ * so each occurrence binds its own fresh type variables. */
933
+ maybeExpandAlias(t) {
934
+ if (t.tag !== 'TCon' || !this.typeAliases.has(t.name))
935
+ return t;
936
+ const vars = this.typeAliasVars.get(t.name) ?? [];
937
+ if (t.args.length === 0 && vars.length > 0) {
938
+ const fresh = vars.map(() => (0, types_1.tVar)());
939
+ const synthesized = { ...t, args: fresh };
940
+ return (0, annotations_1.expandAliases)(this.typeAliases, synthesized, undefined, this.typeAliasVars);
941
+ }
942
+ if (t.args.length === 0) {
943
+ return (0, annotations_1.expandAliases)(this.typeAliases, t, undefined, this.typeAliasVars);
944
+ }
945
+ return t;
946
+ }
947
+ /** Auto-union bridging on unification failure — see `src/infer/unifyDiag.ts`. */
948
+ tryAutoUnion(t1, r1, t2, r2) {
949
+ return unifyDiag.tryAutoUnion(this, t1, r1, t2, r2);
950
+ }
951
+ /** TCon ↔ TFun bridging via instance-callable annotations — see `src/infer/unifyDiag.ts`. */
952
+ tryConstructorCallable(t1, r1, t2, r2) {
953
+ return unifyDiag.tryConstructorCallable(this, t1, r1, t2, r2);
954
+ }
955
+ /** Deepest concretely-bound TVar in a substitution chain — see `src/infer/unifyDiag.ts`. */
956
+ findRootTVarId(t) {
957
+ return unifyDiag.findRootTVarId(this, t);
958
+ }
959
+ recordNodeType(node, type) {
960
+ // Record arrow/function nodes in a dedicated scope map (keyed by start,
961
+ // keeping the smallest span) so hover can find the tightest enclosing
962
+ // function even though the function's own entry in `nodeTypes` is
963
+ // suppressed below in favour of its first parameter identifier.
964
+ if (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression') {
965
+ const prev = this.functionNodeTypes.get(node.start);
966
+ const span = node.end - node.start;
967
+ // Prefer the smallest span; on an equal span keep the LATEST recording so
968
+ // a re-inferred function body (e.g. an overloaded callback resolved in a
969
+ // later pass) overrides the stale variable ids captured by an earlier,
970
+ // rolled-back trial.
971
+ if (!prev || span <= (prev.end - node.start)) {
972
+ this.functionNodeTypes.set(node.start, { type, end: node.end });
973
+ }
974
+ }
975
+ // Always store by end offset for completion lookups (e.g. after call expressions).
976
+ // Keep the most specific (smallest span) entry when multiple nodes share an end offset.
977
+ // This is done before the early-return guards below so that CallExpression types
978
+ // (which share the same start as their callee Identifier) are still captured.
979
+ if (node.type !== 'ArrowFunctionExpression' && node.type !== 'FunctionExpression') {
980
+ const existing = this.nodeTypesByEnd.get(node.end);
981
+ const span = node.end - node.start;
982
+ if (!existing || span < (node.end - existing.start)) {
983
+ this.nodeTypesByEnd.set(node.end, { type, start: node.start });
984
+ }
985
+ }
986
+ // For arrow/function expressions, don't overwrite a parameter already
987
+ // recorded at this offset (the first param shares the same start).
988
+ if ((node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression') &&
989
+ this.nodeTypes.has(node.start)) {
990
+ return;
991
+ }
992
+ // For compound expressions (MemberExpression, BinaryExpression, etc.)
993
+ // that share the same start offset as a child Identifier, don't overwrite.
994
+ // The Identifier type is more useful for hover since the cursor resolves
995
+ // to the innermost node first.
996
+ if (node.type !== 'Identifier' && node.type !== 'Literal' &&
997
+ this.nodeTypes.has(node.start)) {
998
+ return;
999
+ }
1000
+ this.nodeTypes.set(node.start, { type, end: node.end });
1001
+ }
1002
+ /** Lookup an inferred node type by AST node start offset. Used by
1003
+ * post-processing hooks (such as the `Picked` projection in
1004
+ * `infer/calls.ts`) that need to inspect the resolved type of a
1005
+ * sub-expression by AST identity. Falls back to the by-end-offset
1006
+ * map when no entry was recorded at the start offset (e.g. a
1007
+ * CallExpression whose callee Identifier already claimed the start
1008
+ * slot first via `recordNodeType`'s overlap guard). */
1009
+ getNodeType(node) {
1010
+ const direct = this.nodeTypes.get(node.start)?.type;
1011
+ if (direct !== undefined) {
1012
+ // When the start-keyed entry actually belongs to a strictly smaller
1013
+ // span (i.e. a child node such as a callee Identifier), prefer the
1014
+ // end-keyed entry whose start matches this node exactly.
1015
+ const endEntry = this.nodeTypesByEnd.get(node.end);
1016
+ if (endEntry && endEntry.start === node.start)
1017
+ return endEntry.type;
1018
+ return direct;
1019
+ }
1020
+ return this.nodeTypesByEnd.get(node.end)?.type;
1021
+ }
1022
+ /**
1023
+ * Coordinately instantiate receiver + methodType from a method annotation,
1024
+ * ensuring both share the same fresh type variables.
1025
+ * Pre-condition: ann.scheme, ann.receiver, and ann.methodType must be defined.
1026
+ */
1027
+ coordinateInstantiate(ann) {
1028
+ const varNames = new Map();
1029
+ (0, types_1.collectVarNames)(ann.receiver, varNames);
1030
+ (0, types_1.collectVarNames)(ann.methodType, varNames);
1031
+ // Row- and label-variables must be freshened as rows/labels (not plain
1032
+ // TVars) so open records like `{...a}` / `{a}` and label records keep
1033
+ // their open structure; otherwise the rest-row is lost and `{...a}`
1034
+ // collapses to the closed empty record `{}`.
1035
+ const labelIds = new Set();
1036
+ (0, env_1.collectLabelVarIds)(ann.receiver, labelIds);
1037
+ (0, env_1.collectLabelVarIds)(ann.methodType, labelIds);
1038
+ const rowIds = new Set();
1039
+ (0, env_1.collectRowVarIds)(ann.receiver, rowIds);
1040
+ (0, env_1.collectRowVarIds)(ann.methodType, rowIds);
1041
+ const freshSubst = new substitution_1.Substitution();
1042
+ const varIdMap = new Map();
1043
+ for (const v of ann.scheme.vars) {
1044
+ const name = varNames.get(v);
1045
+ if (labelIds.has(v)) {
1046
+ const fresh = (0, types_1.tVar)(name);
1047
+ freshSubst.set(v, { tag: 'TLabel', kind: 'var', id: fresh.id, name: name ?? fresh.name });
1048
+ if (name)
1049
+ varIdMap.set(name, fresh.id);
1050
+ continue;
1051
+ }
1052
+ if (rowIds.has(v)) {
1053
+ const freshRow = (0, types_1.tRow)(name);
1054
+ freshSubst.set(v, freshRow);
1055
+ if (name)
1056
+ varIdMap.set(name, freshRow.id);
1057
+ continue;
1058
+ }
1059
+ const fresh = (0, types_1.tVar)(name);
1060
+ freshSubst.set(v, fresh);
1061
+ if (name)
1062
+ varIdMap.set(name, fresh.id);
1063
+ }
1064
+ // Register constraints (e.g. Applicative f) for the fresh TVars
1065
+ if (ann.scheme.constraints) {
1066
+ for (const constraint of ann.scheme.constraints) {
1067
+ const freshId = varIdMap.get(constraint.typeVarName);
1068
+ if (freshId !== undefined) {
1069
+ this.registerKvConstraint(freshId, constraint);
1070
+ }
1071
+ }
1072
+ }
1073
+ return {
1074
+ thisType: freshSubst.apply(ann.receiver),
1075
+ expectedType: freshSubst.apply(ann.methodType),
1076
+ };
1077
+ }
1078
+ /**
1079
+ * Skolem variant of `coordinateInstantiate`: instantiate receiver +
1080
+ * methodType with rigid skolem constants (shared across both) instead of
1081
+ * fresh unifiable TVars. Used when checking an annotated method body so the
1082
+ * body cannot poison the annotation's parameter / `this` / return display.
1083
+ * Also returns the skolem→name map so the rigid types can be scrubbed back
1084
+ * to the annotation's letters for hover display and diagnostics.
1085
+ */
1086
+ coordinateInstantiateSkolem(ann, preBindings) {
1087
+ const { subst, skolemToName } = (0, env_1.skolemSubstForScheme)(ann.scheme, ann.receiver, ann.methodType, preBindings);
1088
+ // Pre-bound receiver vars may resolve to the ENCLOSING signature's skolems
1089
+ // (see enclosingReceiverBindings in expr-functions.ts). Carry their
1090
+ // display letters into this instantiation's map so the local scrub of the
1091
+ // method's own type (expr-functions.ts) knows them too.
1092
+ if (preBindings) {
1093
+ for (const bound of preBindings.values()) {
1094
+ (0, typeUtils_1.eachType)(bound, n => {
1095
+ if (n.tag === 'TCon' && n.name.startsWith(types_1.SKOLEM_PREFIX) && !skolemToName.has(n.name)) {
1096
+ const letter = this.skolemDisplayNames.get(n.name);
1097
+ if (letter)
1098
+ skolemToName.set(n.name, letter);
1099
+ }
1100
+ });
1101
+ }
1102
+ }
1103
+ return {
1104
+ thisType: subst.apply(ann.receiver),
1105
+ expectedType: subst.apply(ann.methodType),
1106
+ skolemToName,
1107
+ };
1108
+ }
1109
+ propagateCurryFlags(scheme, localName, nodeStart) {
1110
+ if (scheme.curryLeadingArgs) {
1111
+ this.curryNFunctionNames.set(localName, scheme.curryLeadingArgs);
1112
+ }
1113
+ else if (scheme.isCurryWrapper) {
1114
+ this.curryFunctionNames.add(localName);
1115
+ }
1116
+ // Propagate isCurriedResult so overload suggestions show on hover
1117
+ if (scheme.isCurriedResult) {
1118
+ this.curriedNodes.add(nodeStart);
1119
+ }
1120
+ }
1121
+ /** Shorthand: apply the current substitution to a type. */
1122
+ resolve(t) {
1123
+ return this.subst.apply(t);
1124
+ }
1125
+ }
1126
+ exports.InferenceEngine = InferenceEngine;
1127
+ //# sourceMappingURL=index.js.map