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,2794 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Completion — LSP completion item builders
4
+ //
5
+ // Plain language: the suggestion list that pops up while typing. Based on
6
+ // what stands before the cursor, this file assembles the relevant
7
+ // suggestions: after `obj.` the properties and methods of obj's type; inside
8
+ // a `::` annotation the known type names and constraints; after `import`
9
+ // the exports of the target file; etc. Each suggestion carries its type so
10
+ // the list doubles as documentation.
11
+ // ============================================================================
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || (function () {
29
+ var ownKeys = function(o) {
30
+ ownKeys = Object.getOwnPropertyNames || function (o) {
31
+ var ar = [];
32
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
+ return ar;
34
+ };
35
+ return ownKeys(o);
36
+ };
37
+ return function (mod) {
38
+ if (mod && mod.__esModule) return mod;
39
+ var result = {};
40
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
+ __setModuleDefault(result, mod);
42
+ return result;
43
+ };
44
+ })();
45
+ Object.defineProperty(exports, "__esModule", { value: true });
46
+ exports.findJsxOpeningTagContext = findJsxOpeningTagContext;
47
+ exports.findJsxAttrObjectContext = findJsxAttrObjectContext;
48
+ exports.getJSXStyleKeyCompletions = getJSXStyleKeyCompletions;
49
+ exports.getJSXPropCompletions = getJSXPropCompletions;
50
+ exports.getJSXComponentCompletions = getJSXComponentCompletions;
51
+ exports.getSumTypeRecordCompletions = getSumTypeRecordCompletions;
52
+ exports.getTypeAliasRecordCompletions = getTypeAliasRecordCompletions;
53
+ exports.getDestructuringCompletions = getDestructuringCompletions;
54
+ exports.getImportSpecifierCompletions = getImportSpecifierCompletions;
55
+ exports.getImportPathCompletions = getImportPathCompletions;
56
+ exports.getTypeDirectivePathCompletions = getTypeDirectivePathCompletions;
57
+ exports.clearWorkspaceExportCache = clearWorkspaceExportCache;
58
+ exports.invalidateWorkspaceExportEntry = invalidateWorkspaceExportEntry;
59
+ exports.warmWorkspaceExports = warmWorkspaceExports;
60
+ exports.getWorkspaceExports = getWorkspaceExports;
61
+ exports.detectModuleStyle = detectModuleStyle;
62
+ exports.buildAutoImportEdit = buildAutoImportEdit;
63
+ exports.getIdentifierCompletions = getIdentifierCompletions;
64
+ exports.getBracketStringCompletions = getBracketStringCompletions;
65
+ exports.getTableSelectorCompletions = getTableSelectorCompletions;
66
+ exports.getDotCompletions = getDotCompletions;
67
+ exports.getDirectiveCompletions = getDirectiveCompletions;
68
+ exports.getAnnotationTypeCompletions = getAnnotationTypeCompletions;
69
+ exports.getAnnotationNameCompletions = getAnnotationNameCompletions;
70
+ const node_1 = require("vscode-languageserver/node");
71
+ const path = __importStar(require("path"));
72
+ const fs = __importStar(require("fs"));
73
+ const url_1 = require("url");
74
+ const types_1 = require("../hm/types");
75
+ const typeUtils_1 = require("../hm/typeUtils");
76
+ const typeUtils_2 = require("../hm/typeUtils");
77
+ const typeUtils_3 = require("../hm/typeUtils");
78
+ const types_2 = require("../hm/types");
79
+ const index_1 = require("../index");
80
+ const dataTypeRegistry_1 = require("../registries/dataTypeRegistry");
81
+ const methodRegistry_1 = require("../registries/methodRegistry");
82
+ const expressions_1 = require("../infer/expressions");
83
+ const expressions_2 = require("../infer/expressions");
84
+ const jsx_dom_1 = require("../infer/jsx-dom");
85
+ const files_1 = require("./files");
86
+ const hover_1 = require("./hover");
87
+ const references_1 = require("./references");
88
+ // ---------------------------------------------------------------------------
89
+ // Helpers
90
+ // ---------------------------------------------------------------------------
91
+ /** Instantiate a scheme for completion display purposes, falling back to raw type on error. */
92
+ function safeInstantiate(s) {
93
+ try {
94
+ return (0, index_1.instantiate)(s);
95
+ }
96
+ catch {
97
+ return s.type;
98
+ }
99
+ }
100
+ // ---------------------------------------------------------------------------
101
+ // Shared helpers for object-literal completion
102
+ // ---------------------------------------------------------------------------
103
+ /** Scan backwards from `offset` to find the opening `{` of an object literal.
104
+ * Returns -1 if not found before hitting a `;`. */
105
+ function findOpenBrace(source, offset) {
106
+ let braceDepth = 0;
107
+ for (let i = offset - 1; i >= 0; i--) {
108
+ const ch = source[i];
109
+ if (ch === '}')
110
+ braceDepth++;
111
+ if (ch === '{') {
112
+ if (braceDepth === 0)
113
+ return i;
114
+ braceDepth--;
115
+ }
116
+ if (ch === ';')
117
+ break;
118
+ }
119
+ return -1;
120
+ }
121
+ /** Find the name of the enclosing function before `beforeOffset`. */
122
+ function findEnclosingFuncName(source, beforeOffset) {
123
+ const textBefore = source.substring(0, beforeOffset);
124
+ const fnDeclRegex = /function\s+(\w+)\s*\(/g;
125
+ let fnMatch;
126
+ let lastFnMatch = null;
127
+ while ((fnMatch = fnDeclRegex.exec(textBefore)) !== null)
128
+ lastFnMatch = fnMatch;
129
+ const varDeclRegex = /(?:const|let|var)\s+(\w+)\s*=/g;
130
+ let varMatch;
131
+ let lastVarMatch = null;
132
+ while ((varMatch = varDeclRegex.exec(textBefore)) !== null)
133
+ lastVarMatch = varMatch;
134
+ if (lastFnMatch && lastVarMatch) {
135
+ return lastFnMatch.index > lastVarMatch.index ? lastFnMatch[1] : lastVarMatch[1];
136
+ }
137
+ return lastFnMatch?.[1] ?? lastVarMatch?.[1];
138
+ }
139
+ /** Collect keys already present inside a `{ key :: ..., key2 :: ... }` literal. */
140
+ function getPresentKeys(source, openBraceOffset, offset) {
141
+ const closeBrace = source.indexOf('}', offset);
142
+ const objectContent = source.substring(openBraceOffset + 1, closeBrace > 0 ? closeBrace : offset);
143
+ return new Set(objectContent.match(/\b(\w+)\s*[,:}]/g)?.map(m => m.replace(/[\s,:}]/g, '')) ?? []);
144
+ }
145
+ /**
146
+ * Resolve a Type to its record-field entries, following an alias TCon to its
147
+ * underlying TRecord if necessary. Returns `null` when the type is not a record.
148
+ */
149
+ function resolveRecordFields(t, result) {
150
+ if (t.tag === 'TRecord') {
151
+ const hidden = t.hiddenFields;
152
+ const entries = Object.entries(t.fields);
153
+ return hidden ? entries.filter(([k]) => !hidden.has(k)) : entries;
154
+ }
155
+ if (t.tag === 'TCon') {
156
+ if (t.name === 'Union') {
157
+ // Pick the first TRecord (or alias-to-TRecord) member of the union.
158
+ // Useful for query-builder-style overloaded values whose record branch
159
+ // carries the destructurable fields (e.g. `{ props :: …}`).
160
+ for (const member of t.args) {
161
+ const fields = resolveRecordFields(member, result);
162
+ if (fields)
163
+ return fields;
164
+ }
165
+ return null;
166
+ }
167
+ const alias = result.typeAliases.get(t.name);
168
+ if (alias && alias.type.tag === 'TRecord') {
169
+ const hidden = alias.type.hiddenFields;
170
+ const entries = Object.entries(alias.type.fields);
171
+ return hidden ? entries.filter(([k]) => !hidden.has(k)) : entries;
172
+ }
173
+ }
174
+ return null;
175
+ }
176
+ /**
177
+ * Walk backwards from `offset` to find the `(` of an enclosing call expression
178
+ * along with the active argument index (number of top-level commas seen).
179
+ * Returns null when no enclosing `(` exists at depth 0.
180
+ */
181
+ function findEnclosingCallParen(source, offset) {
182
+ let depth = 0;
183
+ let activeParam = 0;
184
+ for (let i = offset - 1; i >= 0; i--) {
185
+ const ch = source[i];
186
+ if (ch === ')' || ch === ']' || ch === '}')
187
+ depth++;
188
+ else if (ch === '(' || ch === '[' || ch === '{') {
189
+ if (depth > 0)
190
+ depth--;
191
+ else if (ch === '(')
192
+ return { parenOffset: i, activeParam };
193
+ // unmatched '[' or '{' at depth 0 — keep scanning outward
194
+ }
195
+ else if (ch === ',' && depth === 0)
196
+ activeParam++;
197
+ }
198
+ return null;
199
+ }
200
+ /**
201
+ * When the cursor sits inside an object literal that is an argument to a call,
202
+ * return the *expected* record type for that argument as inferred from the
203
+ * callee's signature. Useful for completion in `f(arg, { | })` where the
204
+ * literal itself has no fields yet but the callee's parameter is a record.
205
+ */
206
+ function getExpectedRecordTypeForCallArg(source, openBraceOffset, result) {
207
+ const found = findEnclosingCallParen(source, openBraceOffset);
208
+ if (!found)
209
+ return null;
210
+ const { parenOffset, activeParam } = found;
211
+ // Locate the callee identifier just before the '('.
212
+ let calleeEnd = parenOffset - 1;
213
+ while (calleeEnd >= 0 && /\s/.test(source[calleeEnd]))
214
+ calleeEnd--;
215
+ let calleeStart = calleeEnd;
216
+ while (calleeStart >= 0 && /[A-Za-z0-9_$.]/.test(source[calleeStart]))
217
+ calleeStart--;
218
+ calleeStart++;
219
+ if (calleeStart > calleeEnd)
220
+ return null;
221
+ // Find the recorded type whose start lies inside the callee identifier range.
222
+ let bestType = null;
223
+ let bestStart = -1;
224
+ for (const [start, { type }] of result.nodeTypes) {
225
+ if (start >= calleeStart && start <= calleeEnd && start > bestStart) {
226
+ bestType = result.substitution.apply(type);
227
+ bestStart = start;
228
+ }
229
+ }
230
+ if (!bestType)
231
+ return null;
232
+ // Direct TFun: classic case (`f({ | })` where `f :: { ... } -> ...`).
233
+ if (bestType.tag === 'TFun') {
234
+ const params = (0, typeUtils_1.extractParamList)(bestType);
235
+ if (activeParam >= params.length)
236
+ return null;
237
+ return result.substitution.apply(params[activeParam]);
238
+ }
239
+ // Instance-callable TCon (`tag :: QueryTag p o` invoked as `tag({ | })`).
240
+ // Resolve the callable scheme registered for the constructor name and
241
+ // specialise it with the host TCon's row/param slots, mirroring the
242
+ // logic in [hover.ts] `collectConstructorCallableOverloads`.
243
+ if (bestType.tag === 'TCon' && /^[A-Z]/.test(bestType.name)) {
244
+ const callables = result.instanceCallables?.get(bestType.name);
245
+ if (!callables || callables.length === 0)
246
+ return null;
247
+ const slots = (0, typeUtils_2.findHostSlots)(bestType);
248
+ const paramArg = slots.paramArg ?? bestType.paramHint ?? null;
249
+ for (const scheme of callables) {
250
+ let branch = safeInstantiate(scheme);
251
+ if (branch.tag !== 'TFun')
252
+ continue;
253
+ const { paramTVarId, carrierTVarId } = (0, typeUtils_2.findOverloadSlots)(branch);
254
+ if (slots.rowArg && carrierTVarId !== null) {
255
+ branch = (0, typeUtils_2.substTVar)(branch, carrierTVarId, slots.rowArg);
256
+ }
257
+ if (paramArg && paramTVarId !== null) {
258
+ branch = (0, typeUtils_2.substTVar)(branch, paramTVarId, paramArg);
259
+ }
260
+ const params = (0, typeUtils_1.extractParamList)(branch);
261
+ if (activeParam >= params.length)
262
+ continue;
263
+ return result.substitution.apply(params[activeParam]);
264
+ }
265
+ }
266
+ return null;
267
+ }
268
+ /** Run inference on `source` and return the result (shared 3-line preamble).
269
+ * Prefers the request-scoped cache when the server provides one. */
270
+ function runInference(source, uri, ctx) {
271
+ if (ctx.inferSource)
272
+ return ctx.inferSource(source);
273
+ const resolver = ctx.createImportResolver(uri);
274
+ const typeResolver = ctx.createTypeDirectiveResolver(uri);
275
+ const aliasResolver = ctx.createImportTypeAliasResolver?.(uri);
276
+ return ctx.engine.infer(source, undefined, resolver, typeResolver, aliasResolver);
277
+ }
278
+ /**
279
+ * Scan backwards from `offset` to determine whether the cursor sits inside a
280
+ * JSX opening element's attribute region (`<Badge |`, `<Badge la|`,
281
+ * `<Ui.Badge x={1} |`). Purely textual so it works mid-typing when the
282
+ * source does not parse. Returns null when the cursor is:
283
+ * - not after a `<Tag` sequence,
284
+ * - inside an expression container (`{…}`) — normal completion applies,
285
+ * - past the tag's closing `>`,
286
+ * - inside a closing tag (`</Tag`).
287
+ */
288
+ function findJsxOpeningTagContext(source, offset) {
289
+ let braceDepth = 0;
290
+ for (let i = offset - 1; i >= 0; i--) {
291
+ const ch = source[i];
292
+ // Skip string attribute values ("…" / '…'); give up if the string spans
293
+ // a newline (almost certainly not an attribute value).
294
+ if (ch === '"' || ch === '\'') {
295
+ let j = i - 1;
296
+ while (j >= 0 && source[j] !== ch && source[j] !== '\n')
297
+ j--;
298
+ if (j < 0 || source[j] !== ch)
299
+ return null;
300
+ i = j;
301
+ continue;
302
+ }
303
+ if (ch === '}') {
304
+ braceDepth++;
305
+ continue;
306
+ }
307
+ if (ch === '{') {
308
+ // Unmatched `{` — cursor is inside an expression container.
309
+ if (braceDepth === 0)
310
+ return null;
311
+ braceDepth--;
312
+ continue;
313
+ }
314
+ // Characters that cannot occur in an attribute region outside strings
315
+ // and braces — we are not inside an opening tag.
316
+ if (ch === '>' || ch === ';' || ch === '(' || ch === ')' || ch === ',')
317
+ return null;
318
+ if (ch === '<') {
319
+ if (source[i + 1] === '/')
320
+ return null; // closing tag
321
+ const m = /^[A-Za-z_$][\w$.]*/.exec(source.slice(i + 1, i + 200));
322
+ if (!m)
323
+ return null;
324
+ const tagName = m[0];
325
+ const nameEnd = i + 1 + tagName.length;
326
+ if (offset < nameEnd)
327
+ return null; // cursor still inside the tag name
328
+ return { tagName, tagStart: i + 1, attrText: source.slice(nameEnd, offset) };
329
+ }
330
+ }
331
+ return null;
332
+ }
333
+ /**
334
+ * Scan backwards from `offset` to determine whether the cursor sits inside
335
+ * an object literal nested in a JSX attribute's expression container
336
+ * (`style={{ … }`). Purely textual so it works mid-typing. Returns null
337
+ * when the cursor is directly in the container (`attr={|`, no inner
338
+ * object), inside a string, or not in a JSX opening tag at all.
339
+ */
340
+ function findJsxAttrObjectContext(source, offset) {
341
+ let closeDepth = 0;
342
+ let innermostOpen = -1;
343
+ for (let i = offset - 1; i >= 0; i--) {
344
+ const ch = source[i];
345
+ // Skip string literals; bail when the opener is missing on the same
346
+ // line (cursor almost certainly inside an unterminated string).
347
+ if (ch === '"' || ch === '\'' || ch === '`') {
348
+ let j = i - 1;
349
+ while (j >= 0 && source[j] !== ch && source[j] !== '\n')
350
+ j--;
351
+ if (j < 0 || source[j] !== ch)
352
+ return null;
353
+ i = j;
354
+ continue;
355
+ }
356
+ if (ch === '}') {
357
+ closeDepth++;
358
+ continue;
359
+ }
360
+ if (ch !== '{')
361
+ continue;
362
+ if (closeDepth > 0) {
363
+ closeDepth--;
364
+ continue;
365
+ }
366
+ // Unmatched `{` — the attribute container when directly preceded by
367
+ // `attrName=`; otherwise a (possibly nested) object literal.
368
+ const before = source.slice(0, i);
369
+ const m = /([A-Za-z_$][\w$-]*)\s*=\s*$/.exec(before);
370
+ if (!m) {
371
+ if (innermostOpen < 0)
372
+ innermostOpen = i;
373
+ continue;
374
+ }
375
+ if (innermostOpen < 0)
376
+ return null; // directly in `attr={|` — not an object
377
+ const tag = findJsxOpeningTagContext(source, m.index);
378
+ if (!tag)
379
+ return null;
380
+ return { tagName: tag.tagName, attrName: m[1], innerText: source.slice(innermostOpen + 1, offset) };
381
+ }
382
+ return null;
383
+ }
384
+ /**
385
+ * CSS property-name completion inside `style={{ … }}`: on an object-literal
386
+ * KEY position the catalogue names are offered (and the identifier fallback
387
+ * suppressed — file bindings are meaningless there); on a VALUE position
388
+ * null is returned so ordinary identifier completion applies. Unknown keys
389
+ * (CSS custom properties, vendor prefixes) stay diagnostic-free — this is
390
+ * completion only.
391
+ */
392
+ function getJSXStyleKeyCompletions(source, offset, ctx) {
393
+ const objCtx = findJsxAttrObjectContext(source, offset);
394
+ if (!objCtx || objCtx.attrName !== 'style')
395
+ return null;
396
+ const partial = /[\w$]*$/.exec(objCtx.innerText)?.[0] ?? '';
397
+ const beforePartial = objCtx.innerText.slice(0, objCtx.innerText.length - partial.length);
398
+ // Key vs value position: scrub strings + balanced groups, then compare the
399
+ // last `:` against the last `,` — a trailing `:` means value position.
400
+ let scrubbed = beforePartial.replace(/"[^"]*"|'[^']*'|`[^`]*`/g, ' ');
401
+ for (;;) {
402
+ const next = scrubbed.replace(/\{[^{}]*\}|\[[^\]]*\]|\([^()]*\)/g, ' ');
403
+ if (next === scrubbed)
404
+ break;
405
+ scrubbed = next;
406
+ }
407
+ if (scrubbed.lastIndexOf(':') > scrubbed.lastIndexOf(','))
408
+ return null; // value position
409
+ const present = new Set();
410
+ const re = /([A-Za-z_$][\w$-]*)\s*:/g;
411
+ let m;
412
+ while ((m = re.exec(scrubbed)) !== null)
413
+ present.add(m[1]);
414
+ const formatType = ctx.inferredTypeStyle === 'pretty' ? types_1.prettyTypeToString : types_1.typeToString;
415
+ const items = [];
416
+ for (const entry of (0, jsx_dom_1.getCssPropertyEntries)()) {
417
+ if (present.has(entry.name))
418
+ continue;
419
+ if (partial && !entry.name.startsWith(partial))
420
+ continue;
421
+ items.push({
422
+ label: entry.name,
423
+ kind: node_1.CompletionItemKind.Property,
424
+ detail: formatType(entry.type),
425
+ insertText: `${entry.name}: $1`,
426
+ insertTextFormat: node_1.InsertTextFormat.Snippet,
427
+ sortText: `0_${entry.name}`,
428
+ });
429
+ }
430
+ // Always an array on a key position — even when empty — so the generic
431
+ // identifier completion never floods an object-key slot.
432
+ return items;
433
+ }
434
+ /** Resolve a JSX tag name (possibly a member chain) to its binding type. */
435
+ function resolveJsxTagType(tagName, result) {
436
+ const parts = tagName.split('.');
437
+ const scheme = result.topLevelBindings.get(parts[0]);
438
+ if (!scheme)
439
+ return null;
440
+ let t = result.substitution.apply(safeInstantiate(scheme));
441
+ for (const part of parts.slice(1)) {
442
+ if (t.tag !== 'TRecord' || !(part in t.fields))
443
+ return null;
444
+ t = result.substitution.apply(t.fields[part]);
445
+ }
446
+ return t;
447
+ }
448
+ /** Extract the props record of a component type (first parameter). */
449
+ function propsRecordOfComponent(t, result) {
450
+ if (t.tag === 'TFun') {
451
+ const params = (0, typeUtils_1.extractParamList)(t);
452
+ if (params.length === 0)
453
+ return null;
454
+ return result.substitution.apply(params[0]);
455
+ }
456
+ // Instance-callable / constructor-annotated components (`Badge :: … -> Badge`
457
+ // annotates the binding as a TFun already; class components without a
458
+ // constructor annotation resolve to a TCon we cannot introspect).
459
+ if (t.tag === 'TCon' && /^[A-Z]/.test(t.name)) {
460
+ const callables = result.instanceCallables?.get(t.name);
461
+ if (callables) {
462
+ for (const scheme of callables) {
463
+ const branch = safeInstantiate(scheme);
464
+ if (branch.tag !== 'TFun')
465
+ continue;
466
+ const params = (0, typeUtils_1.extractParamList)(branch);
467
+ if (params.length > 0)
468
+ return result.substitution.apply(params[0]);
469
+ }
470
+ }
471
+ }
472
+ return null;
473
+ }
474
+ /** Attribute names already present in an opening tag's attribute text. */
475
+ function presentJsxAttrNames(attrText) {
476
+ const scrubbed = attrText
477
+ .replace(/"[^"]*"|'[^']*'/g, ' ') // string values
478
+ .replace(/\{[^{}]*\}/g, ' ') // simple expression containers
479
+ .replace(/\.\.\.[\w$.]*/g, ' '); // spread attributes
480
+ const names = new Set();
481
+ const re = /([A-Za-z_$][\w$-]*)/g;
482
+ let m;
483
+ while ((m = re.exec(scrubbed)) !== null)
484
+ names.add(m[1]);
485
+ return names;
486
+ }
487
+ /** True when a (resolved) type accepts `undefined` — used to mark optional props. */
488
+ function typeHasUndefined(t) {
489
+ if (t.tag === 'TCon' && t.name === 'Undefined')
490
+ return true;
491
+ if (t.tag === 'TCon' && t.name === types_1.T_UNION)
492
+ return t.args.some(typeHasUndefined);
493
+ return false;
494
+ }
495
+ /**
496
+ * Prop-name completion inside a JSX opening tag: `<Badge l|` offers the
497
+ * fields of the component's props record (first parameter), excluding
498
+ * `children` and attributes already present.
499
+ */
500
+ function getJSXPropCompletions(source, offset, uri, ctx) {
501
+ const tag = findJsxOpeningTagContext(source, offset);
502
+ if (!tag)
503
+ return [];
504
+ // Inside an unterminated attribute value (`label="…`) — not a name position.
505
+ const quoteCount = (tag.attrText.match(/["']/g) ?? []).length;
506
+ if (quoteCount % 2 !== 0)
507
+ return [];
508
+ const partial = /[\w$]*$/.exec(tag.attrText)?.[0] ?? '';
509
+ const present = presentJsxAttrNames(tag.attrText.slice(0, tag.attrText.length - partial.length));
510
+ const formatType = ctx.inferredTypeStyle === 'pretty' ? types_1.prettyTypeToString : types_1.typeToString;
511
+ // Intrinsic (lowercase) tag — complete from the DOM attribute catalogue;
512
+ // per-tag attributes sort above global ones.
513
+ if (/^[a-z]/.test(tag.tagName) && !tag.tagName.includes('.')) {
514
+ const items = [];
515
+ for (const entry of (0, jsx_dom_1.getIntrinsicAttrEntries)(tag.tagName)) {
516
+ if (present.has(entry.name))
517
+ continue;
518
+ if (partial && !entry.name.startsWith(partial))
519
+ continue;
520
+ const isString = entry.type.tag === 'TCon' && entry.type.name === 'String';
521
+ items.push({
522
+ label: entry.name,
523
+ kind: node_1.CompletionItemKind.Property,
524
+ detail: formatType(entry.type),
525
+ insertText: isString ? `${entry.name}="$1"$0` : `${entry.name}={$1}$0`,
526
+ insertTextFormat: node_1.InsertTextFormat.Snippet,
527
+ sortText: `${entry.tagSpecific ? '0' : '1'}_${entry.name}`,
528
+ });
529
+ }
530
+ return items;
531
+ }
532
+ // Mid-typing sources (`… = <Badge l`) do not parse — even loosely — so
533
+ // resolve the component's type against the last good cached result when
534
+ // available, and otherwise re-infer a patched source with the open tag
535
+ // self-closed at the cursor (`… = <Badge l />`).
536
+ let result = ctx.cachedResult;
537
+ let tagType = result ? resolveJsxTagType(tag.tagName, result) : null;
538
+ if (!tagType) {
539
+ const patched = source.slice(0, offset) + ' />' + source.slice(offset);
540
+ result = runInference(patched, uri, ctx);
541
+ tagType = resolveJsxTagType(tag.tagName, result);
542
+ }
543
+ if (!result || !tagType)
544
+ return [];
545
+ const propsType = propsRecordOfComponent(tagType, result);
546
+ if (!propsType)
547
+ return [];
548
+ const fields = resolveRecordFields(propsType, result);
549
+ if (!fields || fields.length === 0)
550
+ return [];
551
+ const items = [];
552
+ for (const [name, rawType] of fields) {
553
+ if (name === 'children')
554
+ continue;
555
+ if (present.has(name))
556
+ continue;
557
+ if (partial && !name.startsWith(partial))
558
+ continue;
559
+ const fieldType = result.substitution.apply(rawType);
560
+ const isString = fieldType.tag === 'TCon' && fieldType.name === 'String';
561
+ items.push({
562
+ label: name,
563
+ kind: node_1.CompletionItemKind.Field,
564
+ detail: formatType(fieldType) + (typeHasUndefined(fieldType) ? ' (optional)' : ''),
565
+ insertText: isString ? `${name}="$1"$0` : `${name}={$1}$0`,
566
+ insertTextFormat: node_1.InsertTextFormat.Snippet,
567
+ sortText: `0_${name}`,
568
+ });
569
+ }
570
+ return items;
571
+ }
572
+ /**
573
+ * Component-name completion right after `<`: `<Badg|` offers uppercase
574
+ * bindings (and auto-import candidates) from the regular identifier
575
+ * completion, since JSX component tags must start with a capital letter.
576
+ */
577
+ function getJSXComponentCompletions(source, offset, uri, ctx) {
578
+ const wordStart = (0, hover_1.scanWord)(source, offset)?.start ?? offset;
579
+ if (wordStart === 0 || source[wordStart - 1] !== '<')
580
+ return [];
581
+ // `a << b`, `a </ b` and friends are not JSX tags.
582
+ if (wordStart >= 2 && /[<\/=!]/.test(source[wordStart - 2]))
583
+ return [];
584
+ const partial = source.slice(wordStart, offset);
585
+ // Only fire for capitalised names — lowercase tags are host elements and
586
+ // `a < b` comparisons; both should keep the default behaviour.
587
+ if (!/^[A-Z]/.test(partial))
588
+ return [];
589
+ // The open tag makes the source unparseable mid-typing; self-close it so
590
+ // the identifier completions can see the file's bindings.
591
+ const patched = source.slice(0, offset) + ' />' + source.slice(offset);
592
+ return getIdentifierCompletions(patched, offset, uri, ctx)
593
+ .filter(item => /^[A-Z]/.test(item.label));
594
+ }
595
+ // ---------------------------------------------------------------------------
596
+ // sumtype factory record completion — return { | }
597
+ // ---------------------------------------------------------------------------
598
+ /**
599
+ * Shared prefix for record-completion providers: locate `{` of a return-object
600
+ * literal inside a function body, infer the source, and resolve the function's
601
+ * annotated return type. Returns null if any precondition fails.
602
+ */
603
+ function resolveReturnRecordContext(source, offset, uri, ctx) {
604
+ // 1. Find { of object literal
605
+ const openBraceOffset = findOpenBrace(source, offset);
606
+ if (openBraceOffset < 0)
607
+ return null;
608
+ // 2. Check that the { is preceded by `return` or `=> (`
609
+ const beforeBrace = source.substring(0, openBraceOffset).trimEnd();
610
+ const isReturn = beforeBrace.endsWith('return');
611
+ const isArrowParen = /=>\s*\($/.test(beforeBrace);
612
+ if (!isReturn && !isArrowParen)
613
+ return null;
614
+ // 3. Find the enclosing function's annotation
615
+ const result = runInference(source, uri, ctx);
616
+ const funcName = findEnclosingFuncName(source, openBraceOffset);
617
+ if (!funcName)
618
+ return null;
619
+ // 4. Look up the annotation for this function
620
+ const ann = result.annotations.get(funcName);
621
+ if (!ann?.scheme)
622
+ return null;
623
+ return { openBraceOffset, result, retType: (0, types_1.getReturnType)(ann.scheme.type) };
624
+ }
625
+ /**
626
+ * Detect if the cursor is inside a return object literal within a sumtype
627
+ * factory function. If so, offer the registered methods/properties as
628
+ * completion items (e.g. `value`, `map`).
629
+ *
630
+ * Pattern: `return { | }` inside a function annotated with a sumtype return.
631
+ */
632
+ function getSumTypeRecordCompletions(source, offset, uri, ctx) {
633
+ if (offset > 0 && source[offset - 1] === '.')
634
+ return [];
635
+ const rc = resolveReturnRecordContext(source, offset, uri, ctx);
636
+ if (!rc)
637
+ return [];
638
+ const { openBraceOffset, retType } = rc;
639
+ // 5. Check if the return type is a TCon with registered methods (sumtype, class, ADT factory)
640
+ if (retType.tag !== 'TCon')
641
+ return [];
642
+ if (!(0, index_1.isDataType)(retType.name) && ((0, index_1.isBuiltinType)(retType.name) || (0, index_1.getMethodNames)(retType.name).length === 0))
643
+ return [];
644
+ const typeName = retType.name;
645
+ const methodNames = (0, index_1.getMethodNames)(typeName);
646
+ if (methodNames.length === 0)
647
+ return [];
648
+ // 6. Build completions with snippet text for each field
649
+ const items = [];
650
+ const presentKeys = getPresentKeys(source, openBraceOffset, offset);
651
+ for (const mn of methodNames) {
652
+ if (presentKeys.has(mn))
653
+ continue; // already present
654
+ const entry = (0, index_1.lookupMethod)(typeName, mn);
655
+ if (entry && !entry.isStatic) {
656
+ const methodType = entry.factory(retType.args);
657
+ const display = (0, types_1.prettyTypeToString)(methodType);
658
+ items.push({
659
+ label: mn,
660
+ kind: methodType.tag === 'TFun' ? node_1.CompletionItemKind.Method : node_1.CompletionItemKind.Field,
661
+ detail: `${typeName}#${mn} :: ${display}`,
662
+ });
663
+ }
664
+ }
665
+ return items;
666
+ }
667
+ // ---------------------------------------------------------------------------
668
+ // Type alias record completion — return { | } or => ({ | })
669
+ // ---------------------------------------------------------------------------
670
+ /**
671
+ * Detect if the cursor is inside a return object literal within a function
672
+ * annotated to return a type alias that expands to a record.
673
+ * If so, offer the missing record fields as completion items.
674
+ *
675
+ * Patterns:
676
+ * - `return { | }` in block-body functions
677
+ * - `=> ({ | })` in expression-body arrow functions
678
+ */
679
+ function getTypeAliasRecordCompletions(source, offset, uri, ctx) {
680
+ if (offset > 0 && source[offset - 1] === '.')
681
+ return [];
682
+ const rc = resolveReturnRecordContext(source, offset, uri, ctx);
683
+ if (!rc)
684
+ return [];
685
+ const { openBraceOffset, result, retType } = rc;
686
+ // 5. Get the return type and check if it expands to a record via type alias
687
+ let aliasName;
688
+ let recordType;
689
+ if (retType.tag === 'TRecord' && retType.alias) {
690
+ aliasName = retType.alias;
691
+ recordType = retType;
692
+ }
693
+ else if (retType.tag === 'TCon') {
694
+ aliasName = retType.name;
695
+ const aliasEntry = result.typeAliases.get(aliasName);
696
+ if (aliasEntry && aliasEntry.type.tag === 'TRecord') {
697
+ recordType = aliasEntry.type;
698
+ }
699
+ }
700
+ if (!aliasName || !recordType || recordType.tag !== 'TRecord')
701
+ return [];
702
+ // 6. Build completion items for missing fields
703
+ const presentKeys = getPresentKeys(source, openBraceOffset, offset);
704
+ const fmt = ctx.inferredTypeStyle === 'pretty' ? types_1.prettyTypeToString : types_1.typeToString;
705
+ const items = [];
706
+ for (const [fieldName, fieldType] of Object.entries(recordType.fields)) {
707
+ if (recordType.hiddenFields?.has(fieldName))
708
+ continue;
709
+ if (presentKeys.has(fieldName))
710
+ continue;
711
+ items.push({
712
+ label: fieldName,
713
+ kind: node_1.CompletionItemKind.Field,
714
+ detail: `${aliasName}.${fieldName} :: ${fmt(fieldType)}`,
715
+ });
716
+ }
717
+ return items;
718
+ }
719
+ // ---------------------------------------------------------------------------
720
+ // Destructuring completion — const { | } = expr
721
+ // ---------------------------------------------------------------------------
722
+ /**
723
+ * Detect if the cursor is inside a destructuring pattern: `const { | } = expr`
724
+ * If so, return completions based on the RHS expression's type.
725
+ *
726
+ * How it works, step by step (plain language):
727
+ * 1. Walk backwards from the cursor to find the `{` that opened the
728
+ * pattern we are inside of.
729
+ * 2. Look at the text just before that `{`:
730
+ * - `(`, `,` or `:` means we are inside a function PARAMETER pattern
731
+ * (e.g. `({ | }) => ...`) — ask the type checker what record type the
732
+ * function expects there and offer its field names.
733
+ * - `const` / `let` / `var` means a VARIABLE pattern — continue below.
734
+ * 3. Walk forwards to find the matching `}`, the `=` sign, and the
735
+ * expression on the right-hand side (possibly a chain like `a.b.c()`).
736
+ * 4. Ask the type checker what type that right-hand side has, and offer
737
+ * its record fields / module exports / methods as suggestions, minus
738
+ * any keys the user has already written inside the braces.
739
+ */
740
+ function getDestructuringCompletions(source, offset, uri, ctx) {
741
+ // If the character right before the cursor is a dot, this is a member-access
742
+ // completion (e.g. `({ ...x, ...y.| })`), not a destructuring/property-key
743
+ // completion. Defer to the dot handler.
744
+ if (offset > 0 && source[offset - 1] === '.')
745
+ return [];
746
+ // Scan backwards from cursor to find if we're inside { } that is part of a destructuring pattern
747
+ let braceDepth = 0;
748
+ let openBraceOffset = -1;
749
+ for (let i = offset - 1; i >= 0; i--) {
750
+ const ch = source[i];
751
+ if (ch === '}')
752
+ braceDepth++;
753
+ if (ch === '{') {
754
+ if (braceDepth === 0) {
755
+ openBraceOffset = i;
756
+ break;
757
+ }
758
+ braceDepth--;
759
+ }
760
+ if (ch === ';' || ch === '\n') {
761
+ continue;
762
+ }
763
+ }
764
+ if (openBraceOffset < 0)
765
+ return [];
766
+ const beforeBrace = source.substring(0, openBraceOffset).trimEnd();
767
+ // --- Parameter destructuring: ({ | }) => ... or ({ | }, ...) => ...
768
+ // Also covers nested object patterns: ({ address: { | } }) or
769
+ // const { a: { | } } = obj. The ObjectPattern node's start offset is the `{`.
770
+ // Lookup the recorded node type and offer record fields.
771
+ if (/[(,:]$/.test(beforeBrace)) {
772
+ const result = runInference(source, uri, ctx);
773
+ const entry = result.nodeTypes.get(openBraceOffset);
774
+ // Fields recorded on the literal itself (concrete property types).
775
+ let literalFields = null;
776
+ if (entry) {
777
+ const resolved = result.substitution.apply(entry.type);
778
+ literalFields = resolveRecordFields(resolved, result);
779
+ }
780
+ // Expected record type from the enclosing call's parameter signature.
781
+ // This is authoritative for available field names — it covers the
782
+ // empty-literal case `f(..., { | })` and, more importantly, the
783
+ // mid-typing case `f(..., { n| })` where the literal records a
784
+ // partial/unbound shape that would otherwise hide the real fields.
785
+ const expected = getExpectedRecordTypeForCallArg(source, openBraceOffset, result);
786
+ const expectedFields = expected ? resolveRecordFields(expected, result) : null;
787
+ // Prefer expected fields when available; merge in any literal fields
788
+ // that the expected type didn't already cover (e.g. open-record rest
789
+ // produced concrete extras on the literal).
790
+ let fields = null;
791
+ if (expectedFields && expectedFields.length > 0) {
792
+ const seen = new Set(expectedFields.map(([k]) => k));
793
+ const extras = (literalFields || []).filter(([k]) => !seen.has(k));
794
+ fields = [...expectedFields, ...extras];
795
+ }
796
+ else {
797
+ fields = literalFields;
798
+ }
799
+ if (fields) {
800
+ const presentKeys = getPresentKeys(source, openBraceOffset, offset);
801
+ // Exclude the identifier currently being typed at the cursor *only* when
802
+ // its inferred field type is an unbound type variable — the telltale
803
+ // sign of a phantom row-variable artifact (e.g. typing `ad` against an
804
+ // open record like `{ ...r }` produces `ad :: a`). Real expected
805
+ // fields keep their concrete name even while the user types them.
806
+ const typedWord = (0, hover_1.scanWord)(source, offset);
807
+ const typedKey = typedWord ? source.slice(typedWord.start, typedWord.end) : '';
808
+ const items = [];
809
+ for (const [fieldName, fieldType] of fields) {
810
+ // Skip keys already written in the literal — but never skip the
811
+ // key the user is *currently* typing, otherwise completing `n` to
812
+ // `name` would be impossible because `n` itself appears in
813
+ // `presentKeys` (it's a shorthand property at the cursor).
814
+ if (presentKeys.has(fieldName) && fieldName !== typedKey)
815
+ continue;
816
+ if (typedKey && fieldName === typedKey) {
817
+ const resolvedFieldType = result.substitution.apply(fieldType);
818
+ if (resolvedFieldType.tag === 'TVar')
819
+ continue;
820
+ }
821
+ // `T | Undefined` fields may be omitted: mark them, as for JSX props.
822
+ const optional = typeHasUndefined(result.substitution.apply(fieldType)) ? ' (optional)' : '';
823
+ items.push({
824
+ label: fieldName,
825
+ kind: fieldType.tag === 'TFun' ? node_1.CompletionItemKind.Method : node_1.CompletionItemKind.Field,
826
+ detail: `${fieldName} :: ${(0, types_1.prettyTypeToString)(fieldType)}${optional}`,
827
+ labelDetails: { description: (0, types_1.prettyTypeToString)(fieldType) + optional },
828
+ });
829
+ }
830
+ if (items.length > 0)
831
+ return items;
832
+ }
833
+ return [];
834
+ }
835
+ if (!/\b(const|let|var)$/.test(beforeBrace))
836
+ return [];
837
+ // Find the closing } and then the = and the RHS expression
838
+ let closeBraceOffset = -1;
839
+ let depth = 1;
840
+ for (let i = openBraceOffset + 1; i < source.length; i++) {
841
+ if (source[i] === '{')
842
+ depth++;
843
+ if (source[i] === '}') {
844
+ depth--;
845
+ if (depth === 0) {
846
+ closeBraceOffset = i;
847
+ break;
848
+ }
849
+ }
850
+ }
851
+ if (closeBraceOffset < 0)
852
+ return [];
853
+ let eqOffset = -1;
854
+ for (let i = closeBraceOffset + 1; i < source.length; i++) {
855
+ if (/\s/.test(source[i]))
856
+ continue;
857
+ if (source[i] === '=') {
858
+ eqOffset = i;
859
+ break;
860
+ }
861
+ break;
862
+ }
863
+ if (eqOffset < 0)
864
+ return [];
865
+ let rhsStart = eqOffset + 1;
866
+ while (rhsStart < source.length && /\s/.test(source[rhsStart]))
867
+ rhsStart++;
868
+ let rhsEnd = rhsStart;
869
+ while (rhsEnd < source.length && /[A-Za-z0-9_$]/.test(source[rhsEnd]))
870
+ rhsEnd++;
871
+ const rhsName = source.slice(rhsStart, rhsEnd);
872
+ if (!rhsName)
873
+ return [];
874
+ // Extend the RHS past chained member accesses and call expressions so
875
+ // we can resolve full expressions like `Organisation.props` or
876
+ // `Repo (Organisation)` (not just the first identifier).
877
+ let rhsChainEnd = rhsEnd;
878
+ // eslint-disable-next-line no-constant-condition
879
+ while (true) {
880
+ // Skip whitespace between chain segments (e.g. `Repo (X)` with a space).
881
+ let probe = rhsChainEnd;
882
+ while (probe < source.length && /\s/.test(source[probe]))
883
+ probe++;
884
+ if (probe >= source.length)
885
+ break;
886
+ const ch = source[probe];
887
+ if (ch === '.' && probe + 1 < source.length && /[A-Za-z_$]/.test(source[probe + 1])) {
888
+ rhsChainEnd = probe + 1;
889
+ while (rhsChainEnd < source.length && /[A-Za-z0-9_$]/.test(source[rhsChainEnd]))
890
+ rhsChainEnd++;
891
+ continue;
892
+ }
893
+ if (ch === '(') {
894
+ // Skip a balanced parenthesised call argument list. Track string
895
+ // literals so parens inside strings don't throw off the depth count.
896
+ let depth = 1;
897
+ let i = probe + 1;
898
+ let str = null;
899
+ while (i < source.length && depth > 0) {
900
+ const c = source[i];
901
+ if (str) {
902
+ if (c === '\\') {
903
+ i += 2;
904
+ continue;
905
+ }
906
+ if (c === str)
907
+ str = null;
908
+ }
909
+ else {
910
+ if (c === '"' || c === "'" || c === '`')
911
+ str = c;
912
+ else if (c === '(')
913
+ depth++;
914
+ else if (c === ')')
915
+ depth--;
916
+ }
917
+ i++;
918
+ }
919
+ if (depth !== 0)
920
+ break;
921
+ rhsChainEnd = i;
922
+ continue;
923
+ }
924
+ break;
925
+ }
926
+ const result = runInference(source, uri, ctx);
927
+ const items = [];
928
+ // 0) Resolve the type of the full RHS expression (member chain ending at
929
+ // `rhsChainEnd`). When it's a record (or a Union containing a record
930
+ // branch — e.g. query-builder tables), offer its fields.
931
+ if (rhsChainEnd > rhsEnd) {
932
+ const entry = result.nodeTypesByEnd.get(rhsChainEnd);
933
+ if (entry) {
934
+ const resolved = result.substitution.apply(entry.type);
935
+ const fields = resolveRecordFields(resolved, result);
936
+ if (fields) {
937
+ for (const [fieldName, fieldType] of fields) {
938
+ if (!items.some(i => i.label === fieldName)) {
939
+ const ft = result.substitution.apply(fieldType);
940
+ items.push({
941
+ label: fieldName,
942
+ kind: ft.tag === 'TFun' ? node_1.CompletionItemKind.Method : node_1.CompletionItemKind.Field,
943
+ detail: `${fieldName} :: ${(0, types_1.prettyTypeToString)(ft)}`,
944
+ labelDetails: { description: (0, types_1.prettyTypeToString)(ft) },
945
+ });
946
+ }
947
+ }
948
+ if (items.length > 0)
949
+ return items;
950
+ }
951
+ }
952
+ }
953
+ // 1) Check if the RHS is a default-imported identifier → offer named module exports
954
+ const importSpecifiers = (0, files_1.extractImportSpecifiers)(source);
955
+ const defaultImportRegex = /import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g;
956
+ let m;
957
+ const defaultImports = new Map();
958
+ while ((m = defaultImportRegex.exec(source)) !== null) {
959
+ defaultImports.set(m[1], m[2]);
960
+ }
961
+ const moduleSpecifier = defaultImports.get(rhsName);
962
+ if (moduleSpecifier) {
963
+ const targetUri = (0, files_1.resolveImportSpecifier)(moduleSpecifier, uri);
964
+ if (targetUri) {
965
+ const exports = ctx.inferFileAndCacheExports(targetUri);
966
+ if (exports) {
967
+ for (const [name, scheme] of exports) {
968
+ if (name === 'default')
969
+ continue;
970
+ const instType = result.substitution.apply(safeInstantiate(scheme));
971
+ items.push({
972
+ label: name,
973
+ kind: instType.tag === 'TFun' ? node_1.CompletionItemKind.Function : node_1.CompletionItemKind.Field,
974
+ detail: `${name} :: ${(0, types_1.prettyTypeToString)(instType)}`,
975
+ });
976
+ }
977
+ }
978
+ }
979
+ }
980
+ // 2) Check if the RHS has a record type → offer record fields
981
+ for (const [start, { type, end }] of result.nodeTypes) {
982
+ if (start >= rhsStart && start < rhsEnd) {
983
+ const resolved = result.substitution.apply(type);
984
+ if (resolved.tag === 'TRecord') {
985
+ for (const [fieldName, fieldType] of Object.entries(resolved.fields)) {
986
+ if (resolved.hiddenFields?.has(fieldName))
987
+ continue;
988
+ if (!items.some(i => i.label === fieldName)) {
989
+ items.push({
990
+ label: fieldName,
991
+ kind: fieldType.tag === 'TFun' ? node_1.CompletionItemKind.Method : node_1.CompletionItemKind.Field,
992
+ detail: `${fieldName} :: ${(0, types_1.prettyTypeToString)(fieldType)}`,
993
+ labelDetails: { description: (0, types_1.prettyTypeToString)(fieldType) },
994
+ });
995
+ }
996
+ }
997
+ }
998
+ if (resolved.tag === 'TCon') {
999
+ const alias = result.typeAliases.get(resolved.name);
1000
+ if (alias && alias.type.tag === 'TRecord') {
1001
+ for (const [fieldName, fieldType] of Object.entries(alias.type.fields)) {
1002
+ if (alias.type.hiddenFields?.has(fieldName))
1003
+ continue;
1004
+ if (!items.some(i => i.label === fieldName)) {
1005
+ items.push({
1006
+ label: fieldName,
1007
+ kind: fieldType.tag === 'TFun' ? node_1.CompletionItemKind.Method : node_1.CompletionItemKind.Field,
1008
+ detail: `${fieldName} :: ${(0, types_1.prettyTypeToString)(fieldType)}`,
1009
+ labelDetails: { description: (0, types_1.prettyTypeToString)(fieldType) },
1010
+ });
1011
+ }
1012
+ }
1013
+ }
1014
+ const names = (0, index_1.getMethodNames)(resolved.name);
1015
+ for (const name of names) {
1016
+ if (!items.some(i => i.label === name)) {
1017
+ const entry = (0, index_1.lookupMethod)(resolved.name, name);
1018
+ if (entry) {
1019
+ const methodType = entry.factory(resolved.args);
1020
+ items.push({
1021
+ label: name,
1022
+ kind: node_1.CompletionItemKind.Method,
1023
+ detail: `${resolved.name}#${name} :: ${(0, types_1.prettyTypeToString)(resolved)} ~> ${(0, types_1.prettyTypeToString)(methodType)}`,
1024
+ });
1025
+ }
1026
+ }
1027
+ }
1028
+ }
1029
+ break;
1030
+ }
1031
+ }
1032
+ return items;
1033
+ }
1034
+ // ---------------------------------------------------------------------------
1035
+ // Import specifier completion — inside import { | } from './module'
1036
+ // ---------------------------------------------------------------------------
1037
+ /**
1038
+ * Detect if the cursor is inside an import specifier list: `import { | } from './module'`
1039
+ * If so, return completions of available exports from the target module.
1040
+ */
1041
+ function getImportSpecifierCompletions(source, offset, uri, ctx) {
1042
+ const lineStart = source.lastIndexOf('\n', offset - 1) + 1;
1043
+ const lineEnd = source.indexOf('\n', offset);
1044
+ const line = source.slice(lineStart, lineEnd < 0 ? source.length : lineEnd);
1045
+ let braceOpen = -1;
1046
+ for (let i = offset - 1; i >= lineStart; i--) {
1047
+ if (source[i] === '{') {
1048
+ braceOpen = i;
1049
+ break;
1050
+ }
1051
+ if (source[i] === '}')
1052
+ break;
1053
+ }
1054
+ if (braceOpen < 0)
1055
+ return null;
1056
+ const beforeBrace = source.substring(Math.max(0, braceOpen - 100), braceOpen).trimEnd();
1057
+ if (!/\bimport\s*$/.test(beforeBrace))
1058
+ return null;
1059
+ const fromMatch = line.match(/from\s+['"]([^'"]+)['"]/);
1060
+ if (!fromMatch)
1061
+ return null;
1062
+ const specifier = fromMatch[1];
1063
+ // From here on the cursor is definitely inside an import-specifier list —
1064
+ // return [] (not null) on resolution failure so the caller does not fall
1065
+ // through to identifier completion, which would nonsensically suggest the
1066
+ // current file's own bindings inside `import { | } from '…'`.
1067
+ let exports = null;
1068
+ const targetUri = (0, files_1.resolveImportSpecifier)(specifier, uri);
1069
+ if (targetUri)
1070
+ exports = ctx.inferFileAndCacheExports(targetUri);
1071
+ if (!exports || exports.size === 0) {
1072
+ // The full resolver additionally handles project `.hm` overrides,
1073
+ // conventional `hm-types/<pkg>.hm` stubs and package sidecars — the
1074
+ // only way to complete `import { useState } from 'react'` typed via
1075
+ // a `react.hm` override.
1076
+ const resolved = ctx.createImportResolver(uri)(specifier);
1077
+ if (resolved instanceof Map)
1078
+ exports = resolved;
1079
+ }
1080
+ if (!exports)
1081
+ return [];
1082
+ const alreadyImported = new Set();
1083
+ const insideBraces = source.slice(braceOpen + 1, offset);
1084
+ for (const part of insideBraces.split(',')) {
1085
+ const name = part.trim().split(/\s+as\s+/)[0]?.trim();
1086
+ if (name)
1087
+ alreadyImported.add(name);
1088
+ }
1089
+ const items = [];
1090
+ for (const [name, scheme] of exports) {
1091
+ if (name === 'default')
1092
+ continue;
1093
+ if (!/^[A-Za-z_$][\w$]*$/.test(name))
1094
+ continue; // skip Type#method entries
1095
+ if (alreadyImported.has(name))
1096
+ continue;
1097
+ const instType = safeInstantiate(scheme);
1098
+ items.push({
1099
+ label: name,
1100
+ kind: scheme.type.tag === 'TFun' ? node_1.CompletionItemKind.Function : node_1.CompletionItemKind.Variable,
1101
+ detail: `${name} :: ${(0, types_1.prettyTypeToString)(instType)}`,
1102
+ });
1103
+ }
1104
+ return items;
1105
+ }
1106
+ // ---------------------------------------------------------------------------
1107
+ // Import path completion — inside from '|' or from "./|"
1108
+ // ---------------------------------------------------------------------------
1109
+ /**
1110
+ * Detect if the cursor is inside a string in 'from' or 'require' — suggest relative file paths.
1111
+ */
1112
+ function getImportPathCompletions(source, offset, uri, ctx) {
1113
+ let quoteChar = null;
1114
+ let quoteStart = -1;
1115
+ for (let i = offset - 1; i >= 0; i--) {
1116
+ if (source[i] === '\'' || source[i] === '"') {
1117
+ quoteChar = source[i];
1118
+ quoteStart = i;
1119
+ break;
1120
+ }
1121
+ if (source[i] === '\n')
1122
+ break;
1123
+ }
1124
+ if (!quoteChar || quoteStart < 0)
1125
+ return null;
1126
+ const beforeQuote = source.substring(Math.max(0, quoteStart - 50), quoteStart).trimEnd();
1127
+ if (!/\bfrom\s*$/.test(beforeQuote) && !/\brequire\s*\(\s*$/.test(beforeQuote))
1128
+ return null;
1129
+ const partial = source.slice(quoteStart + 1, offset);
1130
+ const fromPath = (0, url_1.fileURLToPath)(uri);
1131
+ const fromDir = path.dirname(fromPath);
1132
+ let searchDir;
1133
+ let prefix;
1134
+ if (partial.includes('/')) {
1135
+ const lastSlash = partial.lastIndexOf('/');
1136
+ prefix = partial.slice(lastSlash + 1);
1137
+ const dirPart = partial.slice(0, lastSlash) || '.';
1138
+ searchDir = path.resolve(fromDir, dirPart);
1139
+ }
1140
+ else {
1141
+ prefix = partial;
1142
+ if (!partial.startsWith('.')) {
1143
+ return [
1144
+ { label: './', kind: node_1.CompletionItemKind.Folder, insertText: './' },
1145
+ { label: '../', kind: node_1.CompletionItemKind.Folder, insertText: '../' },
1146
+ ];
1147
+ }
1148
+ searchDir = path.resolve(fromDir, partial || '.');
1149
+ prefix = '';
1150
+ }
1151
+ try {
1152
+ const entries = fs.readdirSync(searchDir, { withFileTypes: true });
1153
+ const items = [];
1154
+ for (const entry of entries) {
1155
+ if (entry.name.startsWith('.'))
1156
+ continue;
1157
+ if (entry.name === 'node_modules')
1158
+ continue;
1159
+ if (entry.isDirectory()) {
1160
+ if (!prefix || entry.name.startsWith(prefix)) {
1161
+ items.push({
1162
+ label: entry.name + '/',
1163
+ kind: node_1.CompletionItemKind.Folder,
1164
+ insertText: entry.name + '/',
1165
+ });
1166
+ }
1167
+ }
1168
+ else if (entry.isFile()) {
1169
+ const ext = path.extname(entry.name);
1170
+ if (!['.js', '.mjs', '.cjs', '.jsx'].includes(ext))
1171
+ continue;
1172
+ const nameWithoutExt = entry.name.replace(/\.(js|mjs|cjs|jsx)$/, '');
1173
+ if (!prefix || nameWithoutExt.startsWith(prefix) || entry.name.startsWith(prefix)) {
1174
+ const filePath = path.join(searchDir, entry.name);
1175
+ const fileUri = (0, url_1.pathToFileURL)(filePath).href;
1176
+ let detail;
1177
+ try {
1178
+ const exports = ctx.inferFileAndCacheExports(fileUri);
1179
+ if (exports) {
1180
+ const exportNames = [...exports.keys()].filter(n => n !== 'default');
1181
+ if (exportNames.length > 0) {
1182
+ detail = `exports: ${exportNames.join(', ')}`;
1183
+ }
1184
+ }
1185
+ }
1186
+ catch { /* inference failed — show file without export detail */ }
1187
+ items.push({
1188
+ label: nameWithoutExt,
1189
+ kind: node_1.CompletionItemKind.File,
1190
+ detail,
1191
+ insertText: nameWithoutExt,
1192
+ });
1193
+ }
1194
+ }
1195
+ }
1196
+ return items.length > 0 ? items : null;
1197
+ }
1198
+ catch { /* directory unreadable — no path completions */
1199
+ return null;
1200
+ }
1201
+ }
1202
+ // ---------------------------------------------------------------------------
1203
+ // Type directive path completion — inside `// ::types <partial>`
1204
+ // ---------------------------------------------------------------------------
1205
+ /**
1206
+ * Suggest workspace-relative paths after a `::types` directive in a comment.
1207
+ * Triggered when the cursor sits on a line of the form
1208
+ * `// ::types <partial>` or `/* ::types <partial>`. Folders end with `/`,
1209
+ * JS files appear without their extension. Directories are also valid
1210
+ * targets (resolved to their `index.js`).
1211
+ */
1212
+ function getTypeDirectivePathCompletions(source, offset, uri) {
1213
+ if (!(0, hover_1.isOffsetInComment)(source, offset))
1214
+ return null;
1215
+ const lineStart = source.lastIndexOf('\n', offset - 1) + 1;
1216
+ const lineBefore = source.slice(lineStart, offset);
1217
+ // Match `// ::types ` (or with surrounding * for block comments) followed
1218
+ // by a partial path. We require at least one space after `::types`.
1219
+ const m = /(?:\/\/|\/\*|\*)\s*::types\s+(\S*)$/.exec(lineBefore);
1220
+ if (!m)
1221
+ return null;
1222
+ const partial = m[1];
1223
+ // Bare specifier (no leading `.` or `/`) — only suggest the leading
1224
+ // `./` and `../` prefixes; bare package paths are a separate concern.
1225
+ if (partial.length === 0 || (!partial.startsWith('.') && !partial.startsWith('/'))) {
1226
+ return [
1227
+ {
1228
+ label: './',
1229
+ kind: node_1.CompletionItemKind.Folder,
1230
+ insertText: './',
1231
+ command: { command: 'editor.action.triggerSuggest', title: 'Re-trigger completions' },
1232
+ },
1233
+ {
1234
+ label: '../',
1235
+ kind: node_1.CompletionItemKind.Folder,
1236
+ insertText: '../',
1237
+ command: { command: 'editor.action.triggerSuggest', title: 'Re-trigger completions' },
1238
+ },
1239
+ ];
1240
+ }
1241
+ const fromPath = (0, url_1.fileURLToPath)(uri);
1242
+ const fromDir = path.dirname(fromPath);
1243
+ let searchDir;
1244
+ let prefix;
1245
+ const lastSlash = partial.lastIndexOf('/');
1246
+ if (lastSlash >= 0) {
1247
+ prefix = partial.slice(lastSlash + 1);
1248
+ const dirPart = partial.slice(0, lastSlash) || '.';
1249
+ searchDir = path.resolve(fromDir, dirPart);
1250
+ }
1251
+ else {
1252
+ prefix = '';
1253
+ searchDir = path.resolve(fromDir, partial);
1254
+ }
1255
+ try {
1256
+ const entries = fs.readdirSync(searchDir, { withFileTypes: true });
1257
+ const items = [];
1258
+ for (const entry of entries) {
1259
+ if (entry.name.startsWith('.'))
1260
+ continue;
1261
+ if (entry.name === 'node_modules')
1262
+ continue;
1263
+ if (entry.isDirectory()) {
1264
+ if (!prefix || entry.name.startsWith(prefix)) {
1265
+ items.push({
1266
+ label: entry.name + '/',
1267
+ kind: node_1.CompletionItemKind.Folder,
1268
+ insertText: entry.name + '/',
1269
+ // Re-trigger completion after the trailing slash so the user can
1270
+ // immediately drill into the chosen folder without retyping.
1271
+ command: { command: 'editor.action.triggerSuggest', title: 'Re-trigger completions' },
1272
+ sortText: '0_' + entry.name,
1273
+ });
1274
+ }
1275
+ }
1276
+ else if (entry.isFile()) {
1277
+ const ext = path.extname(entry.name);
1278
+ if (!['.js', '.mjs', '.cjs', '.jsx'].includes(ext))
1279
+ continue;
1280
+ const nameWithoutExt = entry.name.replace(/\.(js|mjs|cjs|jsx)$/, '');
1281
+ if (!prefix || nameWithoutExt.startsWith(prefix) || entry.name.startsWith(prefix)) {
1282
+ items.push({
1283
+ label: nameWithoutExt,
1284
+ kind: node_1.CompletionItemKind.File,
1285
+ insertText: nameWithoutExt,
1286
+ detail: ext,
1287
+ sortText: '1_' + nameWithoutExt,
1288
+ });
1289
+ }
1290
+ }
1291
+ }
1292
+ return items.length > 0 ? items : null;
1293
+ }
1294
+ catch {
1295
+ return null;
1296
+ }
1297
+ }
1298
+ // ---------------------------------------------------------------------------
1299
+ // Workspace export scanning (for auto-import)
1300
+ //
1301
+ // Plain language: to suggest names the user has NOT imported yet, we need to
1302
+ // know what every other file in the project exports. Finding that out means
1303
+ // reading and type-checking those files, which is expensive — so this section
1304
+ // is mostly about caching: remember each file's exports until it changes on
1305
+ // disk, warm the cache in the background between keystrokes, and put strict
1306
+ // limits (file count, time budget) on how much work one request may do.
1307
+ // ---------------------------------------------------------------------------
1308
+ /** Maximum number of files to scan for workspace exports to avoid runaway I/O. */
1309
+ const MAX_SCAN_FILES = 500;
1310
+ /** Time budget (ms) a single direct {@link getWorkspaceExports} call may
1311
+ * spend inferring not-yet-cached workspace files. The identifier-
1312
+ * completion request path passes `0` (cache-only): inference there is
1313
+ * driven exclusively by {@link warmWorkspaceExports} in the background,
1314
+ * because a single uncached file can recursively infer its whole import
1315
+ * chain and stall the request for hundreds of ms. */
1316
+ const WS_SCAN_BUDGET_MS = 40;
1317
+ /** Per-file workspace-export cache keyed by file URI. An entry is valid
1318
+ * as long as the file's on-disk mtime is unchanged. `exports === null`
1319
+ * caches inference failures so broken files aren't re-inferred on every
1320
+ * keystroke; `mtimeMs === null` records an unstattable (deleted) file. */
1321
+ const fileExportCache = new Map();
1322
+ /** Short-lived mtime cache so a single completion request doesn't issue
1323
+ * one `statSync` per workspace file per keystroke. */
1324
+ const statCache = new Map();
1325
+ const STAT_TTL_MS = 2000;
1326
+ /** Short-lived cache of the candidate-file listing per source directory
1327
+ * (readdir of the dir, its subdirs and parent siblings is ~ms but adds
1328
+ * up when repeated on every keystroke). */
1329
+ const scanListCache = new Map();
1330
+ const SCAN_LIST_TTL_MS = 5000;
1331
+ function statMtime(filePath) {
1332
+ const now = Date.now();
1333
+ const cached = statCache.get(filePath);
1334
+ if (cached && now - cached.at < STAT_TTL_MS)
1335
+ return cached.mtimeMs;
1336
+ let mtimeMs = null;
1337
+ try {
1338
+ mtimeMs = fs.statSync(filePath).mtimeMs;
1339
+ }
1340
+ catch { /* unreadable/deleted */ }
1341
+ statCache.set(filePath, { at: now, mtimeMs });
1342
+ return mtimeMs;
1343
+ }
1344
+ /** Drop all cached workspace-export entries (tests / globals reload). */
1345
+ function clearWorkspaceExportCache() {
1346
+ fileExportCache.clear();
1347
+ statCache.clear();
1348
+ scanListCache.clear();
1349
+ }
1350
+ /** Evict a single file's cached workspace exports (e.g. on editor edits,
1351
+ * which don't touch the on-disk mtime the cache is keyed by). */
1352
+ function invalidateWorkspaceExportEntry(uri) {
1353
+ fileExportCache.delete(uri);
1354
+ }
1355
+ /**
1356
+ * Enumerate the JS files the workspace-export scan considers for `uri`:
1357
+ * the file's own directory, its subdirectories, the parent directory and
1358
+ * the parent's sibling directories — capped at {@link MAX_SCAN_FILES}.
1359
+ */
1360
+ function listWorkspaceScanFiles(uri) {
1361
+ const fromPath = (0, url_1.fileURLToPath)(uri);
1362
+ const fromDir = path.dirname(fromPath);
1363
+ const listCached = scanListCache.get(fromPath);
1364
+ if (listCached && Date.now() - listCached.at < SCAN_LIST_TTL_MS) {
1365
+ return listCached.files;
1366
+ }
1367
+ const dirsToScan = [fromDir];
1368
+ const parentDir = path.dirname(fromDir);
1369
+ if (parentDir !== fromDir) {
1370
+ dirsToScan.push(parentDir);
1371
+ }
1372
+ try {
1373
+ for (const entry of fs.readdirSync(fromDir, { withFileTypes: true })) {
1374
+ if (entry.isDirectory() && !entry.name.startsWith('.') && entry.name !== 'node_modules') {
1375
+ dirsToScan.push(path.join(fromDir, entry.name));
1376
+ }
1377
+ }
1378
+ }
1379
+ catch { /* directory unreadable — scan without subdirs */ }
1380
+ // Also scan sibling directories of the parent (one level up), so files in
1381
+ // e.g. `src/predicate/` can see exports from `src/more/`.
1382
+ if (parentDir !== fromDir) {
1383
+ try {
1384
+ for (const entry of fs.readdirSync(parentDir, { withFileTypes: true })) {
1385
+ if (!entry.isDirectory())
1386
+ continue;
1387
+ if (entry.name.startsWith('.') || entry.name === 'node_modules')
1388
+ continue;
1389
+ const sibling = path.join(parentDir, entry.name);
1390
+ if (sibling === fromDir)
1391
+ continue;
1392
+ dirsToScan.push(sibling);
1393
+ }
1394
+ }
1395
+ catch { /* parent unreadable */ }
1396
+ }
1397
+ const seen = new Set();
1398
+ const files = [];
1399
+ outer: for (const dir of dirsToScan) {
1400
+ let entries;
1401
+ try {
1402
+ entries = fs.readdirSync(dir, { withFileTypes: true });
1403
+ }
1404
+ catch { /* directory unreadable */
1405
+ continue;
1406
+ }
1407
+ for (const entry of entries) {
1408
+ if (!entry.isFile())
1409
+ continue;
1410
+ const ext = path.extname(entry.name);
1411
+ if (!['.js', '.mjs', '.cjs', '.jsx'].includes(ext))
1412
+ continue;
1413
+ if (seen.size >= MAX_SCAN_FILES)
1414
+ break outer;
1415
+ const filePath = path.join(dir, entry.name);
1416
+ if (filePath === fromPath)
1417
+ continue;
1418
+ const fileUri = (0, url_1.pathToFileURL)(filePath).href;
1419
+ if (seen.has(fileUri))
1420
+ continue;
1421
+ seen.add(fileUri);
1422
+ let rel = path.relative(fromDir, filePath);
1423
+ rel = rel.replace(/\\/g, '/');
1424
+ rel = rel.replace(/\.(js|mjs|cjs|jsx)$/, '');
1425
+ if (!rel.startsWith('.'))
1426
+ rel = './' + rel;
1427
+ files.push({ filePath, fileUri, rel });
1428
+ }
1429
+ }
1430
+ scanListCache.set(fromPath, { at: Date.now(), files });
1431
+ return files;
1432
+ }
1433
+ /**
1434
+ * Look up (or compute and cache) the exports of a single scan candidate.
1435
+ * Returns `undefined` when the file cannot be stat'ed, `null` when
1436
+ * inference failed / produced no exports.
1437
+ */
1438
+ function cachedFileExports(file, inferFileAndCacheExports) {
1439
+ const mtimeMs = statMtime(file.filePath);
1440
+ if (mtimeMs === null) {
1441
+ // Record the miss so warming loops don't retry a vanished file forever.
1442
+ fileExportCache.set(file.fileUri, { mtimeMs: null, exports: null });
1443
+ return undefined;
1444
+ }
1445
+ const cached = fileExportCache.get(file.fileUri);
1446
+ if (cached && cached.mtimeMs === mtimeMs)
1447
+ return cached.exports;
1448
+ let exports = null;
1449
+ try {
1450
+ exports = inferFileAndCacheExports(file.fileUri);
1451
+ }
1452
+ catch { /* inference failure — cache the miss */ }
1453
+ fileExportCache.set(file.fileUri, { mtimeMs, exports });
1454
+ return exports;
1455
+ }
1456
+ /** True when `file` has a valid (mtime-fresh) cache entry. */
1457
+ function isExportCacheFresh(file) {
1458
+ const cached = fileExportCache.get(file.fileUri);
1459
+ if (!cached)
1460
+ return false;
1461
+ return statMtime(file.filePath) === cached.mtimeMs;
1462
+ }
1463
+ /** Cheap regex-based extraction of relative import/require specifiers. */
1464
+ const RELATIVE_SPEC_RE = /require\s*\(\s*['"](\.[^'"]*)['"]\s*\)|from\s+['"](\.[^'"]*)['"]/g;
1465
+ function relativeSpecifiers(source) {
1466
+ const specs = [];
1467
+ for (const m of source.matchAll(RELATIVE_SPEC_RE)) {
1468
+ const spec = m[1] ?? m[2];
1469
+ if (spec)
1470
+ specs.push(spec);
1471
+ }
1472
+ return specs;
1473
+ }
1474
+ /** Resolve a relative specifier to an existing JS file path, or null. */
1475
+ function resolveRelativeSpec(fromPath, spec) {
1476
+ const base = path.resolve(path.dirname(fromPath), spec);
1477
+ const candidates = /\.(js|mjs|cjs|jsx)$/.test(base)
1478
+ ? [base]
1479
+ : [base + '.js', base + '.mjs', base + '.cjs', base + '.jsx', path.join(base, 'index.js'), path.join(base, 'index.jsx')];
1480
+ for (const cand of candidates) {
1481
+ if (statMtime(cand) !== null)
1482
+ return cand;
1483
+ }
1484
+ return null;
1485
+ }
1486
+ /**
1487
+ * Walk `file`'s not-yet-cached transitive dependencies and return the
1488
+ * "coldest leaf": an uncached file none of whose own deps are uncached.
1489
+ * Warming leaves first keeps each warm step roughly one file's inference
1490
+ * cost — inferring a barrel file with a cold import chain would otherwise
1491
+ * synchronously infer the whole chain (seconds in large repos).
1492
+ */
1493
+ function findColdLeaf(file, visited) {
1494
+ if (visited.has(file.filePath) || visited.size > 100)
1495
+ return file;
1496
+ visited.add(file.filePath);
1497
+ let source;
1498
+ try {
1499
+ source = fs.readFileSync(file.filePath, 'utf8');
1500
+ }
1501
+ catch {
1502
+ return file;
1503
+ }
1504
+ for (const spec of relativeSpecifiers(source)) {
1505
+ const depPath = resolveRelativeSpec(file.filePath, spec);
1506
+ if (!depPath || visited.has(depPath))
1507
+ continue;
1508
+ const dep = {
1509
+ filePath: depPath,
1510
+ fileUri: (0, url_1.pathToFileURL)(depPath).href,
1511
+ rel: '',
1512
+ };
1513
+ if (isExportCacheFresh(dep))
1514
+ continue;
1515
+ return findColdLeaf(dep, visited);
1516
+ }
1517
+ return file;
1518
+ }
1519
+ /**
1520
+ * Incrementally warm the workspace-export cache for `uri`: infer up to
1521
+ * `maxFiles` not-yet-cached candidate files (dependency-leaves first) and
1522
+ * cache their exports. Returns `true` when every candidate is cached
1523
+ * (warming complete).
1524
+ *
1525
+ * The server calls this from a background timer loop after validation, so
1526
+ * the first identifier completion doesn't have to pay for a full workspace
1527
+ * scan (~seconds in large repos) on the request path.
1528
+ */
1529
+ function warmWorkspaceExports(uri, inferFileAndCacheExports, maxFiles = 2) {
1530
+ const files = listWorkspaceScanFiles(uri);
1531
+ // Scan-triggered inference must not corrupt the built-in method registry
1532
+ // (see getWorkspaceExports below for the full rationale).
1533
+ const builtinSnap = (0, methodRegistry_1.snapshotBuiltinOriginalEntries)();
1534
+ let warmed = 0;
1535
+ try {
1536
+ for (const file of files) {
1537
+ if (isExportCacheFresh(file))
1538
+ continue;
1539
+ if (warmed >= maxFiles)
1540
+ return false;
1541
+ // Warm the coldest transitive dependency instead of `file` itself:
1542
+ // its own turn comes on a later call, by which time its chain is
1543
+ // cached and inferring it is cheap.
1544
+ const leaf = findColdLeaf(file, new Set());
1545
+ cachedFileExports(leaf, inferFileAndCacheExports);
1546
+ warmed++;
1547
+ if (leaf.filePath !== file.filePath)
1548
+ return false;
1549
+ }
1550
+ return true;
1551
+ }
1552
+ finally {
1553
+ (0, methodRegistry_1.restoreBuiltinOriginalEntries)(builtinSnap);
1554
+ }
1555
+ }
1556
+ /**
1557
+ * Scan the workspace directory (same folder and common relatives) for JS files
1558
+ * that export symbols. Returns a map from export name to sources.
1559
+ *
1560
+ * Per-file results are cached by mtime, so only new/changed files pay for
1561
+ * inference. Uncached files are inferred until `budgetMs` is exhausted;
1562
+ * the rest are skipped this round (their results appear on later requests
1563
+ * or via {@link warmWorkspaceExports}). This keeps a single completion
1564
+ * request bounded instead of synchronously inferring hundreds of files.
1565
+ */
1566
+ function getWorkspaceExports(uri, inferFileAndCacheExports, budgetMs = WS_SCAN_BUDGET_MS) {
1567
+ const start = Date.now();
1568
+ const files = listWorkspaceScanFiles(uri);
1569
+ const result = new Map();
1570
+ // Scan-triggered inferences must NOT corrupt the global method registry:
1571
+ // a workspace-sibling file may contain a shorthand annotation like
1572
+ // `// Array.every :: (a -> Boolean) -> Array a -> Boolean` whose static
1573
+ // registration overwrites the built-in instance `Array.every` factory
1574
+ // (kept on the same key). After completion finishes, the corrupted
1575
+ // entry would surface as bogus diagnostics on legitimate `arr.every(...)`
1576
+ // calls (e.g. `Cannot unify '[a] -> Boolean' with 'Boolean'`).
1577
+ // Snapshot the current original-key built-in entries before the scan and
1578
+ // restore them afterwards. Custom additions on non-original keys are
1579
+ // preserved, so completion can still suggest workspace exports normally.
1580
+ const builtinSnap = (0, methodRegistry_1.snapshotBuiltinOriginalEntries)();
1581
+ try {
1582
+ for (const file of files) {
1583
+ // Budget check only gates *uncached* files: assembling cached
1584
+ // entries is cheap and always allowed. A zero budget makes the
1585
+ // scan cache-only (used by the completion request path).
1586
+ if (!isExportCacheFresh(file) && Date.now() - start >= budgetMs)
1587
+ continue;
1588
+ const exports = cachedFileExports(file, inferFileAndCacheExports);
1589
+ if (!exports)
1590
+ continue;
1591
+ for (const [name, scheme] of exports) {
1592
+ if (name === 'default') {
1593
+ const stem = path.basename(file.filePath, path.extname(file.filePath));
1594
+ if (!result.has(stem))
1595
+ result.set(stem, []);
1596
+ result.get(stem).push({ specifier: file.rel, scheme, fileUri: file.fileUri, isDefault: true });
1597
+ continue;
1598
+ }
1599
+ if (!result.has(name))
1600
+ result.set(name, []);
1601
+ result.get(name).push({ specifier: file.rel, scheme, fileUri: file.fileUri });
1602
+ }
1603
+ }
1604
+ }
1605
+ finally {
1606
+ (0, methodRegistry_1.restoreBuiltinOriginalEntries)(builtinSnap);
1607
+ }
1608
+ return result;
1609
+ }
1610
+ // ---------------------------------------------------------------------------
1611
+ // Auto-import text edit builders
1612
+ // ---------------------------------------------------------------------------
1613
+ /**
1614
+ * Detect whether a JS source file uses ES module syntax or CommonJS.
1615
+ * Heuristic: a top-level `import`/`export` keyword => ESM; otherwise if it
1616
+ * contains `require(` or `module.exports` => CJS. Defaults to ESM when
1617
+ * unclear.
1618
+ */
1619
+ function detectModuleStyle(source) {
1620
+ const lines = source.split('\n');
1621
+ for (const line of lines) {
1622
+ const trimmed = line.trim();
1623
+ if (trimmed.startsWith('//'))
1624
+ continue;
1625
+ if (/^(import\s|export\s)/.test(trimmed))
1626
+ return 'esm';
1627
+ }
1628
+ if (/\brequire\s*\(/.test(source) || /\bmodule\.exports\b/.test(source) || /\bexports\.\w+\s*=/.test(source)) {
1629
+ return 'cjs';
1630
+ }
1631
+ return 'esm';
1632
+ }
1633
+ /**
1634
+ * Build a text edit that inserts an import line at the top of the file.
1635
+ * Tries to append to an existing import from the same specifier if present.
1636
+ * Emits an `import` statement for ESM files and a `require` statement for
1637
+ * CJS files (detected via {@link detectModuleStyle}).
1638
+ */
1639
+ function buildAutoImportEdit(source, name, specifier, isDefault) {
1640
+ const style = detectModuleStyle(source);
1641
+ const escapedSpecifier = specifier.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1642
+ // For named imports, try to append to an existing braces-group with the
1643
+ // same specifier (works for both `import { X } from '…'` and
1644
+ // `const { X } = require('…')`).
1645
+ if (!isDefault) {
1646
+ const importRegex = new RegExp(`import\\s*\\{([^}]*)\\}\\s*from\\s*['"]${escapedSpecifier}['"]`, 'g');
1647
+ const importMatch = importRegex.exec(source);
1648
+ if (importMatch) {
1649
+ return appendToNamedImportBraces(source, importMatch, name);
1650
+ }
1651
+ const requireRegex = new RegExp(`const\\s*\\{([^}]*)\\}\\s*=\\s*require\\s*\\(\\s*['"]${escapedSpecifier}['"]\\s*\\)`, 'g');
1652
+ const requireMatch = requireRegex.exec(source);
1653
+ if (requireMatch) {
1654
+ return appendToNamedImportBraces(source, requireMatch, name);
1655
+ }
1656
+ }
1657
+ let insertLine = 0;
1658
+ const lines = source.split('\n');
1659
+ for (let i = 0; i < lines.length; i++) {
1660
+ if (/^\s*(import\s|const\s.*=\s*require\s*\()/.test(lines[i])) {
1661
+ insertLine = i + 1;
1662
+ }
1663
+ }
1664
+ let newImportText;
1665
+ if (style === 'cjs') {
1666
+ newImportText = isDefault
1667
+ ? `const ${name} = require('${specifier}');\n`
1668
+ : `const { ${name} } = require('${specifier}');\n`;
1669
+ }
1670
+ else {
1671
+ newImportText = isDefault
1672
+ ? `import ${name} from '${specifier}';\n`
1673
+ : `import { ${name} } from '${specifier}';\n`;
1674
+ }
1675
+ return node_1.TextEdit.insert({ line: insertLine, character: 0 }, newImportText);
1676
+ }
1677
+ /**
1678
+ * Append a name to an existing named import's braces (works for both
1679
+ * `import { X } from '...'` and `const { X } = require('...')`).
1680
+ */
1681
+ function appendToNamedImportBraces(source, match, name) {
1682
+ const bracePos = match.index + match[0].indexOf('}');
1683
+ let nameEnd = bracePos;
1684
+ while (nameEnd > 0 && /\s/.test(source[nameEnd - 1]))
1685
+ nameEnd--;
1686
+ let startLine = 0;
1687
+ let startNl = -1;
1688
+ for (let i = 0; i < nameEnd; i++) {
1689
+ if (source[i] === '\n') {
1690
+ startLine++;
1691
+ startNl = i;
1692
+ }
1693
+ }
1694
+ const startChar = nameEnd - startNl - 1;
1695
+ let endLine = startLine;
1696
+ let endNl = startNl;
1697
+ for (let i = nameEnd; i <= bracePos; i++) {
1698
+ if (source[i] === '\n') {
1699
+ endLine++;
1700
+ endNl = i;
1701
+ }
1702
+ }
1703
+ const endChar = (bracePos + 1) - endNl - 1;
1704
+ const trailingComma = source[nameEnd - 1] === ',';
1705
+ const newText = trailingComma ? ` ${name} }` : `, ${name} }`;
1706
+ return node_1.TextEdit.replace({ start: { line: startLine, character: startChar }, end: { line: endLine, character: endChar } }, newText);
1707
+ }
1708
+ // ---------------------------------------------------------------------------
1709
+ // Identifier completion with type info + auto-import suggestions
1710
+ // ---------------------------------------------------------------------------
1711
+ /**
1712
+ * Get identifier completions: all in-scope variables with their types,
1713
+ * plus auto-import suggestions from nearby files.
1714
+ *
1715
+ * Plain language: the user is typing a bare name (not after a dot, not in a
1716
+ * string or comment). We offer:
1717
+ * 1. every top-level binding in this file whose name starts with what has
1718
+ * been typed so far, labelled with its type (preferring the user's own
1719
+ * `::` annotation text over the machine-printed type);
1720
+ * 2. local variables in the enclosing scopes;
1721
+ * 3. optionally, exports from OTHER workspace files not yet imported —
1722
+ * picking one of those also inserts the matching `import` line
1723
+ * automatically (see `buildAutoImportEdit`).
1724
+ */
1725
+ function getIdentifierCompletions(source, offset, uri, ctx) {
1726
+ const wordStart = (0, hover_1.scanWord)(source, offset)?.start ?? offset;
1727
+ const partial = source.slice(wordStart, offset);
1728
+ if (wordStart > 0 && source[wordStart - 1] === '.')
1729
+ return [];
1730
+ const lineStart = source.lastIndexOf('\n', offset - 1) + 1;
1731
+ const lineBefore = source.slice(lineStart, wordStart);
1732
+ if (/\/\//.test(lineBefore))
1733
+ return [];
1734
+ let singleQuotes = 0, doubleQuotes = 0, backticks = 0;
1735
+ for (const ch of lineBefore) {
1736
+ if (ch === '\'')
1737
+ singleQuotes++;
1738
+ if (ch === '"')
1739
+ doubleQuotes++;
1740
+ if (ch === '`')
1741
+ backticks++;
1742
+ }
1743
+ if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0 || backticks % 2 !== 0)
1744
+ return [];
1745
+ const result = ctx.cachedResult ?? runInference(source, uri, ctx);
1746
+ const items = [];
1747
+ const addedNames = new Set();
1748
+ const formatType = ctx.inferredTypeStyle === 'pretty' ? types_1.prettyTypeToString : types_1.typeToString;
1749
+ const importMap = (0, files_1.extractImportSpecifiers)(source);
1750
+ for (const [name, scheme] of result.topLevelBindings) {
1751
+ if (partial && !name.startsWith(partial))
1752
+ continue;
1753
+ if (addedNames.has(name))
1754
+ continue;
1755
+ addedNames.add(name);
1756
+ // Prefer the user's verbatim annotation text when available, so the
1757
+ // completion detail matches exactly what they wrote in their `::`
1758
+ // signature (parens, whitespace, ordering). Lookup chain:
1759
+ // 1. local annotation in this file
1760
+ // 2. raw signature from a `.hm` sidecar of an imported binding
1761
+ // 3. fall back to pretty-printed inferred type
1762
+ const ann = result.annotations.get(name);
1763
+ const resolvedType = result.substitution.apply(scheme.type);
1764
+ let typeStr;
1765
+ if (ann?.raw && !ann.receiver) {
1766
+ typeStr = ann.raw;
1767
+ }
1768
+ else {
1769
+ const importSpec = importMap.get(name);
1770
+ const importedRaw = importSpec && ctx.getImportedRawSignature
1771
+ ? ctx.getImportedRawSignature(importSpec, name, uri)
1772
+ : null;
1773
+ typeStr = importedRaw ?? formatType(resolvedType);
1774
+ }
1775
+ const kind = resolvedType.tag === 'TFun'
1776
+ ? node_1.CompletionItemKind.Function
1777
+ : node_1.CompletionItemKind.Variable;
1778
+ items.push({
1779
+ label: name,
1780
+ kind,
1781
+ detail: typeStr,
1782
+ sortText: `0_${name}`,
1783
+ });
1784
+ }
1785
+ // Include local/scoped identifiers (function params, block-scoped vars)
1786
+ // that aren't in topLevelBindings.
1787
+ const scopeNames = (0, references_1.collectScopeBindings)(source, offset);
1788
+ for (const [name, declOffset] of scopeNames) {
1789
+ if (partial && !name.startsWith(partial))
1790
+ continue;
1791
+ if (addedNames.has(name))
1792
+ continue;
1793
+ addedNames.add(name);
1794
+ // Look up the inferred type from nodeTypes using the declaration offset
1795
+ let detail;
1796
+ const entry = result.nodeTypes.get(declOffset);
1797
+ if (entry) {
1798
+ detail = formatType(result.substitution.apply(entry.type));
1799
+ }
1800
+ const kind = entry && result.substitution.apply(entry.type).tag === 'TFun'
1801
+ ? node_1.CompletionItemKind.Function
1802
+ : node_1.CompletionItemKind.Variable;
1803
+ items.push({
1804
+ label: name,
1805
+ kind,
1806
+ detail,
1807
+ sortText: `0_${name}`,
1808
+ });
1809
+ }
1810
+ // Annotation names that don't yet have a binding (signature written, implementation pending).
1811
+ // Extract directly from comment text so this works even when the source has syntax errors
1812
+ // (e.g. the user is typing `const testN` and hasn't finished the declaration yet).
1813
+ const annNameRegex = /\/\/\s*([\w$]+)\s*::\s*(.+)/g;
1814
+ let annMatch;
1815
+ while ((annMatch = annNameRegex.exec(source)) !== null) {
1816
+ const name = annMatch[1];
1817
+ if (addedNames.has(name))
1818
+ continue;
1819
+ if (name.includes('#') || name.includes('.'))
1820
+ continue;
1821
+ if (/^[A-Z]/.test(name))
1822
+ continue; // skip type aliases / constructors
1823
+ if (partial && !name.startsWith(partial))
1824
+ continue;
1825
+ addedNames.add(name);
1826
+ items.push({
1827
+ label: name,
1828
+ kind: node_1.CompletionItemKind.Function,
1829
+ detail: annMatch[2].trim(),
1830
+ sortText: `0_${name}`,
1831
+ });
1832
+ }
1833
+ if (partial.length >= 2 && ctx.autoImports !== false) {
1834
+ const alreadyImported = new Set(result.topLevelBindings.keys());
1835
+ // Cache-only (budget 0): auto-import suggestions come from the
1836
+ // background-warmed workspace-export cache. Never infer on the
1837
+ // completion request path — in large repos that meant multi-second
1838
+ // freezes that also stalled queued diagnostics.
1839
+ const workspaceExports = getWorkspaceExports(uri, ctx.inferFileAndCacheExports, 0);
1840
+ for (const [name, sources] of workspaceExports) {
1841
+ if (!name.startsWith(partial))
1842
+ continue;
1843
+ if (alreadyImported.has(name))
1844
+ continue;
1845
+ if (addedNames.has(name))
1846
+ continue;
1847
+ addedNames.add(name);
1848
+ const { specifier, scheme, isDefault } = sources[0];
1849
+ const instType = safeInstantiate(scheme);
1850
+ const typeStr = formatType(instType);
1851
+ const kind = instType.tag === 'TFun'
1852
+ ? node_1.CompletionItemKind.Function
1853
+ : node_1.CompletionItemKind.Variable;
1854
+ items.push({
1855
+ label: name,
1856
+ kind,
1857
+ detail: `${typeStr} (from '${specifier}')`,
1858
+ sortText: `1_${name}`,
1859
+ additionalTextEdits: [buildAutoImportEdit(source, name, specifier, isDefault)],
1860
+ });
1861
+ }
1862
+ }
1863
+ return items;
1864
+ }
1865
+ // ---------------------------------------------------------------------------
1866
+ // Dot completion — expr.|
1867
+ // ---------------------------------------------------------------------------
1868
+ /**
1869
+ * Build completion items for constraint methods.
1870
+ *
1871
+ * - `kind: 'static'` selects methods *without* `~>` (used for plain TVar /
1872
+ * constructor-position completions). Constraint names may be applied
1873
+ * forms like `"Monoid (f a)"` and are reduced to their base name.
1874
+ * - `kind: 'instance'` selects methods *with* `~>` (used for kv-TCon /
1875
+ * value-position completions, e.g. `functor.map`). The signature is
1876
+ * the part after `~>`.
1877
+ */
1878
+ function buildConstraintCompletionItems(cNames, kind) {
1879
+ if (!cNames)
1880
+ return [];
1881
+ const items = [];
1882
+ for (const cName of cNames) {
1883
+ const baseName = kind === 'static' ? (0, types_1.constraintBaseName)(cName) : cName;
1884
+ const def = (0, index_1.lookupConstraint)(baseName);
1885
+ if (!def)
1886
+ continue;
1887
+ const effectiveMethods = (0, index_1.getEffectiveMethods)(baseName);
1888
+ for (const req of effectiveMethods) {
1889
+ const hasInstanceArrow = req.signature.includes('~>');
1890
+ if (kind === 'static' && hasInstanceArrow)
1891
+ continue;
1892
+ if (kind === 'instance' && !hasInstanceArrow)
1893
+ continue;
1894
+ const methodSig = kind === 'instance'
1895
+ ? req.signature.split('~>')[1].trim()
1896
+ : req.signature;
1897
+ const isFunction = kind === 'instance' || req.signature.includes('->');
1898
+ items.push({
1899
+ label: req.name,
1900
+ kind: isFunction ? node_1.CompletionItemKind.Method : node_1.CompletionItemKind.Field,
1901
+ detail: `[${baseName}] ${req.name} :: ${methodSig}`,
1902
+ });
1903
+ }
1904
+ }
1905
+ return items;
1906
+ }
1907
+ const buildStaticConstraintCompletionItems = (cNames) => buildConstraintCompletionItems(cNames, 'static');
1908
+ const buildInstanceConstraintCompletionItems = (cNames) => buildConstraintCompletionItems(cNames, 'instance');
1909
+ /**
1910
+ * Build completion items for the registered methods of `typeName`, picking
1911
+ * either instance methods (`#`) or static methods (`.`) and formatting the
1912
+ * detail line as `Type#name :: ...` or `Type.name :: ...`.
1913
+ *
1914
+ * `selfType` is the concrete carrier type used in the receiver display. For
1915
+ * static-only completions where the carrier is unused, pass the same TCon.
1916
+ */
1917
+ function methodCompletionsForType(typeName, typeArgs, kind, selfDisplay, includePrivate = false) {
1918
+ const items = [];
1919
+ for (const name of (0, index_1.getMethodNames)(typeName)) {
1920
+ // Statics colliding with an instance of the same name live in the
1921
+ // parallel namespace and are reachable only via lookupStaticMethod.
1922
+ // For static completion we prefer the static side; for instance
1923
+ // completion we prefer the instance side.
1924
+ const entry = kind === 'static'
1925
+ ? ((0, index_1.lookupStaticMethod)(typeName, name) ?? (0, index_1.lookupMethod)(typeName, name))
1926
+ : (0, index_1.lookupMethod)(typeName, name);
1927
+ if (!entry)
1928
+ continue;
1929
+ const isPriv = !!entry.private || (0, methodRegistry_1.isMethodPrivate)(typeName, name);
1930
+ // Hidden via ::hidden (not ::private) is always filtered.
1931
+ const hiddenByOther = (!!entry.hidden || (0, methodRegistry_1.isMethodHidden)(typeName, name)) && !isPriv;
1932
+ if (hiddenByOther)
1933
+ continue;
1934
+ // Private members are filtered unless completing on `this.`.
1935
+ if (isPriv && !includePrivate)
1936
+ continue;
1937
+ // `constructor` is implicitly hidden — every JS object has one and
1938
+ // surfacing it as a completion entry is rarely what the user wants.
1939
+ if (name === 'constructor')
1940
+ continue;
1941
+ const isStatic = !!entry.isStatic;
1942
+ if (kind === 'instance' && isStatic)
1943
+ continue;
1944
+ if (kind === 'static' && !isStatic)
1945
+ continue;
1946
+ const methodType = entry.factory(typeArgs);
1947
+ const detail = kind === 'instance'
1948
+ ? `${typeName}#${name} :: ${selfDisplay} ~> ${(0, types_1.prettyTypeToString)(methodType)}`
1949
+ : `${typeName}.${name} :: ${(0, types_1.prettyTypeToString)(methodType)}`;
1950
+ items.push({
1951
+ label: name,
1952
+ kind: node_1.CompletionItemKind.Method,
1953
+ detail,
1954
+ });
1955
+ }
1956
+ // Record-style sumtype variants name the fields they carry
1957
+ // (`Component :: | Engine { ext :: String, ... }`). A `Component ~>`
1958
+ // method reads those off `this`, so surface them as instance completions
1959
+ // even though they aren't registered methods.
1960
+ if (kind === 'instance') {
1961
+ for (const [fieldName, fieldTypeText] of (0, dataTypeRegistry_1.getVariantRecordFields)(typeName)) {
1962
+ if (items.some(i => i.label === fieldName))
1963
+ continue;
1964
+ items.push({
1965
+ label: fieldName,
1966
+ kind: node_1.CompletionItemKind.Field,
1967
+ detail: `${typeName}#${fieldName} :: ${fieldTypeText}`,
1968
+ });
1969
+ }
1970
+ }
1971
+ return items;
1972
+ }
1973
+ /**
1974
+ * Provide completions for bracket string access: `obj["` or `obj['`.
1975
+ * Suggests record field names when the object has a known TRecord type.
1976
+ */
1977
+ function getBracketStringCompletions(source, offset, uri, ctx) {
1978
+ // Detect pattern: identifier[" or identifier['
1979
+ // offset points right after the quote character
1980
+ const quoteIdx = offset - 1;
1981
+ if (quoteIdx < 1)
1982
+ return [];
1983
+ const quote = source[quoteIdx];
1984
+ if (quote !== '"' && quote !== "'")
1985
+ return [];
1986
+ const bracketIdx = quoteIdx - 1;
1987
+ if (source[bracketIdx] !== '[')
1988
+ return [];
1989
+ // Find the identifier before the bracket
1990
+ const identEnd = bracketIdx;
1991
+ const ident = (0, hover_1.scanWord)(source, identEnd);
1992
+ if (!ident)
1993
+ return [];
1994
+ const objName = source.slice(ident.start, identEnd);
1995
+ if (!objName)
1996
+ return [];
1997
+ // Patch out the incomplete bracket expression so inference doesn't choke.
1998
+ // Replace from '[' to end-of-line (or next ']'/';') with spaces.
1999
+ let patchEnd = offset;
2000
+ while (patchEnd < source.length && source[patchEnd] !== '\n' && source[patchEnd] !== ';')
2001
+ patchEnd++;
2002
+ const patched = source.substring(0, bracketIdx) + ' '.repeat(patchEnd - bracketIdx) + source.substring(patchEnd);
2003
+ const result = runInference(patched, uri, ctx);
2004
+ // Find the type of the object identifier
2005
+ let bestType = null;
2006
+ let bestStart = -1;
2007
+ for (const [start, { type }] of result.nodeTypes) {
2008
+ const nodeText = patched.substring(start, start + objName.length);
2009
+ if (nodeText === objName && start <= ident.start && start > bestStart) {
2010
+ bestType = result.substitution.apply(type);
2011
+ bestStart = start;
2012
+ }
2013
+ }
2014
+ if (!bestType || bestType.tag !== 'TRecord')
2015
+ return [];
2016
+ const items = [];
2017
+ for (const [fieldName, fieldType] of Object.entries(bestType.fields)) {
2018
+ if (bestType.hiddenFields?.has(fieldName))
2019
+ continue;
2020
+ items.push({
2021
+ label: fieldName,
2022
+ kind: fieldType.tag === 'TFun' ? node_1.CompletionItemKind.Method : node_1.CompletionItemKind.Field,
2023
+ detail: `${fieldName} :: ${(0, types_1.prettyTypeToString)(fieldType)}`,
2024
+ labelDetails: { description: (0, types_1.prettyTypeToString)(fieldType) },
2025
+ });
2026
+ }
2027
+ return items;
2028
+ }
2029
+ // ---------------------------------------------------------------------------
2030
+ // Table-selector completion: PascalCase(["| or PascalCase([ "x", | ])
2031
+ // ---------------------------------------------------------------------------
2032
+ /**
2033
+ * When the cursor sits inside an array literal that is the argument of a
2034
+ * PascalCase call (e.g. `User([ | ])` from a query-builder `Table` factory), suggest
2035
+ * the literal-string selector members of the callee's parameter type.
2036
+ *
2037
+ * Resolves the callee's annotated overloads, picks any branch whose param is
2038
+ * `[Selector]`, expands `Selector` through type-aliases / unions and collects
2039
+ * every TLabel-lit value as a completion item. String selectors already
2040
+ * present in the literal are filtered out.
2041
+ */
2042
+ function getTableSelectorCompletions(source, offset, uri, ctx) {
2043
+ // Skip dot-completion contexts.
2044
+ if (offset > 0 && source[offset - 1] === '.')
2045
+ return [];
2046
+ // 1. Find the enclosing `[` at depth 0 (treating ()/{}/[] as containers).
2047
+ let depth = 0;
2048
+ let openBracketOffset = -1;
2049
+ for (let i = offset - 1; i >= 0; i--) {
2050
+ const ch = source[i];
2051
+ if (ch === ']' || ch === ')' || ch === '}')
2052
+ depth++;
2053
+ else if (ch === '[') {
2054
+ if (depth === 0) {
2055
+ openBracketOffset = i;
2056
+ break;
2057
+ }
2058
+ depth--;
2059
+ }
2060
+ else if (ch === '(' || ch === '{') {
2061
+ if (depth === 0)
2062
+ return [];
2063
+ depth--;
2064
+ }
2065
+ else if (ch === ';')
2066
+ return [];
2067
+ }
2068
+ if (openBracketOffset < 0)
2069
+ return [];
2070
+ // 2. The `[` must be directly preceded by `(` (modulo whitespace).
2071
+ let i = openBracketOffset - 1;
2072
+ while (i >= 0 && /\s/.test(source[i]))
2073
+ i--;
2074
+ if (i < 0 || source[i] !== '(')
2075
+ return [];
2076
+ // 3. Identifier directly before the `(`.
2077
+ let identEnd = i - 1;
2078
+ while (identEnd >= 0 && /\s/.test(source[identEnd]))
2079
+ identEnd--;
2080
+ const identInfo = (0, hover_1.scanWord)(source, identEnd + 1);
2081
+ if (!identInfo)
2082
+ return [];
2083
+ const calleeName = source.slice(identInfo.start, identEnd + 1);
2084
+ if (!calleeName || !/^[A-Z]/.test(calleeName))
2085
+ return [];
2086
+ // 4. Patch the array contents to spaces so inference doesn't choke on a
2087
+ // half-typed literal at the cursor.
2088
+ let closeBracketOffset = -1;
2089
+ let d = 1;
2090
+ for (let j = openBracketOffset + 1; j < source.length; j++) {
2091
+ const ch = source[j];
2092
+ if (ch === '[')
2093
+ d++;
2094
+ else if (ch === ']') {
2095
+ d--;
2096
+ if (d === 0) {
2097
+ closeBracketOffset = j;
2098
+ break;
2099
+ }
2100
+ }
2101
+ }
2102
+ const patchEnd = closeBracketOffset > 0 ? closeBracketOffset : source.indexOf('\n', offset);
2103
+ if (patchEnd < openBracketOffset + 1)
2104
+ return [];
2105
+ const patched = source.substring(0, openBracketOffset + 1)
2106
+ + ' '.repeat(patchEnd - openBracketOffset - 1)
2107
+ + source.substring(patchEnd);
2108
+ const result = runInference(patched, uri, ctx);
2109
+ // 5. Locate the callee's recorded type.
2110
+ let calleeType = null;
2111
+ for (const [start, { type, end }] of result.nodeTypes) {
2112
+ if (start === identInfo.start && end === identEnd + 1) {
2113
+ calleeType = result.substitution.apply(type);
2114
+ break;
2115
+ }
2116
+ }
2117
+ if (!calleeType) {
2118
+ // Fallback: any node starting at the identifier start.
2119
+ for (const [start, { type }] of result.nodeTypes) {
2120
+ if (start === identInfo.start) {
2121
+ calleeType = result.substitution.apply(type);
2122
+ break;
2123
+ }
2124
+ }
2125
+ }
2126
+ if (!calleeType)
2127
+ return [];
2128
+ // 6. Walk overload branches; collect param types of `[Selector]` shape.
2129
+ const selectorTypes = [];
2130
+ const collectArrayParam = (t) => {
2131
+ const r = result.substitution.apply(t);
2132
+ if (r.tag === 'TCon' && r.name === types_1.T_UNION) {
2133
+ for (const b of r.args)
2134
+ collectArrayParam(b);
2135
+ return;
2136
+ }
2137
+ if (r.tag === 'TFun') {
2138
+ const p = result.substitution.apply(r.param);
2139
+ if (p.tag === 'TCon' && p.name === types_1.T_ARRAY && p.args.length === 1) {
2140
+ selectorTypes.push(p.args[0]);
2141
+ }
2142
+ }
2143
+ };
2144
+ collectArrayParam(calleeType);
2145
+ if (selectorTypes.length === 0)
2146
+ return [];
2147
+ // 7. Expand selector types: follow alias TCon -> Union -> TLabel-lit leaves.
2148
+ const labels = new Set();
2149
+ const seen = new Set();
2150
+ const expand = (t) => {
2151
+ const r = result.substitution.apply(t);
2152
+ if (r.tag === 'TLabel' && r.kind === 'lit') {
2153
+ labels.add(r.value);
2154
+ return;
2155
+ }
2156
+ if (r.tag === 'TCon') {
2157
+ if (r.name === types_1.T_UNION) {
2158
+ for (const b of r.args)
2159
+ expand(b);
2160
+ return;
2161
+ }
2162
+ if (seen.has(r.name))
2163
+ return;
2164
+ seen.add(r.name);
2165
+ const alias = result.typeAliases.get(r.name);
2166
+ if (alias)
2167
+ expand(alias.type);
2168
+ }
2169
+ };
2170
+ for (const s of selectorTypes)
2171
+ expand(s);
2172
+ if (labels.size === 0)
2173
+ return [];
2174
+ // 8. Filter strings already present between `[` and the cursor.
2175
+ const present = new Set();
2176
+ const before = source.substring(openBracketOffset + 1, offset);
2177
+ const stringRe = /["']([^"'\\]*)["']/g;
2178
+ let sm;
2179
+ while ((sm = stringRe.exec(before)) !== null)
2180
+ present.add(sm[1]);
2181
+ // 9. Determine whether the cursor sits inside an unterminated quote.
2182
+ let inQuote = false;
2183
+ let quoteChar = '';
2184
+ for (let j = openBracketOffset + 1; j < offset; j++) {
2185
+ const ch = source[j];
2186
+ if (!inQuote && (ch === '"' || ch === "'")) {
2187
+ inQuote = true;
2188
+ quoteChar = ch;
2189
+ }
2190
+ else if (inQuote && ch === quoteChar && source[j - 1] !== '\\') {
2191
+ inQuote = false;
2192
+ }
2193
+ }
2194
+ const items = [];
2195
+ for (const lbl of labels) {
2196
+ if (present.has(lbl))
2197
+ continue;
2198
+ const insert = inQuote ? lbl : `"${lbl}"`;
2199
+ items.push({
2200
+ label: insert,
2201
+ kind: node_1.CompletionItemKind.Field,
2202
+ detail: `selector :: '${lbl}'`,
2203
+ filterText: lbl,
2204
+ insertText: insert,
2205
+ sortText: `0_${lbl}`,
2206
+ });
2207
+ }
2208
+ return items;
2209
+ }
2210
+ /**
2211
+ * Determine the type of the expression just before the dot, using fallback
2212
+ * strategies (re-parsing with patched source) when direct lookup fails.
2213
+ *
2214
+ * Plain language: when the user types `something.` the file is momentarily
2215
+ * broken JavaScript (the dot has nothing after it), so the type checker may
2216
+ * fail to produce a type for `something`. This function tries harder:
2217
+ * 1. First, run inference on the source as-is and look for a typed node
2218
+ * that ends exactly at the dot. Often this just works.
2219
+ * 2. If not, "patch" the source: blank out the dot and the half-typed
2220
+ * member name with spaces, so the file parses cleanly again, then run
2221
+ * inference on the patched copy and look up the expression's type at
2222
+ * the same position. Three patch flavours handle the receiver ending
2223
+ * in `)`/`]` (a call or index), a literal (`"`, `'`, `` ` ``, `/`),
2224
+ * or a plain identifier / dotted chain.
2225
+ */
2226
+ function resolveTypeBeforeDot(source, offset, dotIdx, uri, ctx) {
2227
+ // When the dot is on its own line (e.g. `arr\n.map`), scan backwards
2228
+ // past whitespace to collapse the newline.
2229
+ let effectiveSource = source;
2230
+ let effectiveDotIdx = dotIdx;
2231
+ let effectiveOffset = offset;
2232
+ {
2233
+ let exprEnd = dotIdx - 1;
2234
+ while (exprEnd >= 0 && /[\s]/.test(source[exprEnd]))
2235
+ exprEnd--;
2236
+ if (exprEnd >= 0 && exprEnd < dotIdx - 1) {
2237
+ const lastChar = source[exprEnd];
2238
+ if (/[A-Za-z0-9_$)\]'"`]/.test(lastChar)) {
2239
+ const gap = dotIdx - exprEnd - 1;
2240
+ effectiveSource = source.substring(0, exprEnd + 1) + source.substring(dotIdx);
2241
+ effectiveDotIdx = exprEnd + 1;
2242
+ effectiveOffset = offset - gap;
2243
+ }
2244
+ }
2245
+ }
2246
+ let result = ctx.engine.infer(effectiveSource, undefined, ctx.createImportResolver(uri), ctx.createTypeDirectiveResolver(uri), ctx.createImportTypeAliasResolver?.(uri));
2247
+ const objEnd = effectiveDotIdx;
2248
+ const objStart = (0, hover_1.scanWord)(effectiveSource, objEnd)?.start ?? objEnd;
2249
+ const objName = effectiveSource.slice(objStart, objEnd);
2250
+ let bestType = null;
2251
+ let rawBestType = null;
2252
+ let bestStart = -1;
2253
+ for (const [start, { type, end }] of result.nodeTypes) {
2254
+ // The receiver of `expr.member` must end exactly at the dot. Nodes
2255
+ // that extend past the dot are containers (the enclosing call, the
2256
+ // whole assignment, etc.) and accepting them would surface methods
2257
+ // for the wrong type — e.g. typing `orgs[0].` inside a `.map(...)`
2258
+ // callback would otherwise pick the outer `RTask` assignment.
2259
+ if (end !== effectiveDotIdx)
2260
+ continue;
2261
+ if (start > bestStart) {
2262
+ const resolved = result.substitution.apply(type);
2263
+ // Skip $error sentinels so the patched-source fallback cases below
2264
+ // get a chance to recover the real type (e.g. for `expr().` where
2265
+ // the trailing dot causes a parse/inference error on the assignment).
2266
+ if ((0, types_1.isErrorType)(resolved))
2267
+ continue;
2268
+ bestType = resolved;
2269
+ rawBestType = type;
2270
+ bestStart = start;
2271
+ }
2272
+ }
2273
+ if (!bestType) {
2274
+ const charBeforeDot = effectiveDotIdx > 0 ? effectiveSource[effectiveDotIdx - 1] : '';
2275
+ // Case 1: expression ending with ')' or ']' before the dot
2276
+ if (charBeforeDot === ')' || charBeforeDot === ']') {
2277
+ let patchEnd = effectiveOffset;
2278
+ while (patchEnd < effectiveSource.length && /[A-Za-z0-9_$]/.test(effectiveSource[patchEnd]))
2279
+ patchEnd++;
2280
+ const patchLen = patchEnd - effectiveDotIdx;
2281
+ const patched = effectiveSource.substring(0, effectiveDotIdx) + ' '.repeat(patchLen) + effectiveSource.substring(patchEnd);
2282
+ result = ctx.engine.infer(patched, undefined, ctx.createImportResolver(uri), ctx.createTypeDirectiveResolver(uri), ctx.createImportTypeAliasResolver?.(uri));
2283
+ const entry = result.nodeTypesByEnd.get(effectiveDotIdx);
2284
+ if (entry) {
2285
+ const resolved = result.substitution.apply(entry.type);
2286
+ if (resolved.tag === 'TCon' || resolved.tag === 'TRecord' || resolved.tag === 'TFun' || resolved.tag === 'TVar') {
2287
+ bestType = resolved;
2288
+ }
2289
+ }
2290
+ if (charBeforeDot === ']' && (!bestType || bestType.tag === 'TVar' || (bestType.tag === 'TCon' && bestType.name !== types_1.T_ARRAY))) {
2291
+ const patch = (0, files_1.patchArrayLiteralASI)(effectiveSource, effectiveDotIdx - 1);
2292
+ if (patch) {
2293
+ const patched2 = patch.patched.substring(0, effectiveDotIdx + patch.shift) + ' '.repeat(patchLen)
2294
+ + patch.patched.substring(patchEnd + patch.shift);
2295
+ const result2 = ctx.engine.infer(patched2, undefined, ctx.createImportResolver(uri), ctx.createTypeDirectiveResolver(uri), ctx.createImportTypeAliasResolver?.(uri));
2296
+ const entry2 = result2.nodeTypesByEnd.get(effectiveDotIdx + patch.shift);
2297
+ if (entry2) {
2298
+ const resolved2 = result2.substitution.apply(entry2.type);
2299
+ if (resolved2.tag === 'TCon' && resolved2.name === types_1.T_ARRAY) {
2300
+ bestType = resolved2;
2301
+ result = result2;
2302
+ }
2303
+ }
2304
+ }
2305
+ }
2306
+ }
2307
+ // Case 2: literal expression ending with ", ', ` or / before the dot
2308
+ if (!bestType) {
2309
+ const litChar = effectiveDotIdx > 0 ? effectiveSource[effectiveDotIdx - 1] : '';
2310
+ if (litChar === '"' || litChar === "'" || litChar === '`' || litChar === '/') {
2311
+ let patchEnd = effectiveOffset;
2312
+ while (patchEnd < effectiveSource.length && /[A-Za-z0-9_$]/.test(effectiveSource[patchEnd]))
2313
+ patchEnd++;
2314
+ const patchLen = patchEnd - effectiveDotIdx;
2315
+ const patched = effectiveSource.substring(0, effectiveDotIdx) + ' '.repeat(patchLen) + effectiveSource.substring(patchEnd);
2316
+ result = ctx.engine.infer(patched, undefined, ctx.createImportResolver(uri), ctx.createTypeDirectiveResolver(uri), ctx.createImportTypeAliasResolver?.(uri));
2317
+ const entry = result.nodeTypesByEnd.get(effectiveDotIdx);
2318
+ if (entry) {
2319
+ const resolved = result.substitution.apply(entry.type);
2320
+ if (resolved.tag === 'TCon' || resolved.tag === 'TRecord' || resolved.tag === 'TFun' || resolved.tag === 'TVar') {
2321
+ bestType = resolved;
2322
+ }
2323
+ }
2324
+ }
2325
+ }
2326
+ // Case 3: identifier before the dot
2327
+ if (!bestType) {
2328
+ const identEnd = effectiveDotIdx;
2329
+ const identStart = (0, hover_1.scanWord)(effectiveSource, identEnd)?.start ?? identEnd;
2330
+ const identName = effectiveSource.slice(identStart, identEnd);
2331
+ let chainStart = identStart;
2332
+ while (chainStart > 0 && effectiveSource[chainStart - 1] === '.') {
2333
+ chainStart--;
2334
+ chainStart = (0, hover_1.scanWord)(effectiveSource, chainStart)?.start ?? chainStart;
2335
+ }
2336
+ const isChain = chainStart < identStart;
2337
+ let patchEnd = effectiveOffset;
2338
+ while (patchEnd < effectiveSource.length && /[A-Za-z0-9_$]/.test(effectiveSource[patchEnd]))
2339
+ patchEnd++;
2340
+ const patchLen = patchEnd - effectiveDotIdx;
2341
+ const patched = effectiveSource.substring(0, effectiveDotIdx) + ' '.repeat(patchLen) + effectiveSource.substring(patchEnd);
2342
+ result = ctx.engine.infer(patched, undefined, ctx.createImportResolver(uri), ctx.createTypeDirectiveResolver(uri), ctx.createImportTypeAliasResolver?.(uri));
2343
+ if (isChain) {
2344
+ for (const [start, { type, end }] of result.nodeTypes) {
2345
+ if (start >= chainStart && end >= effectiveDotIdx - 1 && end <= effectiveDotIdx + 1) {
2346
+ const resolved = result.substitution.apply(type);
2347
+ if (resolved.tag === 'TCon' || resolved.tag === 'TRecord' || resolved.tag === 'TFun' || resolved.tag === 'TVar') {
2348
+ if (start > bestStart) {
2349
+ bestType = resolved;
2350
+ rawBestType = type;
2351
+ bestStart = start;
2352
+ }
2353
+ }
2354
+ }
2355
+ }
2356
+ }
2357
+ else if (identName) {
2358
+ for (const [start, { type, end }] of result.nodeTypes) {
2359
+ const resolved = result.substitution.apply(type);
2360
+ if (resolved.tag === 'TCon' || resolved.tag === 'TRecord' || resolved.tag === 'TFun' || resolved.tag === 'TVar') {
2361
+ const nodeText = patched.substring(start, start + identName.length);
2362
+ if (nodeText === identName && start <= identStart && start > bestStart) {
2363
+ bestType = resolved;
2364
+ rawBestType = type;
2365
+ bestStart = start;
2366
+ }
2367
+ }
2368
+ }
2369
+ }
2370
+ } // end case 3
2371
+ }
2372
+ if (!bestType)
2373
+ return null;
2374
+ return { bestType, rawBestType, result, objName, effectiveSource, objStart, objEnd };
2375
+ }
2376
+ /**
2377
+ * Provide completions after a dot: methods, fields, and constraint methods.
2378
+ *
2379
+ * Plain language: first figure out the type of the thing before the dot
2380
+ * (see `resolveTypeBeforeDot`), then branch on what kind of type it is:
2381
+ * - a type VARIABLE (unknown type) → only constraint methods we know it
2382
+ * must support (e.g. `Semigroup s` guarantees `.concat`);
2383
+ * - a NAMED type (`Array`, `Maybe`, a user class, …) → its registered
2384
+ * instance methods, record-alias fields, and — when the receiver is the
2385
+ * type name itself, like `Counter.` — its static methods too;
2386
+ * - a FUNCTION → static methods hung on the function object plus the
2387
+ * shared `Function` methods (`.call`, `.apply`, …);
2388
+ * - a RECORD (plain object) → its fields plus the standard
2389
+ * `Object.prototype` methods.
2390
+ */
2391
+ function getDotCompletions(source, offset, dotIdx, uri, ctx) {
2392
+ const resolved = resolveTypeBeforeDot(source, offset, dotIdx, uri, ctx);
2393
+ if (!resolved)
2394
+ return [];
2395
+ const { rawBestType, result, objName, effectiveSource, objStart, objEnd } = resolved;
2396
+ // The receiver type can carry rigid skolem constants (`§N`) when the dot is
2397
+ // inside an annotated method body whose params/`this` were skolemized so the
2398
+ // signature stays authoritative. Scrub them back to display letters so the
2399
+ // completion details (e.g. `Array#reduce :: [a] ~> (b -> a -> b) -> b -> b`)
2400
+ // never leak `§N`.
2401
+ const bestType = (result.skolemDisplayNames && (0, typeUtils_3.someType)(resolved.bestType, types_2.isSkolem))
2402
+ ? (0, typeUtils_3.scrubSkolems)(resolved.bestType, result.skolemDisplayNames)
2403
+ : resolved.bestType;
2404
+ const items = [];
2405
+ // Bare TVars no longer offer static constraint completions — use TypeRep.
2406
+ // However, for kind * constraints (e.g. Semigroup s), instance methods
2407
+ // should still be offered since the TVar represents a concrete value.
2408
+ if (bestType.tag === 'TVar') {
2409
+ const cNames = result.kvConstraints.get(bestType.id);
2410
+ if (cNames && cNames.length > 0) {
2411
+ // Collect instance methods from kind * constraints only
2412
+ const kindStarNames = cNames.filter(cn => {
2413
+ const baseName = (0, types_1.constraintBaseName)(cn);
2414
+ const def = (0, index_1.lookupConstraint)(baseName);
2415
+ return def?.expectedKind === '*';
2416
+ });
2417
+ if (kindStarNames.length > 0) {
2418
+ return buildInstanceConstraintCompletionItems(kindStarNames);
2419
+ }
2420
+ }
2421
+ return [];
2422
+ }
2423
+ if (bestType.tag === 'TCon') {
2424
+ // TypeRep: offer static constraint methods from the inner type's constraints
2425
+ if (bestType.name === types_1.T_TYPEREP && bestType.args.length === 1) {
2426
+ // Prefer the raw (pre-substitution) inner type to preserve kv info
2427
+ // that may have been resolved away during patched inference.
2428
+ const rawInner = rawBestType?.tag === 'TCon' && rawBestType.name === types_1.T_TYPEREP && rawBestType.args.length === 1
2429
+ ? rawBestType.args[0] : null;
2430
+ const innerType = rawInner ?? bestType.args[0];
2431
+ if (innerType.tag === 'TCon') {
2432
+ const innerKv = (0, types_1.parseKvName)(innerType.name);
2433
+ if (innerKv) {
2434
+ const allNames = (0, expressions_1.collectAllKvConstraintNames)(result.kvConstraints, result.kvConstructorConstraints, result.substitution, innerKv.varId, innerType.name);
2435
+ return buildStaticConstraintCompletionItems(allNames.length > 0 ? allNames : undefined);
2436
+ }
2437
+ // Concrete constructor representative (e.g. `TypeRep Array`):
2438
+ // the value IS the type constructor, so offer its registered static
2439
+ // methods (`Array.of`, `Array.from`, …) plus any static constraint
2440
+ // methods attached to the type.
2441
+ const staticItems = methodCompletionsForType(innerType.name, innerType.args, 'static');
2442
+ return staticItems;
2443
+ }
2444
+ if (innerType.tag === 'TVar') {
2445
+ const cNames = result.kvConstraints.get(innerType.id);
2446
+ const ctorCNames = result.kvConstructorConstraints.get(innerType.id);
2447
+ const allNames = [...new Set([...(cNames ?? []), ...(ctorCNames ?? [])])];
2448
+ return buildStaticConstraintCompletionItems(allNames.length > 0 ? allNames : undefined);
2449
+ }
2450
+ }
2451
+ const kv = (0, types_1.parseKvName)(bestType.name);
2452
+ if (kv) {
2453
+ const cNames = (0, expressions_1.resolveKvConstraintNames)(result.kvConstraints, result.substitution, kv.varId, bestType.name);
2454
+ // When the identifier before the dot is 'constructor', the user is
2455
+ // accessing the type constructor (e.g. this.run.constructor.of).
2456
+ // In that case only static methods (no `~>`) should be offered, even
2457
+ // though substitution may have resolved the TVar back to a kv TCon.
2458
+ if (objName === 'constructor') {
2459
+ const allCtorCNames = (0, expressions_1.collectAllKvConstraintNames)(result.kvConstraints, result.kvConstructorConstraints, result.substitution, kv.varId, bestType.name);
2460
+ return buildStaticConstraintCompletionItems(allCtorCNames.length > 0 ? allCtorCNames : undefined);
2461
+ }
2462
+ // For applied kind * constraints (e.g. Semigroup (s a)), the constraint
2463
+ // is stored in kvConstructorConstraints. Instance methods should still
2464
+ // be offered since the value has a concrete Semigroup-like type.
2465
+ const ctorCNames = (0, expressions_1.resolveKvConstraintNames)(result.kvConstructorConstraints, result.substitution, kv.varId, bestType.name);
2466
+ const allCNames = [...new Set([...(cNames ?? []), ...(ctorCNames ?? [])])];
2467
+ // Filter: only include kvConstructorConstraints entries that are kind *
2468
+ // (instance methods make sense). Kind * -> * entries are constructor-level only.
2469
+ const instanceNames = allCNames.filter(cn => {
2470
+ const baseName = (0, types_1.constraintBaseName)(cn);
2471
+ const def = (0, index_1.lookupConstraint)(baseName);
2472
+ // From kvConstraints → always include; from kvConstructorConstraints → only kind *
2473
+ if (cNames?.includes(cn))
2474
+ return true;
2475
+ return def?.expectedKind === '*';
2476
+ });
2477
+ return buildInstanceConstraintCompletionItems(instanceNames.length > 0 ? instanceNames : undefined);
2478
+ }
2479
+ else if (bestType.name === types_1.T_UNION) {
2480
+ // Variant union (e.g. `Just a | Nothing` from sumtype `.constructor`).
2481
+ // Offer the parent sumtype's static methods (`.of` etc.) when every
2482
+ // member is a variant of the same parent.
2483
+ const variantParents = bestType.args.map(a => a.tag === 'TCon' ? (0, dataTypeRegistry_1.getParentTypeName)(a.name) : null);
2484
+ const parent = variantParents[0];
2485
+ if (parent && variantParents.every(p => p === parent)) {
2486
+ const dt = (0, dataTypeRegistry_1.getDataType)(parent);
2487
+ const parentArgs = dt ? dt.decl.typeVars.map(() => ({ tag: 'TVar', id: -1, name: '_' })) : [];
2488
+ items.push(...methodCompletionsForType(parent, parentArgs, 'static'));
2489
+ // Only also offer instance methods when the dotted receiver is NOT
2490
+ // the sumtype identifier itself (e.g. `Either.` should show only
2491
+ // statics, while `ctorRef.` from `x.constructor` shows both).
2492
+ if (objName !== parent) {
2493
+ items.push(...methodCompletionsForType(parent, parentArgs, 'instance', (0, types_1.prettyTypeToString)(bestType)));
2494
+ }
2495
+ }
2496
+ }
2497
+ else {
2498
+ const alias = result.typeAliases.get(bestType.name);
2499
+ if (alias && alias.type.tag === 'TRecord') {
2500
+ for (const [fieldName, fieldType] of Object.entries(alias.type.fields)) {
2501
+ if (alias.type.hiddenFields?.has(fieldName))
2502
+ continue;
2503
+ items.push({
2504
+ label: fieldName,
2505
+ kind: fieldType.tag === 'TFun' ? node_1.CompletionItemKind.Method : node_1.CompletionItemKind.Field,
2506
+ detail: `${fieldName} :: ${(0, types_1.prettyTypeToString)(fieldType)}`,
2507
+ labelDetails: { description: (0, types_1.prettyTypeToString)(fieldType) },
2508
+ });
2509
+ }
2510
+ }
2511
+ items.push(...methodCompletionsForType(bestType.name, bestType.args, 'instance', (0, types_1.prettyTypeToString)(bestType), objName === 'this'));
2512
+ // When the identifier before the dot *is* the class name itself
2513
+ // (e.g. typing `Counter.` rather than `instance.`), also offer the
2514
+ // class's static methods and properties. Class declarations bind
2515
+ // the class symbol to a value of TCon `<ClassName>` so the only
2516
+ // signal we have here is that the textual identifier matches the
2517
+ // type-constructor name.
2518
+ if (objName && objName === bestType.name) {
2519
+ items.push(...methodCompletionsForType(bestType.name, bestType.args, 'static'));
2520
+ }
2521
+ }
2522
+ }
2523
+ if (bestType.tag === 'TFun') {
2524
+ // Look up user-defined static methods on the identifier (e.g. Identity.of).
2525
+ const identName = effectiveSource.slice(objStart, objEnd);
2526
+ if (identName) {
2527
+ items.push(...methodCompletionsForType(identName, [], 'static'));
2528
+ }
2529
+ // When the function type is a constructor (returns a concrete TCon),
2530
+ // also offer static methods from that type. This covers cases like
2531
+ // `building.constructor.create` where the constructor function type
2532
+ // is `(String, Number) -> Building` and `Building.create` is static.
2533
+ const retType = (0, types_1.getReturnType)(bestType);
2534
+ if (retType.tag === 'TCon' && retType.name !== identName) {
2535
+ items.push(...methodCompletionsForType(retType.name, retType.args, 'static'));
2536
+ }
2537
+ items.push(...methodCompletionsForType('Function', [], 'instance', 'Function'));
2538
+ }
2539
+ if (bestType.tag === 'TRecord') {
2540
+ for (const [fieldName, fieldType] of Object.entries(bestType.fields)) {
2541
+ if (bestType.hiddenFields?.has(fieldName))
2542
+ continue;
2543
+ items.push({
2544
+ label: fieldName,
2545
+ kind: fieldType.tag === 'TFun' ? node_1.CompletionItemKind.Method : node_1.CompletionItemKind.Field,
2546
+ detail: `${fieldName} :: ${(0, types_1.prettyTypeToString)(fieldType)}`,
2547
+ labelDetails: { description: (0, types_1.prettyTypeToString)(fieldType) },
2548
+ });
2549
+ }
2550
+ for (const name of expressions_2.OBJECT_PROTOTYPE_METHOD_NAMES) {
2551
+ if (items.some(i => i.label === name))
2552
+ continue;
2553
+ const t = (0, expressions_2.objectPrototypeMethodType)(name);
2554
+ if (!t)
2555
+ continue;
2556
+ items.push({
2557
+ label: name,
2558
+ kind: node_1.CompletionItemKind.Method,
2559
+ detail: `${name} :: ${(0, types_1.prettyTypeToString)(t)}`,
2560
+ labelDetails: { description: (0, types_1.prettyTypeToString)(t) },
2561
+ });
2562
+ }
2563
+ }
2564
+ return items;
2565
+ }
2566
+ // ---------------------------------------------------------------------------
2567
+ // Annotation type completion — type names inside `// name :: |` comments
2568
+ // ---------------------------------------------------------------------------
2569
+ /** Built-in type names offered in annotation completions. */
2570
+ const ANNOTATION_TYPE_NAMES = [
2571
+ { name: 'Number', detail: 'Type' },
2572
+ { name: 'String', detail: 'Type' },
2573
+ { name: 'Boolean', detail: 'Type' },
2574
+ { name: 'Array', detail: 'Type' },
2575
+ { name: 'Object', detail: 'Type' },
2576
+ { name: 'Null', detail: 'Type' },
2577
+ { name: 'Undefined', detail: 'Type' },
2578
+ { name: 'Void', detail: 'Type' },
2579
+ { name: 'Any', detail: 'Type' },
2580
+ { name: 'Integer', detail: 'Type' },
2581
+ { name: 'Float', detail: 'Type' },
2582
+ { name: 'Double', detail: 'Type' },
2583
+ { name: 'NonNegativeInteger', detail: 'Type' },
2584
+ { name: 'NegativeInteger', detail: 'Type' },
2585
+ { name: 'PositiveNumber', detail: 'Type' },
2586
+ { name: 'NegativeNumber', detail: 'Type' },
2587
+ { name: 'ValidNumber', detail: 'Type' },
2588
+ { name: 'NonZeroValidNumber', detail: 'Type' },
2589
+ { name: 'FiniteNumber', detail: 'Type' },
2590
+ { name: 'NonZeroFiniteNumber', detail: 'Type' },
2591
+ { name: 'PositiveFiniteNumber', detail: 'Type' },
2592
+ { name: 'NegativeFiniteNumber', detail: 'Type' },
2593
+ { name: 'NonZeroInteger', detail: 'Type' },
2594
+ { name: 'PositiveInteger', detail: 'Type' },
2595
+ { name: 'StrMap', detail: 'Type' },
2596
+ { name: 'Buffer', detail: 'Type' },
2597
+ { name: 'Process', detail: 'Type' },
2598
+ { name: 'Promise', detail: 'Type' },
2599
+ { name: 'Map', detail: 'Type' },
2600
+ { name: 'Set', detail: 'Type' },
2601
+ { name: 'Error', detail: 'Type' },
2602
+ { name: 'RegExp', detail: 'Type' },
2603
+ { name: 'Date', detail: 'Type' },
2604
+ { name: 'Symbol', detail: 'Type' },
2605
+ { name: 'BigInt', detail: 'Type' },
2606
+ { name: 'TypeRep', detail: 'Type — type representative' },
2607
+ { name: 'Maybe', detail: 'Type — Maybe a' },
2608
+ { name: 'Either', detail: 'Type — Either a b' },
2609
+ ];
2610
+ // ---------------------------------------------------------------------------
2611
+ // Directive keyword completion — `// ::|` triggers directive suggestions
2612
+ // ---------------------------------------------------------------------------
2613
+ const DIRECTIVE_KEYWORDS = [
2614
+ { label: 'types', detail: '::types — load types from another file', snippet: 'types ./$1' },
2615
+ { label: 'constraint', detail: '::constraint — define a type class', snippet: 'constraint $1 $2 { $3 }' },
2616
+ { label: 'global', detail: '::global — declare a method on a built-in type', snippet: 'global $1#$2 :: $3' },
2617
+ { label: 'narrow', detail: '::narrow — narrow a predicate return type', snippet: 'narrow $1' },
2618
+ { label: 'extend', detail: '::extend — append a branch to an existing union alias', snippet: 'extend ${1:AliasName} ${2:Branch}' },
2619
+ { label: 'prefer', detail: '::prefer — pick a definition when a name is ambiguous', snippet: 'prefer ${1:Name} from ${2:source}' },
2620
+ { label: 'rep', detail: '::rep — bind a local annotation as a constraint method representative' },
2621
+ { label: 'ignore', detail: '::ignore — suppress diagnostics on next line' },
2622
+ { label: 'ignore-file', detail: '::ignore-file — suppress all diagnostics in file' },
2623
+ { label: 'ignore-function', detail: '::ignore-function — suppress diagnostics in next function' },
2624
+ { label: 'hidden', detail: '::hidden — hide the following member/field from completion' },
2625
+ { label: 'private', detail: '::private — mark the following member/field as private (implies hidden)' },
2626
+ ];
2627
+ /**
2628
+ * Offer directive keyword completions when the cursor is right after `::` in a
2629
+ * comment and the user is typing a directive name (e.g. `// ::i|` → ignore).
2630
+ */
2631
+ function getDirectiveCompletions(source, offset) {
2632
+ if (!(0, hover_1.isOffsetInComment)(source, offset))
2633
+ return [];
2634
+ const lineStart = source.lastIndexOf('\n', offset - 1) + 1;
2635
+ const lineBefore = source.slice(lineStart, offset);
2636
+ // Match `// ::` optionally followed by a partial directive name.
2637
+ const m = /\/\/\s*::([a-z-]*)$/.exec(lineBefore);
2638
+ if (!m)
2639
+ return [];
2640
+ const partial = m[1]; // may be '' when cursor is right after '::'
2641
+ const items = [];
2642
+ for (const kw of DIRECTIVE_KEYWORDS) {
2643
+ if (partial && !kw.label.startsWith(partial))
2644
+ continue;
2645
+ items.push({
2646
+ label: `::${kw.label}`,
2647
+ kind: node_1.CompletionItemKind.Keyword,
2648
+ detail: kw.detail,
2649
+ sortText: `0_${kw.label}`,
2650
+ filterText: `::${kw.label}`,
2651
+ insertText: kw.snippet ?? kw.label,
2652
+ insertTextFormat: kw.snippet ? 2 : undefined, // 2 = Snippet
2653
+ });
2654
+ }
2655
+ return items;
2656
+ }
2657
+ /**
2658
+ * Offer type constructor names when the cursor is inside an annotation comment.
2659
+ * Returns non-empty array when applicable, empty array otherwise.
2660
+ */
2661
+ function getAnnotationTypeCompletions(source, offset, uri, ctx) {
2662
+ if (!(0, hover_1.isOffsetInComment)(source, offset))
2663
+ return [];
2664
+ // Only complete if we're inside an annotation-like comment (has `::` or starts with `@`)
2665
+ const lineStart = source.lastIndexOf('\n', offset - 1) + 1;
2666
+ const lineBefore = source.slice(lineStart, offset);
2667
+ if (!/::|::constraint|::narrow/.test(lineBefore))
2668
+ return [];
2669
+ const wordInfo = (0, hover_1.scanWord)(source, offset);
2670
+ const partial = wordInfo ? source.slice(wordInfo.start, offset) : '';
2671
+ const items = [];
2672
+ const addedNames = new Set();
2673
+ const addItem = (name, detail) => {
2674
+ if (addedNames.has(name))
2675
+ return;
2676
+ if (partial && !name.startsWith(partial))
2677
+ return;
2678
+ addedNames.add(name);
2679
+ items.push({
2680
+ label: name,
2681
+ // Use Class (not TypeParameter) so VS Code shows these even when
2682
+ // `editor.suggest.showTypeParameters` is false (TypeParameter is
2683
+ // intended for generic params like `T`, not concrete type names).
2684
+ kind: node_1.CompletionItemKind.Class,
2685
+ detail,
2686
+ sortText: `0_${name}`,
2687
+ });
2688
+ };
2689
+ // Built-in types
2690
+ for (const entry of ANNOTATION_TYPE_NAMES) {
2691
+ addItem(entry.name, entry.detail);
2692
+ }
2693
+ // Types from current file inference (type aliases, sumtypes, constructor annotations)
2694
+ const result = runInference(source, uri, ctx);
2695
+ for (const [name] of result.typeAliases) {
2696
+ addItem(name, 'Type alias');
2697
+ }
2698
+ for (const name of (0, dataTypeRegistry_1.getDataTypeNames)()) {
2699
+ addItem(name, 'sum type');
2700
+ }
2701
+ for (const name of (0, index_1.getConstraintNames)()) {
2702
+ addItem(name, '::constraint');
2703
+ }
2704
+ for (const name of (0, methodRegistry_1.getRegisteredTypeNames)()) {
2705
+ addItem(name, 'Type');
2706
+ }
2707
+ return items;
2708
+ }
2709
+ /**
2710
+ * Offer JS binding names when the cursor is inside a comment line that
2711
+ * does not yet contain `::` — typical when the user is starting to write
2712
+ * an annotation for a binding they've already defined in JS:
2713
+ *
2714
+ * const myFunc = (x) => x + 1;
2715
+ * // myF| ← suggest `myFunc`
2716
+ *
2717
+ * Only top-level bindings that don't already have an annotation are
2718
+ * offered, so existing annotations aren't duplicated.
2719
+ */
2720
+ function getAnnotationNameCompletions(source, offset, uri, ctx) {
2721
+ if (!(0, hover_1.isOffsetInComment)(source, offset))
2722
+ return [];
2723
+ const lineStart = source.lastIndexOf('\n', offset - 1) + 1;
2724
+ const lineBefore = source.slice(lineStart, offset);
2725
+ // Match a `//` (or `/*`/`*`) comment line that has only an optional
2726
+ // partial word before the cursor. Stop here if `::` is already present
2727
+ // — that's the type-name completion territory.
2728
+ if (lineBefore.includes('::'))
2729
+ return [];
2730
+ // Accept an optional dotted partial like `builtIn.Obj` so member-access
2731
+ // annotation names (e.g. `builtIn.Object`) can be filtered as the user
2732
+ // continues typing past the dot.
2733
+ const m = /^\s*(?:\/\/+|\/\*+|\*+)\s*([A-Za-z_$][\w$]*(?:\.[\w$]*)?)?$/.exec(lineBefore);
2734
+ if (!m)
2735
+ return [];
2736
+ const partial = m[1] ?? '';
2737
+ const result = runInference(source, uri, ctx);
2738
+ // Names that already have a `Name :: ...` annotation — skip them so the
2739
+ // user isn't offered duplicates. Track bare and dotted names separately;
2740
+ // method (`Type#method`) entries never collide with these.
2741
+ const annotated = new Set();
2742
+ for (const name of result.annotations.keys()) {
2743
+ if (name.includes('#'))
2744
+ continue;
2745
+ annotated.add(name);
2746
+ }
2747
+ const items = [];
2748
+ const seen = new Set();
2749
+ for (const [name] of result.topLevelBindings) {
2750
+ if (annotated.has(name))
2751
+ continue;
2752
+ if (partial && !name.startsWith(partial))
2753
+ continue;
2754
+ if (seen.has(name))
2755
+ continue;
2756
+ seen.add(name);
2757
+ items.push({
2758
+ label: name,
2759
+ kind: node_1.CompletionItemKind.Variable,
2760
+ detail: 'Annotate this binding',
2761
+ sortText: `0_${name}`,
2762
+ // Insert `Name :: ` so the user can immediately type the type.
2763
+ insertText: `${name} :: `,
2764
+ });
2765
+ }
2766
+ // Also offer member-assignment targets like `builtIn.Object` when the
2767
+ // source contains `builtIn.Object = ...`. Without this the user can
2768
+ // only accept the bare `builtIn` suggestion, which inserts `builtIn :: `
2769
+ // and leaves them having to manually move the cursor back to append the
2770
+ // member name.
2771
+ const memberAssignRegex = /^[ \t]*([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)\s*=(?!=)/gm;
2772
+ let am;
2773
+ while ((am = memberAssignRegex.exec(source)) !== null) {
2774
+ if ((0, hover_1.isOffsetInComment)(source, am.index))
2775
+ continue;
2776
+ const full = `${am[1]}.${am[2]}`;
2777
+ if (annotated.has(full))
2778
+ continue;
2779
+ if (seen.has(full))
2780
+ continue;
2781
+ if (partial && !full.startsWith(partial))
2782
+ continue;
2783
+ seen.add(full);
2784
+ items.push({
2785
+ label: full,
2786
+ kind: node_1.CompletionItemKind.Variable,
2787
+ detail: 'Annotate this member assignment',
2788
+ sortText: `0_${full}`,
2789
+ insertText: `${full} :: `,
2790
+ });
2791
+ }
2792
+ return items;
2793
+ }
2794
+ //# sourceMappingURL=completion.js.map