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,1285 @@
1
+ "use strict";
2
+ // ============================================================================
3
+ // Type Signature Parser — parses HM type notation from comments
4
+ //
5
+ // WHAT THIS FILE DOES (in plain language)
6
+ // ---------------------------------------------------------------------------
7
+ // Users write type notes as text, e.g. `Number -> String`. This file reads
8
+ // that text and turns it into the in-memory building blocks from types.ts.
9
+ // It works like reading a sentence in two steps:
10
+ // 1. The *tokenizer* chops the text into words and symbols (tokens):
11
+ // "Array", "->", "(", "a", ...
12
+ // 2. The *parser* fits those tokens together according to the grammar of
13
+ // the type language (arrows are right-associative, `|` binds tighter
14
+ // than `->`, brackets mean arrays, braces mean records, ...).
15
+ // The result is a Type tree — or a TypeParseError pointing at the exact spot
16
+ // where the text stopped making sense.
17
+ //
18
+ // Supported syntax examples:
19
+ // // :: Number -> String -> Boolean
20
+ // // :: a -> b -> a
21
+ // // :: [Number] -> Number
22
+ // // :: (Number -> String) -> [String]
23
+ // // :: Array<Number> -> Number (also supported)
24
+ // /* :: Number -> Number */
25
+ // ============================================================================
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.TypeParseError = void 0;
28
+ exports.parseTypeSignature = parseTypeSignature;
29
+ exports.parseType = parseType;
30
+ exports.parseMethodTypeSignature = parseMethodTypeSignature;
31
+ const types_1 = require("./types");
32
+ /** Matches uppercase-leading identifiers (type constructors). */
33
+ const UPPERCASE_RE = /^[A-Z]/;
34
+ /** Matches lowercase-leading identifiers (type variables). */
35
+ const LOWERCASE_RE = /^[a-z]/;
36
+ /** Single-character token lookup — hoisted to module scope. */
37
+ const SINGLE_CHARS = {
38
+ '(': 'LPAREN', ')': 'RPAREN',
39
+ '<': 'LANGLE', '>': 'RANGLE',
40
+ '[': 'LBRACKET', ']': 'RBRACKET',
41
+ '{': 'LBRACE', '}': 'RBRACE',
42
+ ',': 'COMMA', '.': 'DOT',
43
+ '|': 'PIPE', ':': 'COLON',
44
+ '*': 'STAR',
45
+ };
46
+ function tokenize(input) {
47
+ const tokens = [];
48
+ let i = 0;
49
+ while (i < input.length) {
50
+ // Skip whitespace
51
+ if (/\s/.test(input[i])) {
52
+ i++;
53
+ continue;
54
+ }
55
+ // Arrow ->
56
+ if (input[i] === '-' && input[i + 1] === '>') {
57
+ tokens.push({ kind: 'ARROW', value: '->' });
58
+ i += 2;
59
+ continue;
60
+ }
61
+ // Fat arrow =>
62
+ if (input[i] === '=' && input[i + 1] === '>') {
63
+ tokens.push({ kind: 'FAT_ARROW', value: '=>' });
64
+ i += 2;
65
+ continue;
66
+ }
67
+ // Squiggly arrow ~>
68
+ if (input[i] === '~' && input[i + 1] === '>') {
69
+ tokens.push({ kind: 'SQUIGGLY', value: '~>' });
70
+ i += 2;
71
+ continue;
72
+ }
73
+ // Ellipsis ...
74
+ if (input[i] === '.' && i + 2 < input.length && input[i + 1] === '.' && input[i + 2] === '.') {
75
+ tokens.push({ kind: 'ELLIPSIS', value: '...' });
76
+ i += 3;
77
+ continue;
78
+ }
79
+ // Single chars
80
+ if (SINGLE_CHARS[input[i]]) {
81
+ tokens.push({ kind: SINGLE_CHARS[input[i]], value: input[i] });
82
+ i++;
83
+ continue;
84
+ }
85
+ // Identifier: optional `@@` or `@` prefix (Fantasy-Land / Symbol-style
86
+ // keys, e.g. `@@type`, `@iterator`), then [A-Za-z_][A-Za-z0-9_]*.
87
+ {
88
+ let p = i;
89
+ if (input[p] === '@') {
90
+ p++;
91
+ if (input[p] === '@')
92
+ p++;
93
+ }
94
+ if (p > i && /[A-Za-z_]/.test(input[p])) {
95
+ const start = i;
96
+ i = p;
97
+ while (i < input.length && /[A-Za-z0-9_]/.test(input[i]))
98
+ i++;
99
+ tokens.push({ kind: 'IDENT', value: input.slice(start, i) });
100
+ continue;
101
+ }
102
+ }
103
+ if (/[A-Za-z_]/.test(input[i])) {
104
+ let start = i;
105
+ while (i < input.length && /[A-Za-z0-9_]/.test(input[i]))
106
+ i++;
107
+ tokens.push({ kind: 'IDENT', value: input.slice(start, i) });
108
+ continue;
109
+ }
110
+ // Number literal: digits with optional decimal point
111
+ if (/[0-9]/.test(input[i]) || (input[i] === '-' && i + 1 < input.length && /[0-9]/.test(input[i + 1]))) {
112
+ let start = i;
113
+ if (input[i] === '-')
114
+ i++;
115
+ while (i < input.length && /[0-9]/.test(input[i]))
116
+ i++;
117
+ if (i < input.length && input[i] === '.' && i + 1 < input.length && /[0-9]/.test(input[i + 1])) {
118
+ i++; // consume .
119
+ while (i < input.length && /[0-9]/.test(input[i]))
120
+ i++;
121
+ }
122
+ tokens.push({ kind: 'NUMBER', value: input.slice(start, i) });
123
+ continue;
124
+ }
125
+ // String literal: "..." or '...'
126
+ if (input[i] === '"' || input[i] === "'") {
127
+ const quote = input[i];
128
+ let start = i;
129
+ i++; // consume opening quote
130
+ while (i < input.length && input[i] !== quote)
131
+ i++;
132
+ i++; // consume closing quote
133
+ tokens.push({ kind: 'STRING', value: input.slice(start, i) });
134
+ continue;
135
+ }
136
+ // Unknown char — skip
137
+ i++;
138
+ }
139
+ tokens.push({ kind: 'EOF', value: '' });
140
+ return tokens;
141
+ }
142
+ // ---------------------------------------------------------------------------
143
+ // Parser
144
+ // ---------------------------------------------------------------------------
145
+ class TypeParseError extends Error {
146
+ constructor(message) {
147
+ // Thrown and caught routinely while probing annotation shapes; skip the
148
+ // stack trace unless debugging hinmil itself (`HM_DEBUG=1`).
149
+ const limit = Error.stackTraceLimit;
150
+ if (!(typeof process !== 'undefined' && process.env?.HM_DEBUG))
151
+ Error.stackTraceLimit = 0;
152
+ super(message);
153
+ Error.stackTraceLimit = limit;
154
+ this.name = 'TypeParseError';
155
+ }
156
+ }
157
+ exports.TypeParseError = TypeParseError;
158
+ class TypeParser {
159
+ constructor(tokens) {
160
+ /** When true, lowercase identifiers are never resolved to record label
161
+ * variables — used while parsing a constraint head (`Array k =>`) where a
162
+ * lowercase ident is always a constraint type variable, even if the same
163
+ * name also appears as a `[k]` record label elsewhere in the signature. */
164
+ this.suppressLabelVars = false;
165
+ /** Set when at least one nested `forall` quantifier was parsed — cached on
166
+ * the resulting Scheme as `hasForall` so hot inference paths can gate all
167
+ * rank-N handling behind one boolean. */
168
+ this.sawForall = false;
169
+ this.tokens = tokens;
170
+ this.pos = 0;
171
+ this.varMap = new Map();
172
+ this.labelVarMap = new Map();
173
+ this.constraintVarNames = new Set();
174
+ this.typeArities = new Map();
175
+ // Pre-scan tokens for `[name] :: …` bracketed-key patterns inside
176
+ // record types so that any appearance of `name` as a top-level
177
+ // identifier elsewhere in the signature (e.g.
178
+ // `k -> { [k] :: a, ...r } -> { ...r }`) parses as a label
179
+ // variable rather than a type variable. We require the trailing
180
+ // `::` to avoid catching ordinary array shorthand `[a]`.
181
+ for (let i = 0; i < tokens.length - 4; i++) {
182
+ if (tokens[i].kind === 'LBRACKET' &&
183
+ tokens[i + 1].kind === 'IDENT' &&
184
+ LOWERCASE_RE.test(tokens[i + 1].value) &&
185
+ tokens[i + 2].kind === 'RBRACKET' &&
186
+ tokens[i + 3].kind === 'COLON' &&
187
+ tokens[i + 4].kind === 'COLON') {
188
+ const name = tokens[i + 1].value;
189
+ if (!this.labelVarMap.has(name)) {
190
+ this.labelVarMap.set(name, (0, types_1.tLabelVar)(name));
191
+ }
192
+ }
193
+ }
194
+ }
195
+ peek() {
196
+ return this.tokens[this.pos];
197
+ }
198
+ advance() {
199
+ return this.tokens[this.pos++];
200
+ }
201
+ expect(kind) {
202
+ const tok = this.peek();
203
+ if (tok.kind !== kind) {
204
+ throw new TypeParseError(`Expected ${kind} but got ${tok.kind} ("${tok.value}")`);
205
+ }
206
+ return this.advance();
207
+ }
208
+ // -----------------------------------------------------------------------
209
+ // Top-level: parse constraints + type, auto-quantify free vars
210
+ // Also handles constraints: "Functor f => ..." or "(Functor f, Monad m) => ..."
211
+ // -----------------------------------------------------------------------
212
+ parseScheme() {
213
+ // Try parsing constraints: Functor f => ... or (Functor f, Monad m) => ...
214
+ const constraints = this.tryParseConstraints();
215
+ // Parse the type (free vars will be auto-quantified)
216
+ let type = this.normalizeObjectKeys(this.parseType());
217
+ // Collect all variable ids that appeared. Label-vars share the same
218
+ // id-space as ordinary type variables and must also be quantified so
219
+ // that each instantiation produces a fresh label var.
220
+ const vars = Array.from(this.varMap.values());
221
+ for (const lbl of this.labelVarMap.values()) {
222
+ if (lbl.kind === 'var' && !vars.includes(lbl.id))
223
+ vars.push(lbl.id);
224
+ }
225
+ if (this.sawForall) {
226
+ // Prenex normalization: quantifiers at the top level and in RESULT
227
+ // positions are semantically identical to scheme-level quantification
228
+ // (the CALLER still chooses the instantiation), so absorb them into
229
+ // the scheme. Only contravariant (parameter / record-field) foralls
230
+ // remain as nested TForall nodes — those are the genuine rank-N spots.
231
+ const allConstraints = constraints.slice();
232
+ type = this.hoistCovariantForalls(type, vars, allConstraints);
233
+ this.validateForallPositions(type, false);
234
+ const out = {
235
+ vars, type,
236
+ constraints: allConstraints.length > 0 ? allConstraints : undefined,
237
+ };
238
+ // The hoist may have absorbed every quantifier — only flag schemes
239
+ // that still carry a nested TForall.
240
+ if ((0, types_1.containsForall)(type))
241
+ out.hasForall = true;
242
+ return out;
243
+ }
244
+ return { vars, type, constraints: constraints.length > 0 ? constraints : undefined };
245
+ }
246
+ /** Absorb `forall`s at the top level and in (nested) result positions into
247
+ * the enclosing scheme: their vars join `intoVars` and their constraints
248
+ * join `intoConstraints`. Returns the stripped type. */
249
+ hoistCovariantForalls(t, intoVars, intoConstraints) {
250
+ while (t.tag === 'TForall') {
251
+ for (const v of t.vars)
252
+ if (!intoVars.includes(v))
253
+ intoVars.push(v);
254
+ if (t.constraints)
255
+ intoConstraints.push(...t.constraints);
256
+ t = t.body;
257
+ }
258
+ if (t.tag === 'TFun') {
259
+ const result = this.hoistCovariantForalls(t.result, intoVars, intoConstraints);
260
+ if (result !== t.result)
261
+ return (0, types_1.tFun)(t.param, result);
262
+ }
263
+ return t;
264
+ }
265
+ /** Predicativity check: a nested `forall` may appear as a function
266
+ * parameter (directly, or as a tuple-slot of a multi-param function) or as
267
+ * a record field value — never inside type-constructor arguments
268
+ * (`[forall a. …]`, `Either (forall a. …) b`, union members, …). */
269
+ validateForallPositions(t, allowHere) {
270
+ switch (t.tag) {
271
+ case 'TForall':
272
+ if (!allowHere) {
273
+ throw new TypeParseError(`'forall' is only allowed as a function parameter or record field type — not inside type-constructor arguments`);
274
+ }
275
+ this.validateForallPositions(t.body, false);
276
+ return;
277
+ case 'TFun': {
278
+ const p = t.param;
279
+ if (p.tag === 'TCon' && p.name === types_1.T_TUPLE) {
280
+ for (const a of p.args)
281
+ this.validateForallPositions(a, true);
282
+ }
283
+ else {
284
+ this.validateForallPositions(p, true);
285
+ }
286
+ this.validateForallPositions(t.result, false);
287
+ return;
288
+ }
289
+ case 'TCon':
290
+ for (const a of t.args)
291
+ this.validateForallPositions(a, false);
292
+ return;
293
+ case 'TRecord':
294
+ for (const k in t.fields)
295
+ this.validateForallPositions(t.fields[k], true);
296
+ if (t.labelFields)
297
+ for (const lf of t.labelFields)
298
+ this.validateForallPositions(lf.type, true);
299
+ return;
300
+ default:
301
+ return;
302
+ }
303
+ }
304
+ /**
305
+ * Post-parse rewrite: the first child of an applied `Object k a` is the
306
+ * record *key* and must be a label variable, but juxtaposition parses a
307
+ * bare lowercase `k` as an ordinary type variable. Convert any such key
308
+ * to a label variable (reusing the existing id so quantification stays
309
+ * consistent, or the shared label from {@link labelVarMap} when the same
310
+ * name also appears as a `[k] ::` field elsewhere — so `Object k a` and
311
+ * `{ [k] :: a }` reference the same key).
312
+ */
313
+ normalizeObjectKeys(t) {
314
+ switch (t.tag) {
315
+ case 'TCon': {
316
+ const args = t.args.map(a => this.normalizeObjectKeys(a));
317
+ if (t.name === 'Object' && args.length === 2 && args[0].tag === 'TVar') {
318
+ const v = args[0];
319
+ let label = this.labelVarMap.get(v.name);
320
+ if (!label || label.kind !== 'var') {
321
+ label = { tag: 'TLabel', kind: 'var', id: v.id, name: v.name };
322
+ this.labelVarMap.set(v.name, label);
323
+ // The id (kept in varMap) now denotes a label var; instantiation
324
+ // detects label-ness from the type structure, so leaving the id in
325
+ // varMap simply keeps it quantified — correct for a standalone
326
+ // `Object k a` whose key appears nowhere else.
327
+ }
328
+ return { ...t, args: [label, args[1]] };
329
+ }
330
+ return { ...t, args };
331
+ }
332
+ case 'TFun':
333
+ return (0, types_1.tFun)(this.normalizeObjectKeys(t.param), this.normalizeObjectKeys(t.result));
334
+ case 'TRecord': {
335
+ const fields = {};
336
+ for (const k in t.fields)
337
+ fields[k] = this.normalizeObjectKeys(t.fields[k]);
338
+ const rec = { ...t, fields };
339
+ if (t.labelFields) {
340
+ rec.labelFields = t.labelFields.map(lf => ({ label: lf.label, type: this.normalizeObjectKeys(lf.type) }));
341
+ }
342
+ return rec;
343
+ }
344
+ case 'TForall':
345
+ return { ...t, body: this.normalizeObjectKeys(t.body) };
346
+ default:
347
+ return t;
348
+ }
349
+ }
350
+ // -----------------------------------------------------------------------
351
+ // Constraint parsing: "Functor f =>" or "(Functor f, Monad m) =>"
352
+ // -----------------------------------------------------------------------
353
+ tryParseConstraints() {
354
+ // We need to look ahead to see if there's a `=>` pattern.
355
+ // Three forms:
356
+ // 1. ClassName varName =>
357
+ // 2. (ClassName varName, ClassName varName, ...) =>
358
+ // 3. (T1 | T2 | ...) varName => (structural-union constraint)
359
+ const savedPos = this.pos;
360
+ const savedVarMap = new Map(this.varMap);
361
+ const savedConstraintVarNames = new Set(this.constraintVarNames);
362
+ // Constraint-head atoms are parsed with label-variable resolution
363
+ // suppressed: a lowercase ident in a constraint head (`Array k =>`) is
364
+ // always a constraint type variable, never a `[k]` record label — even
365
+ // when the same name also appears as `[k]` later in the signature.
366
+ const savedSuppress = this.suppressLabelVars;
367
+ this.suppressLabelVars = true;
368
+ try {
369
+ // Try form 3 first: (T1 | T2 | ...) v =>
370
+ // We attempt to parse a parenthesised type containing at least one
371
+ // top-level `|`, followed by a lowercase ident, followed by `=>`.
372
+ if (this.peek().kind === 'LPAREN') {
373
+ try {
374
+ this.advance(); // consume (
375
+ const parsedType = this.parseType();
376
+ if (parsedType.tag === 'TCon' &&
377
+ parsedType.name === types_1.T_UNION &&
378
+ this.peek().kind === 'RPAREN') {
379
+ this.advance(); // consume )
380
+ if (this.peek().kind === 'IDENT' && LOWERCASE_RE.test(this.peek().value)) {
381
+ const varName = this.advance().value;
382
+ if (this.peek().kind === 'FAT_ARROW') {
383
+ this.advance(); // consume =>
384
+ if (!this.varMap.has(varName)) {
385
+ const id = (0, types_1.freshTypeVarId)();
386
+ this.varMap.set(varName, id);
387
+ }
388
+ this.constraintVarNames.add(varName);
389
+ const display = `(${parsedType.args.map(a => {
390
+ const s = (0, types_1.typeToString)(a);
391
+ return a.tag === 'TFun' ? `(${s})` : s;
392
+ }).join(' | ')})`;
393
+ return [{
394
+ className: display,
395
+ typeVarName: varName,
396
+ unionAlternatives: parsedType.args,
397
+ }];
398
+ }
399
+ }
400
+ }
401
+ // Pattern didn't match — restore.
402
+ this.pos = savedPos;
403
+ this.varMap = new Map(savedVarMap);
404
+ this.constraintVarNames = new Set(savedConstraintVarNames);
405
+ }
406
+ catch {
407
+ this.pos = savedPos;
408
+ this.varMap = new Map(savedVarMap);
409
+ this.constraintVarNames = new Set(savedConstraintVarNames);
410
+ }
411
+ }
412
+ try {
413
+ // Try form 2: (Constraint, Constraint, ...) =>
414
+ if (this.peek().kind === 'LPAREN') {
415
+ const constraints = this.parseConstraintList();
416
+ if (this.peek().kind === 'FAT_ARROW') {
417
+ this.advance(); // consume =>
418
+ return constraints;
419
+ }
420
+ }
421
+ // Try form 1: ClassName varName => or ClassName (varName args...) =>
422
+ if (this.peek().kind === 'IDENT' && UPPERCASE_RE.test(this.peek().value)) {
423
+ const className = this.advance().value;
424
+ // Applied constraint: ClassName (varName args...) =>
425
+ if (this.peek().kind === 'LPAREN') {
426
+ this.advance(); // consume (
427
+ if (this.peek().kind === 'IDENT' && LOWERCASE_RE.test(this.peek().value)) {
428
+ const varName = this.advance().value;
429
+ if (!this.varMap.has(varName)) {
430
+ const id = (0, types_1.freshTypeVarId)();
431
+ this.varMap.set(varName, id);
432
+ }
433
+ this.constraintVarNames.add(varName);
434
+ // Consume inner type args (plain vars or nested applications)
435
+ const { names: innerArgNames, types: innerArgTypes } = this.parseAppliedConstraintArgs();
436
+ this.expect('RPAREN');
437
+ if (innerArgNames.length === 0) {
438
+ throw new TypeParseError(`Applied constraint '${className} (${varName})' requires inner type arguments. Use '${className} ${varName}' or '${className} (${varName} a)'.`);
439
+ }
440
+ const constraints = [{ className, typeVarName: varName, isApplied: true, appliedArgNames: innerArgNames, appliedArgs: innerArgTypes }];
441
+ // Check for comma-separated additional constraints (no parens)
442
+ while (this.peek().kind === 'COMMA') {
443
+ this.advance(); // consume ,
444
+ constraints.push(this.parseSingleConstraint());
445
+ }
446
+ if (this.peek().kind === 'FAT_ARROW') {
447
+ this.advance(); // consume =>
448
+ return constraints;
449
+ }
450
+ }
451
+ }
452
+ // Unified collector for the remaining single-constraint forms:
453
+ // - simple: `ClassName v =>`
454
+ // - mixed: `ClassName T1 T2 ... v =>` (positional + bound var)
455
+ // - concrete: `ClassName T =>` (single concrete arg)
456
+ // - all-extra: `ClassName T1 T2 ... T =>` (all positional concrete)
457
+ // Atoms are parsed via `parseSimpleAtom` so uppercase identifiers do
458
+ // NOT consume juxtaposition arguments — each token is one positional
459
+ // arg. Result is stored as `positionalArgs: Type[]`. `typeVarName`
460
+ // mirrors the LAST atom when it is a bare lowercase ident; otherwise
461
+ // it is the synthetic placeholder '_concrete'.
462
+ {
463
+ const collectSavedPos = this.pos;
464
+ const collectSavedVarMap = new Map(this.varMap);
465
+ try {
466
+ const atoms = [];
467
+ while (this.peek().kind === 'IDENT' ||
468
+ this.peek().kind === 'LPAREN' ||
469
+ this.peek().kind === 'LBRACKET' ||
470
+ this.peek().kind === 'LBRACE') {
471
+ atoms.push(this.parseSimpleAtom());
472
+ }
473
+ if (atoms.length >= 1) {
474
+ const last = atoms[atoms.length - 1];
475
+ const lastIsBareVar = last.tag === 'TVar' && !!last.name;
476
+ // Allow comma-separated additional constraints only for the
477
+ // pure simple case (single bare TVar); mixed/concrete forms
478
+ // are stand-alone.
479
+ if (atoms.length === 1 && lastIsBareVar) {
480
+ const tv = last;
481
+ this.constraintVarNames.add(tv.name);
482
+ const constraints = [{ className, typeVarName: tv.name }];
483
+ while (this.peek().kind === 'COMMA') {
484
+ this.advance(); // consume ,
485
+ constraints.push(this.parseSingleConstraint());
486
+ }
487
+ if (this.peek().kind === 'FAT_ARROW') {
488
+ this.advance(); // consume =>
489
+ return constraints;
490
+ }
491
+ }
492
+ else if (this.peek().kind === 'FAT_ARROW') {
493
+ this.advance(); // consume =>
494
+ if (lastIsBareVar) {
495
+ const tv = last;
496
+ this.constraintVarNames.add(tv.name);
497
+ return [{
498
+ className,
499
+ typeVarName: tv.name,
500
+ positionalArgs: atoms,
501
+ }];
502
+ }
503
+ return [{
504
+ className,
505
+ typeVarName: '_concrete',
506
+ positionalArgs: atoms,
507
+ }];
508
+ }
509
+ }
510
+ // No match \u2014 restore.
511
+ this.pos = collectSavedPos;
512
+ this.varMap = collectSavedVarMap;
513
+ }
514
+ catch {
515
+ this.pos = collectSavedPos;
516
+ this.varMap = collectSavedVarMap;
517
+ }
518
+ }
519
+ }
520
+ // No constraints found — restore position
521
+ this.pos = savedPos;
522
+ this.varMap = savedVarMap;
523
+ this.constraintVarNames = savedConstraintVarNames;
524
+ return [];
525
+ }
526
+ catch (e) {
527
+ // Re-throw explicit applied-constraint validation errors so they surface
528
+ // as proper diagnostics rather than being silently swallowed.
529
+ if (e instanceof TypeParseError && e.message.includes('requires inner type arguments')) {
530
+ throw e;
531
+ }
532
+ this.pos = savedPos;
533
+ this.varMap = savedVarMap;
534
+ this.constraintVarNames = savedConstraintVarNames;
535
+ return [];
536
+ }
537
+ }
538
+ finally {
539
+ this.suppressLabelVars = savedSuppress;
540
+ }
541
+ }
542
+ parseConstraintList() {
543
+ this.expect('LPAREN');
544
+ const constraints = [];
545
+ // Parse first constraint
546
+ constraints.push(this.parseSingleConstraint());
547
+ // Parse remaining constraints
548
+ while (this.peek().kind === 'COMMA') {
549
+ this.advance(); // consume ,
550
+ constraints.push(this.parseSingleConstraint());
551
+ }
552
+ this.expect('RPAREN');
553
+ return constraints;
554
+ }
555
+ /** Parse the inner argument list of an applied constraint (after the head
556
+ * var of `Setoid (f b)`). Accepts plain lowercase type vars and nested
557
+ * parenthesized applications (`Setoid (f (t a))`), encoding the latter
558
+ * exactly like the signature body encodes `t a` (a kv-named TCon) so
559
+ * signatures compare consistently. */
560
+ parseAppliedConstraintArgs() {
561
+ const names = [];
562
+ const types = [];
563
+ for (;;) {
564
+ const tok = this.peek();
565
+ if (tok.kind === 'IDENT' && LOWERCASE_RE.test(tok.value)) {
566
+ this.advance();
567
+ if (!this.varMap.has(tok.value)) {
568
+ this.varMap.set(tok.value, (0, types_1.freshTypeVarId)());
569
+ }
570
+ names.push(tok.value);
571
+ types.push({ tag: 'TVar', id: this.varMap.get(tok.value), name: tok.value });
572
+ continue;
573
+ }
574
+ if (tok.kind === 'LPAREN') {
575
+ this.advance(); // consume (
576
+ const headTok = this.expect('IDENT');
577
+ if (!LOWERCASE_RE.test(headTok.value)) {
578
+ throw new TypeParseError(`Expected type variable (lowercase) in nested applied-constraint argument, got '${headTok.value}'`);
579
+ }
580
+ if (!this.varMap.has(headTok.value)) {
581
+ this.varMap.set(headTok.value, (0, types_1.freshTypeVarId)());
582
+ }
583
+ const inner = this.parseAppliedConstraintArgs();
584
+ this.expect('RPAREN');
585
+ if (inner.types.length === 0) {
586
+ throw new TypeParseError(`Nested applied-constraint argument '(${headTok.value})' requires inner type arguments`);
587
+ }
588
+ names.push(`(${headTok.value} ${inner.names.join(' ')})`);
589
+ types.push((0, types_1.tCon)((0, types_1.kvName)(headTok.value, this.varMap.get(headTok.value)), inner.types));
590
+ continue;
591
+ }
592
+ break;
593
+ }
594
+ return { names, types };
595
+ }
596
+ parseSingleConstraint() {
597
+ // Structural-union head inside a constraint list: `(T1 | T2 | …) v`.
598
+ // Mirrors form 3 in `tryParseConstraints`, but here the surrounding
599
+ // parens belong to the list (e.g. `(String p, (Number | Undefined) x)`).
600
+ if (this.peek().kind === 'LPAREN') {
601
+ this.advance(); // consume (
602
+ const parsedType = this.parseType();
603
+ if (parsedType.tag !== 'TCon' || parsedType.name !== types_1.T_UNION) {
604
+ throw new TypeParseError('Expected a union type `(T1 | T2 | …)` in a parenthesised constraint head');
605
+ }
606
+ this.expect('RPAREN');
607
+ const varTok = this.expect('IDENT');
608
+ if (!LOWERCASE_RE.test(varTok.value)) {
609
+ throw new TypeParseError(`Expected type variable (lowercase) after union constraint head, got '${varTok.value}'`);
610
+ }
611
+ if (!this.varMap.has(varTok.value)) {
612
+ const id = (0, types_1.freshTypeVarId)();
613
+ this.varMap.set(varTok.value, id);
614
+ }
615
+ this.constraintVarNames.add(varTok.value);
616
+ const display = `(${parsedType.args.map(a => {
617
+ const s = (0, types_1.typeToString)(a);
618
+ return a.tag === 'TFun' ? `(${s})` : s;
619
+ }).join(' | ')})`;
620
+ return {
621
+ className: display,
622
+ typeVarName: varTok.value,
623
+ unionAlternatives: parsedType.args,
624
+ };
625
+ }
626
+ const classNameTok = this.expect('IDENT');
627
+ if (!UPPERCASE_RE.test(classNameTok.value)) {
628
+ throw new TypeParseError(`Expected constraint name (uppercase), got '${classNameTok.value}'`);
629
+ }
630
+ // Support applied constraints: Monoid (f a)
631
+ if (this.peek().kind === 'LPAREN') {
632
+ this.advance(); // consume (
633
+ const outerTok = this.expect('IDENT');
634
+ if (!LOWERCASE_RE.test(outerTok.value)) {
635
+ throw new TypeParseError(`Expected type variable (lowercase) in applied constraint, got '${outerTok.value}'`);
636
+ }
637
+ // Register the outer kind variable
638
+ if (!this.varMap.has(outerTok.value)) {
639
+ const id = (0, types_1.freshTypeVarId)();
640
+ this.varMap.set(outerTok.value, id);
641
+ }
642
+ this.constraintVarNames.add(outerTok.value);
643
+ // Consume any inner type args (e.g. the `a` in `f a`, or a nested
644
+ // application like `(t a)` in `Setoid (f (t a))`)
645
+ const { names: innerArgNames, types: innerArgTypes } = this.parseAppliedConstraintArgs();
646
+ this.expect('RPAREN');
647
+ if (innerArgNames.length === 0) {
648
+ throw new TypeParseError(`Applied constraint '${classNameTok.value} (${outerTok.value})' requires inner type arguments. Use '${classNameTok.value} ${outerTok.value}' or '${classNameTok.value} (${outerTok.value} a)'.`);
649
+ }
650
+ return { className: classNameTok.value, typeVarName: outerTok.value, isApplied: true, appliedArgNames: innerArgNames, appliedArgs: innerArgTypes };
651
+ }
652
+ const varNameTok = this.expect('IDENT');
653
+ if (!LOWERCASE_RE.test(varNameTok.value)) {
654
+ throw new TypeParseError(`Expected type variable (lowercase) after constraint name, got '${varNameTok.value}'`);
655
+ }
656
+ // Ensure the type var is registered
657
+ if (!this.varMap.has(varNameTok.value)) {
658
+ const id = (0, types_1.freshTypeVarId)();
659
+ this.varMap.set(varNameTok.value, id);
660
+ }
661
+ this.constraintVarNames.add(varNameTok.value);
662
+ return { className: classNameTok.value, typeVarName: varNameTok.value };
663
+ }
664
+ // -----------------------------------------------------------------------
665
+ // Type = Union ( -> Type )? (`->` is right-associative)
666
+ // Union = Atom ( | Atom )* (`|` binds TIGHTER than `->`)
667
+ //
668
+ // So `A | B -> C` parses as `(A | B) -> C` — the most natural reading.
669
+ // To make a function a union member, write `A | (B -> C)` explicitly.
670
+ // -----------------------------------------------------------------------
671
+ parseType() {
672
+ // Nested quantifier: `forall a b. [Constraints =>] Type`. `forall` is a
673
+ // CONTEXTUAL keyword — only recognised when followed by one or more
674
+ // lowercase identifiers and a dot, so `forall` stays usable as an
675
+ // ordinary type-variable name (backward compatibility).
676
+ if (this.isForallAhead())
677
+ return this.parseForall();
678
+ let left = this.parseAtom();
679
+ // Union: collect all `| Atom` members first (no arrows inside members).
680
+ if (this.peek().kind === 'PIPE') {
681
+ const members = [left];
682
+ while (this.peek().kind === 'PIPE') {
683
+ this.advance(); // consume |
684
+ members.push(this.parseAtom());
685
+ }
686
+ left = (0, types_1.tUnion)(members);
687
+ }
688
+ // Then optionally a single `->` makes everything-so-far the param.
689
+ if (this.peek().kind === 'ARROW') {
690
+ this.advance(); // consume ->
691
+ const right = this.parseType(); // right-associative
692
+ return (0, types_1.tFun)(left, right);
693
+ }
694
+ return left;
695
+ }
696
+ /** Lookahead: IDENT `forall`, then ≥1 lowercase IDENT, then `.` */
697
+ isForallAhead() {
698
+ const t0 = this.peek();
699
+ if (t0.kind !== 'IDENT' || t0.value !== 'forall')
700
+ return false;
701
+ let i = this.pos + 1;
702
+ let count = 0;
703
+ while (this.tokens[i] && this.tokens[i].kind === 'IDENT' && LOWERCASE_RE.test(this.tokens[i].value)) {
704
+ i++;
705
+ count++;
706
+ }
707
+ return count > 0 && this.tokens[i] !== undefined && this.tokens[i].kind === 'DOT';
708
+ }
709
+ /** Parse `forall a b. [Constraints =>] Type` into a TForall node.
710
+ * The bound names shadow same-named outer variables while the body is
711
+ * parsed, and are removed from `varMap` afterwards so the enclosing
712
+ * scheme never auto-quantifies them. */
713
+ parseForall() {
714
+ this.advance(); // 'forall'
715
+ const names = [];
716
+ while (this.peek().kind === 'IDENT' && LOWERCASE_RE.test(this.peek().value)) {
717
+ names.push(this.advance().value);
718
+ }
719
+ this.expect('DOT');
720
+ // Scope: shadow outer vars of the same name with fresh bound ids.
721
+ const savedVarIds = names.map(n => [n, this.varMap.get(n)]);
722
+ const savedConstraintHas = names.map(n => [n, this.constraintVarNames.has(n)]);
723
+ const vars = [];
724
+ for (const n of names) {
725
+ const id = (0, types_1.freshTypeVarId)();
726
+ this.varMap.set(n, id);
727
+ vars.push(id);
728
+ }
729
+ // Optional scoped constraints: `forall f. Functor f => …`. These parse
730
+ // via the regular constraint machinery (which also registers `f` in
731
+ // `constraintVarNames`, so `f a` in the body parses as a kv application).
732
+ const constraints = this.tryParseConstraints();
733
+ for (const c of constraints) {
734
+ const idx = names.indexOf(c.typeVarName);
735
+ if (idx >= 0 && c.varId === undefined)
736
+ c.varId = vars[idx];
737
+ }
738
+ const body = this.parseType();
739
+ // Restore the enclosing scope.
740
+ for (const [n, old] of savedVarIds) {
741
+ if (old === undefined)
742
+ this.varMap.delete(n);
743
+ else
744
+ this.varMap.set(n, old);
745
+ }
746
+ for (const [n, had] of savedConstraintHas) {
747
+ if (!had)
748
+ this.constraintVarNames.delete(n);
749
+ }
750
+ this.sawForall = true;
751
+ return (0, types_1.tForall)(vars, names, body, constraints.length > 0 ? constraints : undefined);
752
+ }
753
+ // -----------------------------------------------------------------------
754
+ // Atom = '(' Type ')' | '[' Type ']' | Ident | Ident '<' Type (',' Type)* '>'
755
+ // -----------------------------------------------------------------------
756
+ parseAtom() {
757
+ return this.parseAtomCore(true);
758
+ }
759
+ /**
760
+ * Parse a simple atom without juxtaposition — uppercase identifiers are
761
+ * returned as bare TCon (no args consumed). Parenthesized groups and
762
+ * array shorthand still allow full types inside them.
763
+ */
764
+ parseSimpleAtom() {
765
+ return this.parseAtomCore(false);
766
+ }
767
+ /**
768
+ * Core atom parser.
769
+ * When `withJuxtaposition` is true, an uppercase identifier consumes following
770
+ * simple atoms as type arguments (e.g. `Box a`, `Either a b`).
771
+ * When false, uppercase identifiers are returned bare as `tCon(name, [])`.
772
+ */
773
+ parseAtomCore(withJuxtaposition) {
774
+ const tok = this.peek();
775
+ // Record type: { field :: Type, field2 :: Type, ... }
776
+ if (tok.kind === 'LBRACE') {
777
+ return this.parseRecordType();
778
+ }
779
+ // Parenthesized type or tuple: (A) or (A, B, ...) or (..., Y, Z) or () for unit/void
780
+ if (tok.kind === 'LPAREN') {
781
+ this.advance();
782
+ // () — empty parens represent the Unit/Void type
783
+ if (this.peek().kind === 'RPAREN') {
784
+ this.advance();
785
+ return (0, types_1.tCon)('Void');
786
+ }
787
+ // Leading spread: (..., y, z)
788
+ if (this.peek().kind === 'ELLIPSIS') {
789
+ this.advance(); // consume ...
790
+ const types = [types_1.tSpread];
791
+ while (this.peek().kind === 'COMMA') {
792
+ this.advance(); // consume ,
793
+ if (this.peek().kind === 'ELLIPSIS') {
794
+ this.advance(); // consume ...
795
+ types.push(types_1.tSpread);
796
+ continue;
797
+ }
798
+ types.push(this.parseType());
799
+ }
800
+ this.expect('RPAREN');
801
+ return (0, types_1.tCon)(types_1.T_TUPLE, types);
802
+ }
803
+ const first = this.parseType();
804
+ if (this.peek().kind === 'COMMA') {
805
+ // Tuple: (A, B, ...) — used for multi-param function types
806
+ const types = [first];
807
+ while (this.peek().kind === 'COMMA') {
808
+ this.advance(); // consume ,
809
+ // Spread marker: (a, ..., z) — variadic tuple
810
+ if (this.peek().kind === 'ELLIPSIS') {
811
+ this.advance(); // consume ...
812
+ types.push(types_1.tSpread);
813
+ continue;
814
+ }
815
+ types.push(this.parseType());
816
+ }
817
+ this.expect('RPAREN');
818
+ return (0, types_1.tCon)(types_1.T_TUPLE, types);
819
+ }
820
+ // Parenthesized higher-kinded application: (f m), (f a b), etc.
821
+ // When the inner type is a bare TVar and there are remaining atom
822
+ // tokens before the closing paren, treat as kind-variable application.
823
+ // Reject legacy predicate syntax: (a is Type).
824
+ if (first.tag === 'TVar' && this.peek().kind !== 'RPAREN') {
825
+ if (this.peek().kind === 'IDENT' && this.peek().value === 'is') {
826
+ throw new TypeParseError(`Legacy inline type predicate syntax (${first.name} is ...) is not supported. Use ::narrow instead.`);
827
+ }
828
+ const args = [];
829
+ while (this.peek().kind !== 'RPAREN' &&
830
+ this.peek().kind !== 'EOF' &&
831
+ (this.peek().kind === 'IDENT' ||
832
+ this.peek().kind === 'LPAREN' ||
833
+ this.peek().kind === 'LBRACKET' ||
834
+ this.peek().kind === 'LBRACE' ||
835
+ this.peek().kind === 'NUMBER' ||
836
+ this.peek().kind === 'STRING')) {
837
+ args.push(this.parseAtomCore(false));
838
+ }
839
+ if (args.length > 0) {
840
+ this.expect('RPAREN');
841
+ return (0, types_1.tCon)((0, types_1.kvName)(first.name, first.id), args);
842
+ }
843
+ }
844
+ this.expect('RPAREN');
845
+ return first;
846
+ }
847
+ // Array shorthand: [Type] or spread array: [a, ..., b] or [..., a, b]
848
+ if (tok.kind === 'LBRACKET') {
849
+ this.advance();
850
+ // Strict empty array: `[]` — analogous to strict empty record `{}`.
851
+ // Encoded as a 1-arg `Array` (fresh element var) carrying the
852
+ // `strictEmpty` flag so the `Array` arity invariant holds while
853
+ // unification still treats it as "accepts only an empty array".
854
+ if (this.peek().kind === 'RBRACKET') {
855
+ this.advance(); // consume ]
856
+ return { tag: 'TCon', name: 'Array', args: [(0, types_1.tVar)()], strictEmpty: true };
857
+ }
858
+ // Leading spread: [..., a, b]
859
+ if (this.peek().kind === 'ELLIPSIS') {
860
+ this.advance(); // consume ...
861
+ const types = [types_1.tSpread];
862
+ while (this.peek().kind === 'COMMA') {
863
+ this.advance(); // consume ,
864
+ if (this.peek().kind === 'ELLIPSIS') {
865
+ this.advance(); // consume ...
866
+ types.push(types_1.tSpread);
867
+ continue;
868
+ }
869
+ types.push(this.parseType());
870
+ }
871
+ this.expect('RBRACKET');
872
+ return (0, types_1.tCon)('SpreadArray', types);
873
+ }
874
+ const first = this.parseType();
875
+ if (this.peek().kind === 'COMMA') {
876
+ // Spread array: [a, ..., b] or [a -> b, b -> c, ..., y -> z]
877
+ // Also: trailing comma `[a,]` → a FIXED 1-slot SpreadArray (exactly
878
+ // one element of type `a`), distinct from `[a]` (= `Array a`, any length).
879
+ const types = [first];
880
+ while (this.peek().kind === 'COMMA') {
881
+ this.advance(); // consume ,
882
+ if (this.peek().kind === 'RBRACKET')
883
+ break; // trailing comma
884
+ if (this.peek().kind === 'ELLIPSIS') {
885
+ this.advance(); // consume ...
886
+ types.push(types_1.tSpread);
887
+ continue;
888
+ }
889
+ types.push(this.parseType());
890
+ }
891
+ this.expect('RBRACKET');
892
+ return (0, types_1.tCon)('SpreadArray', types);
893
+ }
894
+ this.expect('RBRACKET');
895
+ return (0, types_1.tCon)('Array', [first]);
896
+ }
897
+ // Must be an identifier
898
+ if (tok.kind === 'IDENT') {
899
+ const name = this.advance().value;
900
+ // Boolean literal values: true, false → infer Boolean type
901
+ if (name === 'true' || name === 'false') {
902
+ return types_1.tBool;
903
+ }
904
+ // Lowercase type keywords: null → Null, undefined → Undefined
905
+ if (name === 'null') {
906
+ return types_1.tNull;
907
+ }
908
+ if (name === 'undefined') {
909
+ return types_1.tUndefined;
910
+ }
911
+ // Check for generic args: Ident '<' ... '>'
912
+ if (this.peek().kind === 'LANGLE') {
913
+ this.advance(); // consume <
914
+ const args = [this.parseType()];
915
+ while (this.peek().kind === 'COMMA') {
916
+ this.advance(); // consume ,
917
+ args.push(this.parseType());
918
+ }
919
+ this.expect('RANGLE');
920
+ return (0, types_1.tCon)(name, args);
921
+ }
922
+ // Is it a known concrete type (starts uppercase) or a type variable (lowercase)?
923
+ if (name[0] === name[0].toUpperCase() && UPPERCASE_RE.test(name)) {
924
+ if (!withJuxtaposition) {
925
+ // Simple mode: return bare TCon without consuming any arguments
926
+ return (0, types_1.tCon)(name, []);
927
+ }
928
+ // Juxtaposition type application: Box a, Box Number, Either a b, etc.
929
+ // Consume following *simple* atoms as type arguments (lowercase vars,
930
+ // uppercase concrete types WITHOUT their own juxtaposition args,
931
+ // parenthesized types, and array shorthand).
932
+ //
933
+ // When the arity of this constructor is known, parse the last
934
+ // positional argument with full juxtaposition (parseAtomCore(true))
935
+ // so that constraint variables like `f` in `Pair Boolean f m` can
936
+ // consume their own arguments (`f m` → $kv:f(m)).
937
+ const knownArity = (name === 'Function' || name === 'Object')
938
+ ? 2
939
+ : this.typeArities.get(name);
940
+ const args = [];
941
+ while ((this.peek().kind === 'IDENT' ||
942
+ this.peek().kind === 'LPAREN' ||
943
+ this.peek().kind === 'LBRACKET' ||
944
+ this.peek().kind === 'LBRACE' ||
945
+ this.peek().kind === 'NUMBER' ||
946
+ this.peek().kind === 'STRING')) {
947
+ const isLastPosition = knownArity !== undefined && args.length === knownArity - 1;
948
+ args.push(this.parseAtomCore(isLastPosition));
949
+ }
950
+ return (0, types_1.tCon)(name, args);
951
+ }
952
+ // Lowercase type variable — may be a higher-kinded constructor
953
+ // via juxtaposition: f a, m b, m (Maybe a).
954
+ // Constraint variables (from `Functor f =>`) get full juxtaposition
955
+ // (consuming any following atoms). Non-constraint variables only get
956
+ // HK treatment when followed by a parenthesized group — this covers
957
+ // the common m (Maybe a) pattern without breaking trailing-token checks.
958
+ // Label variables (any name appearing as `[name]` somewhere in the
959
+ // signature, picked up during pre-scan) are returned as TLabel
960
+ // wherever they appear bare in type position — e.g. the first `k`
961
+ // in `k -> { [k] :: a, ...r } -> { ...r }`.
962
+ //
963
+ // EXCEPTION: when the same name is ALSO a constraint variable
964
+ // (`Array String k => k -> { [k] :: a }`), the constraint binding wins
965
+ // for bare/applied `k` in type position so it can be baked to the
966
+ // constrained type (`k := Array String`). The `[k]` record key itself
967
+ // is still resolved to the shared label by `parseRecordField`.
968
+ if (this.labelVarMap.has(name) &&
969
+ !this.suppressLabelVars &&
970
+ !this.constraintVarNames.has(name)) {
971
+ return this.labelVarMap.get(name);
972
+ }
973
+ if (!this.varMap.has(name)) {
974
+ const id = (0, types_1.freshTypeVarId)();
975
+ this.varMap.set(name, id);
976
+ }
977
+ const varId = this.varMap.get(name);
978
+ if (withJuxtaposition &&
979
+ (this.constraintVarNames.has(name) || this.peek().kind === 'LPAREN')) {
980
+ // Parse juxtaposition args (like uppercase constructors)
981
+ const args = [];
982
+ while ((this.peek().kind === 'IDENT' ||
983
+ this.peek().kind === 'LPAREN' ||
984
+ this.peek().kind === 'LBRACKET' ||
985
+ this.peek().kind === 'LBRACE' ||
986
+ this.peek().kind === 'NUMBER' ||
987
+ this.peek().kind === 'STRING')) {
988
+ args.push(this.parseAtomCore(false));
989
+ }
990
+ if (args.length > 0) {
991
+ // Higher-kinded application: encode as $kv:name:id TCon
992
+ return (0, types_1.tCon)((0, types_1.kvName)(name, varId), args);
993
+ }
994
+ }
995
+ // No args or simple mode: just a bare type variable
996
+ return { tag: 'TVar', id: varId, name };
997
+ }
998
+ // Number literal in type position → numeric literal (singleton) type,
999
+ // e.g. `_Tuple :: 2 -> …` (see `tNumLit`).
1000
+ if (tok.kind === 'NUMBER') {
1001
+ this.advance();
1002
+ return (0, types_1.tNumLit)(Number(tok.value));
1003
+ }
1004
+ // String literal in type position → label-literal (singleton) type.
1005
+ // E.g. `'id'` parses as tLabelLit('id'), and `'id' | 'name'` becomes a
1006
+ // union of label-lits — usable for per-key string-literal validation
1007
+ // (see query-builder per-table selector unions). TLabelLit is silently
1008
+ // unify-compatible with the wide `String` type, so existing code that
1009
+ // wrote a single string-literal where a String was expected still works.
1010
+ if (tok.kind === 'STRING') {
1011
+ this.advance();
1012
+ // Strip surrounding quotes (the tokenizer keeps them in `value`).
1013
+ const raw = tok.value;
1014
+ const inner = raw.length >= 2 && (raw[0] === '"' || raw[0] === "'")
1015
+ ? raw.slice(1, -1)
1016
+ : raw;
1017
+ return (0, types_1.tLabelLit)(inner);
1018
+ }
1019
+ // Star (*) — wildcard / any type
1020
+ if (tok.kind === 'STAR') {
1021
+ this.advance();
1022
+ return types_1.tAny;
1023
+ }
1024
+ // Bare spread marker: ... (used in curry result types like a -> b -> ... -> z)
1025
+ if (tok.kind === 'ELLIPSIS') {
1026
+ this.advance();
1027
+ return types_1.tSpread;
1028
+ }
1029
+ throw new TypeParseError(`Unexpected token ${tok.kind} ("${tok.value}") — expected a type`);
1030
+ }
1031
+ // -----------------------------------------------------------------------
1032
+ // Record type: { key :: Type, key2 :: Type, ... }
1033
+ // Values can be types OR literal values (numbers, strings, booleans)
1034
+ // -----------------------------------------------------------------------
1035
+ parseRecordType() {
1036
+ this.expect('LBRACE');
1037
+ // Reject the alternate row-rest syntax `{ a :: T | r }` — only
1038
+ // the spread form `{ a :: T, ...r }` is supported. We scan ahead
1039
+ // for a top-level PIPE within the matching braces; a union value
1040
+ // type like `{ a :: Integer | String }` is still allowed because
1041
+ // the trailing `}` is preceded by an IDENT that is *not* the last
1042
+ // token before `}` in a row-rest position — distinguish by
1043
+ // checking whether the PIPE is followed by exactly `IDENT }` or
1044
+ // `IDENT ,`.
1045
+ {
1046
+ let depth = 1;
1047
+ let i = this.pos;
1048
+ while (i < this.tokens.length && depth > 0) {
1049
+ const tk = this.tokens[i];
1050
+ if (tk.kind === 'LBRACE' || tk.kind === 'LPAREN' || tk.kind === 'LBRACKET')
1051
+ depth++;
1052
+ else if (tk.kind === 'RBRACE' || tk.kind === 'RPAREN' || tk.kind === 'RBRACKET')
1053
+ depth--;
1054
+ else if (depth === 1 && tk.kind === 'PIPE') {
1055
+ const a = this.tokens[i + 1];
1056
+ const b = this.tokens[i + 2];
1057
+ if (a && b && a.kind === 'IDENT' && LOWERCASE_RE.test(a.value)
1058
+ && (b.kind === 'RBRACE' || b.kind === 'COMMA')) {
1059
+ throw new TypeParseError(`Use '...${a.value}' for record row-rest, not '| ${a.value}'`);
1060
+ }
1061
+ }
1062
+ i++;
1063
+ }
1064
+ }
1065
+ const fields = {};
1066
+ const labelFields = [];
1067
+ // Collect ALL spread (`...x`) row variables; if more than one we lower
1068
+ // to `Merge` (see Plan v6.3 Phase A).
1069
+ const rests = [];
1070
+ const buildSingleRecord = (rest) => {
1071
+ const out = rest ? (0, types_1.tOpenRecord)(fields, rest) : (0, types_1.tRecord)(fields);
1072
+ if (labelFields.length > 0)
1073
+ out.labelFields = labelFields;
1074
+ return out;
1075
+ };
1076
+ const finish = () => {
1077
+ if (rests.length <= 1) {
1078
+ // A literal `{}` in an annotation is a strict, closed, exactly-empty
1079
+ // object: tag it so unification refuses to absorb surplus fields.
1080
+ if (rests.length === 0
1081
+ && Object.keys(fields).length === 0
1082
+ && labelFields.length === 0) {
1083
+ return { tag: 'TRecord', fields: {}, strictEmpty: true };
1084
+ }
1085
+ return buildSingleRecord(rests[0]);
1086
+ }
1087
+ // Multi-spread → lower to Merge. When concrete fields/labelFields
1088
+ // are present, the first Merge arg is a closed TRecord holding them.
1089
+ const hasConcrete = Object.keys(fields).length > 0 || labelFields.length > 0;
1090
+ const args = [];
1091
+ if (hasConcrete)
1092
+ args.push(buildSingleRecord(undefined));
1093
+ for (const r of rests)
1094
+ args.push(r);
1095
+ return (0, types_1.tCon)(types_1.T_MERGE, args);
1096
+ };
1097
+ // Empty record: {}
1098
+ if (this.peek().kind === 'RBRACE') {
1099
+ this.advance();
1100
+ return finish();
1101
+ }
1102
+ // Parse comma-separated entries: each entry is a field, a bracket-form
1103
+ // field, or a `...rowvar` spread. Multiple spreads are allowed.
1104
+ const parseEntry = () => {
1105
+ if (this.peek().kind === 'ELLIPSIS') {
1106
+ rests.push(this.parseRowVar());
1107
+ return;
1108
+ }
1109
+ // Shorthand row variable: a lone lowercase identifier (`{a}` or the `a`
1110
+ // in `{a, b}`) is sugar for the spread form `{...a}` — an open record
1111
+ // whose unknown fields range over the row variable `a`.
1112
+ const cur = this.peek();
1113
+ const next = this.tokens[this.pos + 1];
1114
+ if (cur.kind === 'IDENT' && LOWERCASE_RE.test(cur.value)
1115
+ && next && (next.kind === 'RBRACE' || next.kind === 'COMMA')) {
1116
+ this.advance(); // consume the identifier
1117
+ rests.push(this.rowVarFromName(cur.value));
1118
+ return;
1119
+ }
1120
+ this.parseRecordField(fields, labelFields);
1121
+ };
1122
+ parseEntry();
1123
+ while (this.peek().kind === 'COMMA') {
1124
+ this.advance(); // consume ,
1125
+ parseEntry();
1126
+ }
1127
+ this.expect('RBRACE');
1128
+ return finish();
1129
+ }
1130
+ parseRowVar() {
1131
+ this.advance(); // consume ...
1132
+ const tok = this.expect('IDENT');
1133
+ if (!LOWERCASE_RE.test(tok.value)) {
1134
+ throw new TypeParseError(`Row variable must be a lowercase identifier (got '${tok.value}')`);
1135
+ }
1136
+ return this.rowVarFromName(tok.value);
1137
+ }
1138
+ /**
1139
+ * Build a row variable (`TRow`) for a given name. Row variables share the
1140
+ * type-var id space (the disjointness is enforced by `tag`, not by id
1141
+ * allocation). The name is registered in `varMap` so quantification picks
1142
+ * it up at scheme-creation time, and the emitted `TRow`'s `id` matches the
1143
+ * shared name's id. Used for both the `...a` spread form and the `{a}`
1144
+ * shorthand.
1145
+ */
1146
+ rowVarFromName(name) {
1147
+ if (!this.varMap.has(name)) {
1148
+ this.varMap.set(name, (0, types_1.freshTypeVarId)());
1149
+ }
1150
+ const id = this.varMap.get(name);
1151
+ return { tag: 'TRow', id, name };
1152
+ }
1153
+ parseRecordField(fields, labelFields) {
1154
+ // Bracket-form field key: `[k] :: type` or `['x'] :: type`
1155
+ if (this.peek().kind === 'LBRACKET') {
1156
+ this.advance(); // [
1157
+ const tok = this.advance();
1158
+ if (tok.kind !== 'IDENT' || !LOWERCASE_RE.test(tok.value)) {
1159
+ throw new TypeParseError(`Bracketed record key must be a label variable (lowercase ident), got '${tok.value}'`);
1160
+ }
1161
+ if (!this.labelVarMap.has(tok.value)) {
1162
+ this.labelVarMap.set(tok.value, (0, types_1.tLabelVar)(tok.value));
1163
+ }
1164
+ const label = this.labelVarMap.get(tok.value);
1165
+ this.expect('RBRACKET');
1166
+ this.expect('COLON');
1167
+ if (this.peek().kind !== 'COLON') {
1168
+ throw new TypeParseError(`Use '::' for record field separator after bracketed key`);
1169
+ }
1170
+ this.advance(); // second :
1171
+ const valueType = this.parseType();
1172
+ labelFields.push({ label, type: valueType });
1173
+ return;
1174
+ }
1175
+ const keyTok = this.expect('IDENT');
1176
+ this.expect('COLON');
1177
+ if (this.peek().kind !== 'COLON') {
1178
+ throw new TypeParseError(`Use '::' for record field separator (found single ':' after '${keyTok.value}')`);
1179
+ }
1180
+ this.advance(); // consume second ':'
1181
+ const valueType = this.parseType();
1182
+ fields[keyTok.value] = valueType;
1183
+ }
1184
+ }
1185
+ // ---------------------------------------------------------------------------
1186
+ // Public API
1187
+ // ---------------------------------------------------------------------------
1188
+ /**
1189
+ * Build the error for input left over after a complete type was parsed.
1190
+ * Two leftovers have a known cause and get an actionable message instead of
1191
+ * the bare "Unexpected trailing token":
1192
+ * - `f a` where `f` is a lowercase variable without a constraint: only
1193
+ * constraint variables absorb juxtaposed arguments (see README, "Generics
1194
+ * & Higher-Kinded Types"), so the parse stops after `f`.
1195
+ * - a `=>` that the constraint list could not claim, e.g.
1196
+ * `(TypeRep M, Monad m) => …`: a constraint must be `Class var` with a
1197
+ * lowercase variable, so the parenthesised list was parsed as a tuple.
1198
+ */
1199
+ function trailingTokenError(parser) {
1200
+ const tok = parser['peek']();
1201
+ const prev = parser['tokens'][parser['pos'] - 1];
1202
+ if (tok.kind === 'FAT_ARROW') {
1203
+ return new TypeParseError(`Unexpected '=>': each constraint must be a class applied to a lowercase type variable (e.g. 'Monad m =>'); a concrete type such as 'TypeRep M' cannot appear in the constraint list`);
1204
+ }
1205
+ if (prev && prev.kind === 'IDENT' && /^[a-z]/.test(prev.value)
1206
+ && (tok.kind === 'IDENT' || tok.kind === 'LBRACKET' || tok.kind === 'LBRACE')) {
1207
+ return new TypeParseError(`Type variable '${prev.value}' is applied to '${tok.value}' but has no constraint. Add a constraint like 'Functor ${prev.value} =>' to use it as a type constructor`);
1208
+ }
1209
+ return new TypeParseError(`Unexpected trailing token: ${tok.value}`);
1210
+ }
1211
+ /**
1212
+ * Parse a Hindley-Milner type signature string into a `Scheme`.
1213
+ *
1214
+ * Examples:
1215
+ * "Number -> String"
1216
+ * "a -> a"
1217
+ * "[Number] -> Number"
1218
+ * "(Number -> String) -> Boolean"
1219
+ * "Box a" (juxtaposition type application)
1220
+ */
1221
+ function parseTypeSignature(input, constraintVarNames, typeArities) {
1222
+ const tokens = tokenize(input);
1223
+ const parser = new TypeParser(tokens);
1224
+ if (constraintVarNames) {
1225
+ for (const name of constraintVarNames) {
1226
+ parser['constraintVarNames'].add(name);
1227
+ }
1228
+ }
1229
+ if (typeArities) {
1230
+ parser['typeArities'] = typeArities;
1231
+ }
1232
+ const scheme = parser.parseScheme();
1233
+ // Verify we consumed everything (allow ~> to stop here for method sigs)
1234
+ if (parser['peek']().kind !== 'EOF' && parser['peek']().kind !== 'SQUIGGLY') {
1235
+ throw trailingTokenError(parser);
1236
+ }
1237
+ return scheme;
1238
+ }
1239
+ /**
1240
+ * Parse a type signature, returning only the `Type` (discarding quantifiers).
1241
+ */
1242
+ function parseType(input) {
1243
+ return parseTypeSignature(input).type;
1244
+ }
1245
+ /**
1246
+ * Parse a method type signature with `~>` syntax.
1247
+ *
1248
+ * Example: "Box a ~> (a -> b) -> Box b"
1249
+ * Returns: { receiver: Box<a>, methodType: (a -> b) -> Box<b> }
1250
+ *
1251
+ * @param constraintVarNames Optional set of type variable names that should
1252
+ * be treated as higher-kinded (constraint) variables. This allows parsing
1253
+ * `f a ~> ...` where `f` is a constraint type variable.
1254
+ */
1255
+ function parseMethodTypeSignature(input, constraintVarNames, typeArities) {
1256
+ const tokens = tokenize(input);
1257
+ const parser = new TypeParser(tokens);
1258
+ // Populate constraint variable names so the parser can handle
1259
+ // higher-kinded type application like `f a`
1260
+ if (constraintVarNames) {
1261
+ for (const name of constraintVarNames) {
1262
+ parser['constraintVarNames'].add(name);
1263
+ }
1264
+ }
1265
+ if (typeArities) {
1266
+ parser['typeArities'] = typeArities;
1267
+ }
1268
+ // Parse optional constraints: `Monad m =>` or `(Functor f, Monad m) =>`
1269
+ const constraints = parser['tryParseConstraints']();
1270
+ // Parse receiver type (left of ~>)
1271
+ const receiver = parser['normalizeObjectKeys'](parser['parseType']());
1272
+ parser['expect']('SQUIGGLY');
1273
+ // Parse method type (right of ~>)
1274
+ const methodType = parser['normalizeObjectKeys'](parser['parseType']());
1275
+ if (parser['peek']().kind !== 'EOF') {
1276
+ throw trailingTokenError(parser);
1277
+ }
1278
+ const vars = Array.from(parser['varMap'].values());
1279
+ return {
1280
+ receiver,
1281
+ methodType,
1282
+ scheme: { vars, type: methodType, constraints: constraints.length > 0 ? constraints : undefined },
1283
+ };
1284
+ }
1285
+ //# sourceMappingURL=typeParser.js.map