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
package/README.md CHANGED
@@ -1,3 +1,2307 @@
1
- # Temporary Holding Version
1
+ # HinMil — Hindley-Milner for JavaScript
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![VS Code Marketplace](https://badgen.net/vs-marketplace/v/hinmil.hinmil)](https://marketplace.visualstudio.com/items?itemName=hinmil.hinmil)
4
+ [![npm](https://img.shields.io/npm/v/hinmil)](https://www.npmjs.com/package/hinmil)
5
+ [![License: MIT](https://img.shields.io/github/license/tureluren/hinmil)](LICENSE)
6
+ [![CI](https://github.com/tureluren/hinmil/actions/workflows/ci.yml/badge.svg)](https://github.com/tureluren/hinmil/actions/workflows/ci.yml)
7
+
8
+ HinMil is a VS Code extension that type-checks plain JavaScript. You write type
9
+ signatures in ordinary comments, and a Hindley-Milner inference engine checks
10
+ your code against them while you type. There is no build step and no
11
+ transpilation — the files stay plain `.js`.
12
+
13
+ ```javascript
14
+ // lineTotal :: (Number, Number) -> Number
15
+ const lineTotal = (quantity, unitPrice) => quantity * unitPrice;
16
+ ```
17
+
18
+ ![A call with a string where a number is expected: HinMil underlines it, the hover shows the type mismatch, and after the fix the hover shows the inferred type total :: Number](images/diagnostics.gif)
19
+
20
+ On top of the checker sit the editor features you would expect: hover types,
21
+ diagnostics, completion, signature help, quick fixes, rename, and an outline
22
+ view. The type system itself goes further than you might assume for a
23
+ comment-based checker: records with row polymorphism, sum types, type classes
24
+ with constraints, higher-kinded types, currying, overloading, and type
25
+ narrowing. The sections below cover all of it.
26
+
27
+ ---
28
+
29
+ ## Why HinMil?
30
+
31
+ If you already write Hindley-Milner signatures in your comments, as the
32
+ documentation of Ramda, Sanctuary, Fluture and fantasy-land does, HinMil
33
+ turns them into checked types. Your code stays plain JavaScript that runs as
34
+ it is.
35
+
36
+ ```javascript
37
+ // ::constraint Functor f { f :: { map :: f a ~> (a -> b) -> f b } }
38
+
39
+ // map :: Functor f => (a -> b) -> f a -> f b
40
+ const map = fn => functor => functor.map (fn);
41
+
42
+ const lengths = map (s => s.length) (["Ada", "Alan"]); // [Number]
43
+ const wrong = map (s => s.length) (42);
44
+ // ✗ Type mismatch: Cannot unify 'Number' with 'f a'
45
+ ```
46
+
47
+ How it compares to the other ways of getting types into JavaScript:
48
+
49
+ | | HinMil | TypeScript | JSDoc + `checkJs` | Flow |
50
+ |---|---|---|---|---|
51
+ | Files stay plain `.js`, no build step | yes | no: `.ts` is compiled or stripped | yes | only with its `/*: T */` comment syntax |
52
+ | How you write a type | one HM line above the declaration | inline annotations | `@param`, `@returns`, `@template` tags | inline annotations |
53
+ | Inference without annotations | Hindley-Milner: `compose = (f, g) => x => f (g (x))` gets `(a -> b, c -> a) -> c -> b` | local; an unannotated parameter is `any` | as TypeScript | local; exports need annotations |
54
+ | Curried functions (`a -> b -> c`) | the natural form | possible, verbose with generics | verbose | possible, verbose |
55
+ | Higher-kinded types and type classes (`Functor f =>`) | yes | no, only through encodings | no | no |
56
+ | Sum types | `Maybe :: Just a \| Nothing`, with constructors and narrowing | discriminated unions | as TypeScript | disjoint unions |
57
+ | Types for npm packages | React, Node built-ins, and packages that ship HM annotations; everything else is `Any` | nearly every package (DefinitelyTyped) | as TypeScript | flow-typed, fewer |
58
+ | Editors | VS Code, plus a CLI for CI | every major editor | every major editor | most editors |
59
+ | Maturity | new (0.x) | very mature | very mature | mature, mostly used at Meta |
60
+
61
+ **When to choose what:**
62
+
63
+ - **TypeScript** when you need the ecosystem: types for every dependency,
64
+ editor support everywhere, refactorings, and a team that already knows it.
65
+ - **JSDoc + `checkJs`** when you want TypeScript's checker without a build
66
+ step and do not mind the verbose tag syntax.
67
+ - **HinMil** when you write JavaScript in a functional style (currying,
68
+ composition, algebraic data types, fantasy-land type classes) and want the
69
+ signatures you already write to be checked, without leaving plain `.js`.
70
+
71
+ **Honest limitations:**
72
+
73
+ - A package without HM annotations is `Any`, and `Any` fits everywhere. A
74
+ check is only as strict as the types it can see.
75
+ - Inference is strongest on functions and records. A method call on an
76
+ unannotated parameter (`items => items.reduce (…)`) stays open, so annotate
77
+ the functions you export.
78
+ - HinMil checks; it never changes or emits code. It is young, has one
79
+ maintainer, and the editor integration is VS Code only.
80
+
81
+ ---
82
+
83
+ ## Table of Contents
84
+
85
+ - [Why HinMil?](#why-hinmil)
86
+ - [Getting Started](#getting-started)
87
+ - [Type Annotations](#type-annotations)
88
+ - [Method Annotations](#method-annotations)
89
+ - [Hover](#hover)
90
+ - [Diagnostics](#diagnostics)
91
+ - [Autocompletion](#autocompletion)
92
+ - [Signature Help](#signature-help)
93
+ - [Code Actions](#code-actions)
94
+ - [Go to definition](#go-to-definition)
95
+ - [Using HinMil without the built-in TypeScript extension](#using-hinmil-without-the-built-in-typescript-extension)
96
+ - [Find References & Rename](#find-references--rename)
97
+ - [Document Symbols](#document-symbols)
98
+ - [Syntax Highlighting](#syntax-highlighting)
99
+ - [Sum Types](#sum-types)
100
+ - [Variants and constructors](#variants-and-constructors)
101
+ - [Variant methods](#variant-methods)
102
+ - [Factory functions instead of classes](#factory-functions-instead-of-classes)
103
+ - [Multi-line declarations and complex fields](#multi-line-declarations-and-complex-fields)
104
+ - [Phantom variant parameters](#phantom-variant-parameters)
105
+ - [Narrowing on variants](#narrowing-on-variants)
106
+ - [JSX & React](#jsx--react)
107
+ - [Optional props](#optional-props)
108
+ - [Directives](#directives)
109
+ - [::constraint — Type Classes](#constraint--type-classes)
110
+ - [::narrow — Type Predicates](#narrow--type-predicates)
111
+ - [::types — Cross-File Types](#types--cross-file-types)
112
+ - [::global — Extend Built-in Types](#global--extend-built-in-types)
113
+ - [::prefer — Disambiguate Overlapping Imports](#prefer--disambiguate-overlapping-imports)
114
+ - [::extend — Extend a Type Alias](#extend--extend-a-type-alias)
115
+ - [::rep — Constraint Representatives](#rep--constraint-representatives)
116
+ - [::curried — Curried Library Functions](#curried--curried-library-functions)
117
+ - [::hidden / ::private — Completion Visibility](#hidden--private--completion-visibility)
118
+ - [::ignore / ::ignore-file / ::ignore-function](#ignore--ignore-file--ignore-function)
119
+ - [Type System](#type-system)
120
+ - [Primitives](#primitives)
121
+ - [Calling Convention](#calling-convention)
122
+ - [Functions](#functions)
123
+ - [Arrays & Tuples](#arrays--tuples)
124
+ - [Records & Row Polymorphism](#records--row-polymorphism)
125
+ - [Union & String-Literal Types](#union--string-literal-types)
126
+ - [Generics & Higher-Kinded Types](#generics--higher-kinded-types)
127
+ - [Label Polymorphism](#label-polymorphism)
128
+ - [Type Aliases](#type-aliases)
129
+ - [Properties & Private Members](#properties--private-members)
130
+ - [Instance-Callable Values](#instance-callable-values)
131
+ - [Overloading](#overloading)
132
+ - [Picked Projection](#picked-projection)
133
+ - [Curry](#curry)
134
+ - [Pipe & Compose](#pipe--compose)
135
+ - [Type Narrowing](#type-narrowing)
136
+ - [Publishing types for an npm package](#publishing-types-for-an-npm-package)
137
+ - [1. Inline annotations (zero config)](#1-inline-annotations-zero-config)
138
+ - [2. Sidecar .hm files](#2-sidecar-hm-files)
139
+ - [3. Package globals](#3-package-globals)
140
+ - [Merge order](#merge-order)
141
+ - [Cross-package chaining](#cross-package-chaining)
142
+ - [Using a typed npm package (consumer side)](#using-a-typed-npm-package-consumer-side)
143
+ - [When signatures don't show up](#when-signatures-dont-show-up)
144
+ - [Ramda](#ramda)
145
+ - [Built-in Method Types](#built-in-method-types)
146
+ - [Array Methods](#array-methods)
147
+ - [String Methods](#string-methods)
148
+ - [Object Static Methods](#object-static-methods)
149
+ - [Promise Methods](#promise-methods)
150
+ - [Map Methods](#map-methods)
151
+ - [Set Methods](#set-methods)
152
+ - [Configuration](#configuration)
153
+ - [Configuration per folder (monorepos)](#configuration-per-folder-monorepos)
154
+ - [Enabling / disabling the language server](#enabling--disabling-the-language-server)
155
+ - [Project-file settings](#project-file-settings)
156
+ - [Command-Line Checker](#command-line-checker)
157
+ - [Diagnostic Codes Reference](#diagnostic-codes-reference)
158
+ - [Example: Full Workflow](#example-full-workflow)
159
+ - [License](#license)
160
+
161
+ ---
162
+
163
+ ## Getting Started
164
+
165
+ 1. Install the **HinMil** extension in VS Code.
166
+ 2. Open any `.js` or `.jsx` file.
167
+ 3. Add type annotations in comments using `::` syntax:
168
+
169
+ ```javascript
170
+ // lineTotal :: (Number, Number) -> Number
171
+ const lineTotal = (quantity, unitPrice) => quantity * unitPrice;
172
+ ```
173
+
174
+ That is the whole setup. The language server activates on the first JS file
175
+ you open and checks as you type.
176
+
177
+ To see it working first, clone
178
+ [hinmil-example](https://github.com/tureluren/hinmil-example): a few small
179
+ files, each with one deliberate type error, ready to open in VS Code.
180
+
181
+ Next steps, all optional:
182
+
183
+ - **A project configuration** (`hinmil.config.json`, or `"hinmil"` in
184
+ `package.json`) for shared type aliases (`globals`), diagnostic levels and
185
+ file selection — see [Configuration](#configuration). In a monorepo, each
186
+ application folder can have its own.
187
+ - **The command-line checker** for CI: `npm install --save-dev hinmil`, then
188
+ `npx hinmil .` — see [Command-Line Checker](#command-line-checker).
189
+ - **VS Code's built-in TypeScript extension** also analyses JavaScript and
190
+ shows its own hovers and diagnostics next to those of HinMil. See
191
+ [Using HinMil without the built-in TypeScript extension](#using-hinmil-without-the-built-in-typescript-extension).
192
+
193
+ ---
194
+
195
+
196
+ ## Type Annotations
197
+
198
+ Annotations are written in comments directly above declarations, using `::` to introduce the type signature:
199
+
200
+ ```javascript
201
+ // applyVat :: (Number, Number) -> Number
202
+ const applyVat = (amount, rate) => amount * (1 + rate);
203
+
204
+ // identity :: a -> a
205
+ const identity = (x) => x;
206
+
207
+ // invoiceTotal :: [Number] -> Number
208
+ const invoiceTotal = (amounts) => amounts.reduce((a, b) => a + b, 0);
209
+ ```
210
+
211
+ An annotation (or a directive) takes the **whole** comment line: text after
212
+ the type is read as part of it. Put a remark on a line of its own, above:
213
+
214
+ ```javascript
215
+ // Gross amount, rounded to cents:
216
+ // grossOf :: Number -> Number
217
+ const grossOf = (net) => Math.round (net * 1.21);
218
+ ```
219
+
220
+ Block comments work too, also over several lines (the annotation runs to
221
+ the end of its paragraph, so a long signature can be wrapped):
222
+
223
+ ```javascript
224
+ /* invoiceTotal ::
225
+ ([{ quantity :: Number, unitPrice :: Number }], Number) -> Number */
226
+ const invoiceTotal = (lines, vatRate) =>
227
+ lines.reduce ((sum, line) => sum + line.quantity * line.unitPrice, 0) * (1 + vatRate);
228
+ ```
229
+
230
+ ### Method Annotations
231
+
232
+ Use `~>` for instance method receivers, and annotate constructors with the type they produce:
233
+
234
+ ```javascript
235
+ // Box :: a -> Box a
236
+ const Box = (value) => ({
237
+ // Box#value :: Box a ~> a
238
+ value,
239
+
240
+ // Box#map :: Box a ~> (a -> b) -> Box b
241
+ map(fn) { return Box(fn(this.value)); },
242
+ });
243
+
244
+ // Box.of :: a -> Box a
245
+ Box.of = (value) => Box(value);
246
+ ```
247
+
248
+ A constructor annotation declares the type, not its fields: give every
249
+ field you read through `this` (or on a value of the type) its own
250
+ `Type#field` annotation.
251
+
252
+ Named method and static annotations can also be placed above any declaration:
253
+
254
+ ```javascript
255
+ // Box :: a -> Box a
256
+ const Box = (value) => ({
257
+ value,
258
+
259
+ map(fn) { return Box(fn(this.value)); },
260
+ });
261
+
262
+ Box.of = (value) => Box(value);
263
+
264
+ // Box#map :: Box a ~> (a -> b) -> Box b
265
+ // Box.of :: a -> Box a
266
+ const boxMap = (fn, box) => Box(fn(box.value));
267
+ ```
268
+
269
+ ---
270
+
271
+ ## Hover
272
+
273
+ Hover over an identifier to see its inferred type. This works for variables
274
+ (`Number`, `String`, `[Number]`), functions (the full signature), methods
275
+ (receiver and parameter types), constrained types
276
+ (`Functor f => (a -> b) -> f a -> f b`), and narrowed types inside type guard
277
+ branches — hovering the same variable in different branches shows different
278
+ types.
279
+
280
+ The display style is configurable: `pretty` shows readable variable names
281
+ (`a`, `b`, `c`), `raw` shows the internal ones.
282
+
283
+ ---
284
+
285
+ ## Diagnostics
286
+
287
+ Type errors show up in the editor as you type. The extension reports type
288
+ mismatches, infinite types, missing record properties, unbound variables,
289
+ syntax errors in annotations, unresolved imports, constraint violations, and
290
+ curry arity problems — see the [Diagnostic Codes Reference](#diagnostic-codes-reference)
291
+ for the full list.
292
+
293
+ ```javascript
294
+ // applyVat :: (Number, Number) -> Number
295
+ const applyVat = (amount, rate) => amount * (1 + rate);
296
+
297
+ applyVat("21%", 0.21); // Cannot unify String with Number
298
+ ```
299
+
300
+ Every diagnostic category can be set to error, warning, information, hint, or
301
+ off — see [Configuration](#configuration).
302
+
303
+ ---
304
+
305
+ ## Autocompletion
306
+
307
+ Completions are driven by the inferred types, so the suggestions after a dot
308
+ are the methods that actually exist for that type. This covers identifiers in
309
+ scope, methods and properties after `.`, import specifiers from other files,
310
+ destructuring patterns, and registered methods inside sumtype factory
311
+ functions.
312
+
313
+ ```javascript
314
+ const amounts = [120.5, 89.99, 42];
315
+ amounts. // ← suggests: map, filter, reduce, find, length, ...
316
+ ```
317
+
318
+ Each completion item shows the inferred type in the detail panel.
319
+
320
+ ---
321
+
322
+ ## Signature Help
323
+
324
+ When calling a function, the expected parameter types appear with the current
325
+ parameter highlighted:
326
+
327
+ ```javascript
328
+ // applyVat :: (Number, Number) -> Number
329
+ const applyVat = (amount, rate) => amount * (1 + rate);
330
+
331
+ applyVat(100, |) // ← shows: applyVat(Number, Number) -> Number
332
+ // with the second Number highlighted
333
+ ```
334
+
335
+ Works with multi-line calls and nested function invocations.
336
+
337
+ ---
338
+
339
+ ## Code Actions
340
+
341
+ Quick fixes available via the lightbulb menu or `Ctrl+.`:
342
+
343
+ | Action | Description |
344
+ |--------|-------------|
345
+ | **Add missing annotation** | Generates an inferred `::` type signature for functions without one |
346
+ | **Rename to match annotation** | Fixes name mismatches between annotation and declaration |
347
+ | **Add ::types directive** | Suggests importing types from other files |
348
+ | **Add constraint to the enclosing signature** | When a call needs a constraint the enclosing function does not declare (`Missing constraint 'Monoid (f a)' required here`), adds it to that function's annotation |
349
+ | **Ignore line** | Adds `// ::ignore` to suppress diagnostics on the next line |
350
+ | **Ignore file** | Adds `// ::ignore-file` to suppress all diagnostics in the file |
351
+
352
+ ---
353
+
354
+ ## Go to definition
355
+
356
+ - **Types and annotations** — a type name in an annotation (or a `::narrow` / `::constraint` directive) jumps to its alias, constructor or constraint declaration: in the file, in `globals.hm`, or in a package's `.hm` sidecar. A function name in its own annotation jumps to the code. A `::types` path jumps to the file.
357
+ - **Code** (setting `hinmil.navigation.definitions`):
358
+ - a module path jumps to the file: `import … from "x"`, `export … from "x"`, `require ("x")`, `require.resolve ("x")`, `import ("x")`;
359
+ - an imported name jumps to its real declaration, from the import statement and from every use: ESM default, named (also `"string" as name`) and namespace imports (`ns.x`), CommonJS `require` (whole module, destructured, `require ("x").y`), Babel's `_interopRequireDefault (require ("x"))`, `await import ("x")`;
360
+ - re-exports are followed until the declaration: `export { x }`, `export { x as y } from`, `export *`, `export * as ns`, `module.exports = require ("x")`;
361
+ - in the target module it understands `export const/function/class`, `export default`, `module.exports = value`, `module.exports = { a, b: c }`, `exports.a = …`, `module.exports = X; X.a = …`, and `Object.defineProperty (exports, "a", …)`;
362
+ - modules resolve like Node: relative paths with or without extension (`.js`, `.mjs`, `.cjs`, `.jsx`) or `/index`, packages via `exports`, `main`/`module` and subpaths. A package with an `.hm` sidecar opens its JavaScript, not the sidecar;
363
+ - names declared in the same file jump to their binding (scope-aware, like Find References).
364
+
365
+ With `auto` (default) HinMil does this only when VS Code's built-in **TypeScript and JavaScript Language Features** extension is not active, so you never get the same result twice. AMD (`define ([…], function (…) {})`) is not supported.
366
+
367
+ The clicked text is one link: a whole module path (`"../../services/users"`) or a whole identifier, not one link per word.
368
+
369
+ ### Using HinMil without the built-in TypeScript extension
370
+
371
+ VS Code ships a built-in extension, **TypeScript and JavaScript Language Features**, that also analyses JavaScript. Next to HinMil it adds a second hover, its own (TypeScript) diagnostics and completions, and suggestions that do not know HM annotations. In a project that relies on HinMil you can switch it off for that workspace only:
372
+
373
+ 1. Open the Extensions view (`Ctrl+Shift+X`, macOS `Cmd+Shift+X`).
374
+ 2. Type `@builtin typescript` in the search box. Alternatively, run **Extensions: Show Built-in Extensions** from the Command Palette and scroll to the *Features* group.
375
+ 3. On **TypeScript and JavaScript Language Features**, click the gear icon and choose **Disable (Workspace)**.
376
+ 4. Reload the window (**Developer: Reload Window**).
377
+
378
+ Turn it back on the same way with **Enable (Workspace)**.
379
+
380
+ Good to know:
381
+
382
+ - **HinMil notices the change.** With `hinmil.navigation.definitions: "auto"` (default), HinMil takes over go to definition for module paths, imported names and local names as soon as the extension is disabled, and hands it back when you enable it again. No setting needs to change.
383
+ - **The choice is stored per workspace in VS Code itself**, not in `.vscode/settings.json`. You cannot commit it: every team member who wants this does the steps above.
384
+ - **It also switches off TypeScript support for `.ts`/`.tsx` files** in that workspace. Do not do this in a workspace that also contains TypeScript code you want to edit.
385
+ - **What you lose:** features only the TypeScript extension offers, such as Find References and Rename across files (HinMil does both within one file), updating imports when you move a file, Organize Imports, refactorings (extract function, …), workspace symbol search (`Ctrl+T`), call hierarchy, inlay hints and its formatter. HinMil still provides hover, diagnostics, completion (including auto-imports), signature help, go to definition, document symbols and code actions.
386
+ - **A lighter alternative:** keep the extension and only silence its diagnostics with `"js/ts.validate.enabled": false` (older VS Code versions: `"javascript.validate.enable": false`) in `.vscode/settings.json`. You keep all TypeScript features, but also its hover and completions next to those of HinMil.
387
+
388
+ ---
389
+
390
+ ## Find References & Rename
391
+
392
+ - **Find All References** — locates every use of an identifier, accounting for scope and shadowing
393
+ - **Rename Symbol** — renames across all references in a file, including inside annotations
394
+
395
+ The engine is scope-aware, so shadowed variables in nested blocks are handled correctly.
396
+
397
+ ---
398
+
399
+ ## Document Symbols
400
+
401
+ The outline view lists all top-level declarations with their inferred types:
402
+
403
+ - **Functions** — shown with their full type signature
404
+ - **Constructors** — uppercase-named functions displayed as constructors
405
+ - **Variables** — non-function declarations
406
+ - **Sum type declarations** — shown as enums with variant children
407
+
408
+ ---
409
+
410
+ ## Syntax Highlighting
411
+
412
+ HM type annotations inside JS comments are syntax-highlighted automatically:
413
+
414
+ - Type constructors (`Number`, `String`, `Maybe`, etc.)
415
+ - Type variables (`a`, `b`, `f`)
416
+ - Arrows (`->`, `~>`, `=>`)
417
+ - Directive keywords (`::types`, `::constraint`, `::narrow`, `::prefer`, …)
418
+
419
+ Can be toggled on/off via `hinmil.syntaxHighlighting.enabled`.
420
+
421
+ ![Typing HinMil annotations in VS Code: the signatures in the comments are highlighted as types while you type](images/highlighting.gif)
422
+
423
+ ---
424
+
425
+ ## Sum Types
426
+
427
+ Sum types (tagged unions, algebraic data types) are a core part of the
428
+ type system, and they need no directive. Any annotation whose right-hand
429
+ side is a `|`-separated list of capitalised variant names declares one:
430
+
431
+ ```javascript
432
+ // Maybe :: Just a | Nothing
433
+ ```
434
+
435
+ This registers the type constructor `Maybe a`, links the variants
436
+ `Just` and `Nothing` to it, and makes `Maybe` usable in every signature
437
+ in the file (or project-wide, via `globals.hm` or `::types`).
438
+
439
+ ### Variants and constructors
440
+
441
+ The declaration names the variants, but the engine does not guess what
442
+ their constructors take — annotate each constructor explicitly. If one
443
+ is missing, the engine shows an info diagnostic with the exact
444
+ annotation to add (e.g. *"Variant 'Just' is missing a constructor
445
+ annotation. Add: `// Just :: a -> Maybe a`"*).
446
+
447
+ ```javascript
448
+ // Maybe :: Just a | Nothing
449
+
450
+ class Just {
451
+ // Just :: a -> Maybe a
452
+ constructor(value) { this.value = value; }
453
+
454
+ // Maybe#map :: Maybe a ~> (a -> b) -> Maybe b
455
+ map(fn) { return new Just(fn(this.value)); }
456
+ }
457
+
458
+ // Nothing :: Maybe a
459
+ class Nothing {
460
+ map(_fn) { return new Nothing(); }
461
+ }
462
+ ```
463
+
464
+ Note that both `new Just(1)` and `new Nothing()` are typed as
465
+ `Maybe Number` / `Maybe a` — the variant classes construct values of
466
+ the *parent* type.
467
+
468
+ ### Variant methods
469
+
470
+ A method annotated on the parent type (`Maybe#map`) applies to all
471
+ variants. Each variant is expected to implement it; a variant that
472
+ doesn't gets an info diagnostic (code 6002) on the declaration comment.
473
+ Method calls dispatch on the parent type, so a `Maybe Number` value has
474
+ `.map` regardless of which variant it holds at runtime.
475
+
476
+ ### Factory functions instead of classes
477
+
478
+ Classes are not required. A capitalised factory function returning a
479
+ record works the same way, and registered methods are offered as
480
+ completions inside the returned record literal:
481
+
482
+ ```javascript
483
+ // Result :: Ok a | Err e
484
+
485
+ // Ok :: a -> Result a e
486
+ const Ok = (value) => ({
487
+ tag: 'Ok',
488
+ value,
489
+ });
490
+
491
+ // Err :: e -> Result a e
492
+ const Err = (error) => ({
493
+ tag: 'Err',
494
+ error,
495
+ });
496
+ ```
497
+
498
+ ### Multi-line declarations and complex fields
499
+
500
+ Variant fields can be more than bare type variables: parenthesised type
501
+ applications and inline record groups are accepted. Long declarations
502
+ may span multiple comment lines, joined by a trailing or leading `|`:
503
+
504
+ ```javascript
505
+ // Response :: Success { status :: Number, body :: String }
506
+ // | Failure (Object String String)
507
+
508
+ // Success :: { status :: Number, body :: String } -> Response
509
+ // Failure :: (Object String String) -> Response
510
+ ```
511
+
512
+ ### Phantom variant parameters
513
+
514
+ A type parameter that a variant does not use stays polymorphic when
515
+ that variant is produced. `new Nothing()` is `Maybe a`, not
516
+ `Maybe Unknown` — it unifies with whatever `Maybe` the surrounding code
517
+ expects:
518
+
519
+ ```javascript
520
+ // findDiscount :: Number -> Maybe Number
521
+ const findDiscount = (total) =>
522
+ total > 500 ? new Just(total * 0.05) : new Nothing();
523
+ ```
524
+
525
+ ### Narrowing on variants
526
+
527
+ Predicates can narrow a value to a single variant via
528
+ [`::narrow`](#narrow--type-predicates), and in the negative branch the
529
+ type narrows to the union of the remaining variants:
530
+
531
+ ```javascript
532
+ // Maybe :: Just a | Nothing
533
+ // ::narrow Just
534
+ // isJust :: a -> Boolean
535
+ const isJust = (m) => m.tag === 'Just';
536
+ ```
537
+
538
+ Sum type declarations also show up in the document outline as enums
539
+ with their variants as children.
540
+
541
+ ---
542
+
543
+ ## JSX & React
544
+
545
+ JSX works out of the box in `.js` and `.jsx` files. Detection is
546
+ content-based, not extension-based: many modern setups (Vite, Next.js,
547
+ create-react-app) keep JSX in plain `.js` files, and those are handled
548
+ identically — no configuration, renaming or pragma needed. Imports resolve
549
+ across both extensions too (`import App from './App'` finds `App.js`,
550
+ `App.jsx` or `index.jsx`).
551
+
552
+ Every JSX expression
553
+ (`<App />`, `<div>…</div>`, `<>…</>`) has the built-in type `ReactElement`,
554
+ and a component element is type-checked as a call: `<Greeting name={user} />`
555
+ checks the props record `{ name: user }` (plus `children`, when present)
556
+ against the component's parameter — a wrong, missing or misspelled prop is
557
+ reported on the exact attribute, just like a wrong function argument.
558
+
559
+ Lowercase host elements (`<div>`, `<button>`) check their attributes against a
560
+ builtin DOM catalogue: `className`, `id` and friends must be strings, `style`
561
+ must be an object (`style="color:red"` is an error), event handlers
562
+ (`onClick`, `onChange`, …) must be functions, and per-tag attributes like
563
+ `input`'s `checked` (`Boolean`), `label`'s `htmlFor` or `td`'s `colSpan`
564
+ (`Number`) are typed too — with completion for all of them inside the open
565
+ tag. Inside `style={{ … }}` the object keys complete against a catalogue of
566
+ ~170 CSS properties (`color`, `flexDirection`, `gridTemplateColumns`, …);
567
+ the values and unknown keys stay unchecked, so CSS custom properties
568
+ (`'--brand': …`) and vendor prefixes are always fine. Unknown attribute names
569
+ (`data-*`, `aria-*`, web-component attributes) are left
570
+ unchecked rather than flagged. React's `key` accepts a `String` or `Number`
571
+ and `ref` accepts a ref object or callback ref on any element; both are
572
+ React-managed and therefore stripped before a component's props record is
573
+ checked, so `<Todo key={it.id} …/>` never complains about an unexpected
574
+ `key` field.
575
+
576
+ React's own API is typed out of the box: the extension bundles signature
577
+ files for `react` and `react-dom` ([hm-types-builtin/](hm-types-builtin/)),
578
+ so `import { useState } from 'react'` and
579
+ `import { createRoot } from 'react-dom/client'` resolve typed signatures
580
+ with zero configuration. Two properties keep this future-proof:
581
+
582
+ - **Your project always wins.** A project `.hm` file for the same package
583
+ (an `overrides` entry or a conventional `hm-types/react.hm`) merges with
584
+ the bundled layer *per export name*: names you declare override the
585
+ bundled signature, names you don't keep working from the bundle. See
586
+ [sample/react.hm](sample/react.hm) for a merge demo that adds React 19
587
+ APIs on top of the bundled catalogue.
588
+ - **The bundle can never be worse than no typings.** Importing a name the
589
+ bundled catalogue doesn't know (say React ships a new hook) binds it to
590
+ `Any` instead of erroring — exactly what an untyped package would do.
591
+
592
+ A larger example — every annotation below is checked against the JSX usage:
593
+
594
+ ```jsx
595
+ import { useState, useMemo, createContext, useContext } from 'react';
596
+
597
+ const ThemeContext = createContext('light'); // Context String
598
+
599
+ // Badge :: { label :: String } -> ReactElement
600
+ const Badge = ({ label }) => <span className="badge">{label}</span>;
601
+
602
+ // Children arrive as the `children` prop, like in React itself.
603
+ // Card :: { title :: String, children :: a } -> ReactElement
604
+ const Card = ({ title, children }) => {
605
+ const theme = useContext(ThemeContext); // theme :: String
606
+ return (
607
+ <section className={'card-' + theme}>
608
+ <h2>{title}</h2>
609
+ {children}
610
+ </section>
611
+ );
612
+ };
613
+
614
+ // Todo :: { id :: Number, text :: String, done :: Boolean } -> ReactElement
615
+ const Todo = ({ id, text, done }) => (
616
+ <li key={id} className={done ? 'done' : 'open'}>{text}</li>
617
+ );
618
+
619
+ // TodoApp :: { items :: [{ id :: Number, text :: String, done :: Boolean }] } -> ReactElement
620
+ const TodoApp = ({ items }) => {
621
+ const [filter, setFilter] = useState('all'); // filter :: String
622
+ const open = useMemo(() => items.filter((it) => !it.done), [items]);
623
+
624
+ return (
625
+ <ThemeContext.Provider value="dark">
626
+ <Card title="Tasks">
627
+ <Badge label={filter} />
628
+ {open.length === 0 ? (
629
+ <p>Nothing to do!</p>
630
+ ) : (
631
+ <ul>{open.map((it) => <Todo id={it.id} text={it.text} done={it.done} />)}</ul>
632
+ )}
633
+ <button onClick={() => setFilter('open')}>open only</button>
634
+ </Card>
635
+ </ThemeContext.Provider>
636
+ );
637
+ };
638
+ ```
639
+
640
+ What gets caught here:
641
+
642
+ - `<Badge label={3} />` — `Cannot unify 'Number' with 'String'` on the attribute;
643
+ - `<Todo id={it.id} />` — `Missing required fields 'text', 'done' on argument`;
644
+ - `<ThemeContext.Provider value={42}>` — the Provider's `value` must match the
645
+ context's type (`String` here, fixed by `createContext('light')`);
646
+ - `setFilter(1)` — the `useState` setter only accepts a `String` or an updater
647
+ function;
648
+ - typos inside braces — `{items.mapp(…)}` — are ordinary member diagnostics.
649
+
650
+ Spread props type-check like object spreads (`<Todo {...defaults} />`), class
651
+ components (`class Timer extends Component`) are instantiated with `new`
652
+ behind the scenes, and unannotated components simply get inferred props.
653
+
654
+ Refs and the modern API are covered by the same bundled typings: the
655
+ `useRef(null)` DOM idiom works without complaints (`inputRef.current.focus()`
656
+ after mounting), `forwardRef((props, ref) => …)` yields an ordinary component
657
+ whose props are still checked, and `createRef`, `useImperativeHandle`,
658
+ `useReducer`, `useLayoutEffect`, `useId`, `useTransition`, `useDeferredValue`,
659
+ `useSyncExternalStore`, `memo`, `lazy`, `startTransition`, `Suspense` and
660
+ `StrictMode` are all typed — see [sample/jsx/refs.jsx](sample/jsx/refs.jsx).
661
+
662
+ Browser globals — `document`, `window`, `navigator`, `localStorage`,
663
+ `sessionStorage` — are typed out of the box: they carry nominal types
664
+ (`Document`, `Window`, `Navigator`, `Storage`) with a compact catalogue of
665
+ the everyday DOM surface, so `document.getElementById('root')` returns an
666
+ `Element`, its members complete and hover, `el.textContent = 42` is caught,
667
+ and event listeners see a typed `Event` (`e.clientX`, `e.key`,
668
+ `e.target.value`). Anything *outside* the catalogue silently resolves to
669
+ `Any` — the full DOM never false-positives. The type names are usable in
670
+ your own annotations too (`highlight :: Element -> Void`). Two settings
671
+ control this: `hinmil.dom.globalTypes` (default on; turn it off if your
672
+ project defines its own `Element`/`Document` types — globals revert to
673
+ `Any`) and `hinmil.dom.strictNulls` (default off; when on, lookups that can
674
+ miss — `getElementById`, `querySelector`, `getAttribute`,
675
+ `localStorage.getItem`, … — return `T | Null`). A local binding named
676
+ `document`, `window`, … still shadows the corresponding browser global
677
+ with full strict checking, a declaration in your project globals file
678
+ (e.g. `globals.hm`) replaces a builtin entirely, and a
679
+ `::global Element#… :: …` directive extends the catalogue per type —
680
+ see [sample/browser.js](sample/browser.js).
681
+
682
+ The Fetch API is typed for every project (browser, node, workers) with no
683
+ configuration: `fetch` is `(u, o?) -> Promise e Response`, and `Response`
684
+ carries `ok`, `status`, `json()`, `text()`, … — so
685
+ `fetch('/api').then(r => r.status.toUpperCase())` is caught.
686
+
687
+ Other React-ecosystem packages are one `.hm` file away: the same override
688
+ mechanism types anything. [sample/redux/](sample/redux/) shows classic
689
+ Redux, Redux Toolkit and the react-redux hooks typed by three small
690
+ signature files in [sample/hm-types/](sample/hm-types/) — plain packages as
691
+ conventional `hm-types/<pkg>.hm` stubs, the scoped `@reduxjs/toolkit` wired
692
+ up through an `overrides` entry.
693
+
694
+ Runnable examples live in [sample/jsx/](sample/jsx/) and
695
+ [sample/readme/jsx.jsx](sample/readme/jsx.jsx).
696
+
697
+ ### Optional props
698
+
699
+ Two conventions are supported, both fully checked:
700
+
701
+ ```jsx
702
+ // FP-style: the prop is required, but the value may be Nothing.
703
+ // UserBadge :: { name :: String, nickname :: Maybe String } -> ReactElement
704
+ const UserBadge = ({ name, nickname }) => (
705
+ <span>{name} ({nickname.getOrElse('no nickname')})</span>
706
+ );
707
+ const a = <UserBadge name="Ada" nickname={new Just('Countess')} />;
708
+ const b = <UserBadge name="Ada" nickname={new Nothing()} />; // ok
709
+ const c = <UserBadge name="Ada" nickname="Countess" />; // error: String vs Maybe String
710
+
711
+ // `| Undefined`: the prop may be omitted on the tag entirely.
712
+ // Tooltip :: { text :: String, delay :: (Number | Undefined) } -> ReactElement
713
+ const Tooltip = ({ text, delay = 300 }) => <span data-delay={delay}>{text}</span>;
714
+ const d = <Tooltip text="Save" />; // ok — delay omitted
715
+ const e = <Tooltip text="Save" delay="long" />; // error: String vs Number | Undefined
716
+ ```
717
+
718
+ Missing-prop diagnostics carry code `1008` and follow the
719
+ `hinmil.diagnostics.missingRecordFields` setting (default `error`). Prop
720
+ completion inside an open tag marks `| Undefined` props as `(optional)`.
721
+ See [sample/jsx/optional-props.jsx](sample/jsx/optional-props.jsx).
722
+
723
+ ---
724
+
725
+ ## Directives
726
+
727
+ > All directives use the `::` prefix inside a comment, e.g.
728
+ > `// ::constraint …`.
729
+
730
+ ### `::constraint` — Type Classes
731
+
732
+ Type class constraints come in two flavours:
733
+
734
+ **Nominal (method dictionary)** — required methods are listed in a
735
+ record under the constraint variable:
736
+
737
+ ```javascript
738
+ // ::constraint Functor f { f :: { map :: f a ~> (a -> b) -> f b } }
739
+ // ::constraint Monad m { m :: { chain :: m a ~> (a -> m b) -> m b, of :: a -> m a } }
740
+ ```
741
+
742
+ **Structural-union (multi-parameter)** — body lists `var :: Type | Type | …`
743
+ clauses; satisfied by any value whose type unifies with one of the
744
+ alternatives. Multiple header parameters are supported:
745
+
746
+ ```javascript
747
+ // ::constraint Runnable t r { r :: (a -> t) | t }
748
+ // ::constraint Indexed r e s { r :: [e] | Map s e, s :: Number | String }
749
+ ```
750
+
751
+ A constraint builds on constraints declared before it by naming them in its
752
+ body (a bare constraint name instead of a record):
753
+
754
+ ```javascript
755
+ // ::constraint Pointed f { f :: Functor, f :: { of :: a -> f a } }
756
+ // ::constraint Monad m { m :: Applicative, m :: Chain }
757
+ ```
758
+
759
+ A value then has to satisfy the named constraints as well, and a
760
+ signature that requires `Pointed f` may use `map` on an `f a`.
761
+
762
+ Use constraints in signatures with `=>`:
763
+
764
+ ```javascript
765
+ // fmap :: Functor f => ((a -> b), f a) -> f b
766
+ // limit :: Runnable Number r => r -> Limit
767
+ ```
768
+
769
+ A full worked example — the constraint is discharged by checking that
770
+ the argument's type actually has the required method:
771
+
772
+ ```javascript
773
+ // ::constraint Semigroup s { s :: { concat :: s ~> s -> s } }
774
+
775
+ // joinAll :: Semigroup s => (s, [s]) -> s
776
+ const joinAll = (init, xs) => xs.reduce((acc, x) => acc.concat(x), init);
777
+
778
+ const ref = joinAll('INV-', ['2026', '-001']); // String has concat — fine
779
+ const rows = joinAll([1], [[2], [3]]); // Array has concat — fine
780
+ const bad = joinAll(5, [6]);
781
+ // Type 'Number' does not satisfy constraint 'Semigroup': missing method 'concat'
782
+ ```
783
+
784
+ ### `::narrow` — Type Predicates
785
+
786
+ Define type guard functions that narrow types in conditionals. Two
787
+ forms are supported:
788
+
789
+ ```javascript
790
+ // Narrow to a primitive
791
+ // ::narrow String
792
+ // isString :: a -> Boolean
793
+ const isString = (x) => typeof x === 'string';
794
+
795
+ // Narrow to a sumtype variant
796
+ // Maybe :: Just a | Nothing
797
+ // ::narrow Just
798
+ // isJust :: a -> Boolean
799
+ const isJust = (m) => m.tag === 'Just';
800
+ ```
801
+
802
+ Requirements:
803
+ - The predicate function must return `Boolean`
804
+ - The first parameter must be a type variable (`a`)
805
+ - The narrowed type is specified by the `::narrow` directive
806
+
807
+ In use, both branches narrow. Here `q` is `Number` inside the positive
808
+ branch and `String` in the negative one, so both method calls check out:
809
+
810
+ ```javascript
811
+ // ::narrow Number
812
+ // isCount :: a -> Boolean
813
+ const isCount = (x) => Number.isInteger(x) && x >= 0;
814
+
815
+ // quantityLabel :: (Number | String) -> String
816
+ const quantityLabel = (q) => isCount(q) ? q.toFixed(0) : q.trim();
817
+ ```
818
+
819
+ `typeof x === 'string' | 'number' | 'boolean' | 'bigint' | 'symbol'`
820
+ narrows automatically — no `::narrow` annotation is needed for those.
821
+
822
+ ### `::types` — Cross-File Types
823
+
824
+ Import type definitions from other files or packages without runtime
825
+ imports:
826
+
827
+ ```javascript
828
+ // Types from ./demo.js (or ./demo.hm when there is no demo.js):
829
+ // ::types ./demo
830
+
831
+ // Types from an npm package's hinmil sidecar (also scoped: @scope/pkg):
832
+ // ::types fantasy-box
833
+ ```
834
+
835
+ A `::types` target also brings the `::types` of that file with it, so a
836
+ shared `types.js` can itself pull in other type files.
837
+
838
+ A typical split: keep shared aliases in one file, reference them
839
+ everywhere else. Note that `::types` imports *types only* — value
840
+ bindings (functions, classes) still need a regular `import`/`require`:
841
+
842
+ ```javascript
843
+ // invoice-types.js
844
+ // LineItem :: { description :: String, quantity :: Number, unitPrice :: Number }
845
+ // VatRate :: Number
846
+ ```
847
+
848
+ ```javascript
849
+ // main.js
850
+ // ::types ./invoice-types
851
+
852
+ // lineTotal :: LineItem -> Number
853
+ const lineTotal = (item) => item.quantity * item.unitPrice;
854
+
855
+ // applyVat :: (Number, VatRate) -> Number
856
+ const applyVat = (amount, rate) => amount * (1 + rate);
857
+ ```
858
+
859
+ **Types travel with imports.** Importing a value from a JavaScript
860
+ module (`import` or `require`) also makes the type names visible in that
861
+ module available: its free-standing aliases (`// LineItem :: { … }`, not
862
+ attached to a declaration), the targets of its `::types` directives, and,
863
+ recursively, the types of its own imports. So you only need `::types`
864
+ for type-only use — a file that names `LineItem` but imports nothing
865
+ from `invoice-types.js`. When two imports provide the same name, the
866
+ nearer one wins; a local declaration always wins. An annotation on a
867
+ declaration (`// lineTotal :: LineItem -> Number`) is a value annotation
868
+ and is not exported as a type name.
869
+
870
+ ### `::global` — Extend Built-in Types
871
+
872
+ Despite the name, `::global` does not declare global *variables* — it
873
+ registers methods and statics on types (typically prototype extensions
874
+ the checker cannot see). The "global" refers to the *reach* of the
875
+ declaration: it applies to every file in the project scope that loads it
876
+ (the folder with the configuration, and everything below it).
877
+ Instance methods use `Type#method` with a `~>` receiver; statics use
878
+ `Type.method`:
879
+
880
+ ```javascript
881
+ // ::global Array#ap :: [a] ~> [a -> b] -> [b]
882
+ // ::global Array.empty :: () -> [a]
883
+ ```
884
+
885
+ `::global` is read from your project's globals file(s) (e.g.
886
+ `globals.hm`, or whatever `hinmil.globals` points at — see
887
+ [Configuration](#configuration)), and the declarations then apply to
888
+ every file in the workspace.
889
+
890
+ ### `::prefer` — Disambiguate Overlapping Imports
891
+
892
+ When two packages export the same name (e.g. both expose `Prop`),
893
+ declare which source to prefer in the current file:
894
+
895
+ ```javascript
896
+ // Both sqlkit and another dependency publish a `Prop`:
897
+ // ::types sqlkit
898
+ // ::types other-orm
899
+
900
+ // ::prefer Prop from sqlkit
901
+
902
+ // Several names at once:
903
+ // ::prefer Prop, Table from sqlkit
904
+ ```
905
+
906
+ The directive only affects the file it appears in, so different files
907
+ can resolve the same name to different packages.
908
+
909
+ ### `::extend` — Extend a Type Alias
910
+
911
+ Append alternatives to an existing union alias without redefining it. This is
912
+ mainly useful when the alias comes from a package sidecar and you want to
913
+ widen it locally (or in an override sidecar):
914
+
915
+ ```javascript
916
+ // Selector :: String | Prop a
917
+
918
+ // ::extend Selector Limit
919
+ // Selector is now String | Prop a | Limit
920
+ ```
921
+
922
+ String-literal branches work too — handy for widening a status union
923
+ that a library defined too narrowly:
924
+
925
+ ```javascript
926
+ // PaymentMethod :: 'cash' | 'card'
927
+
928
+ // ::extend PaymentMethod 'voucher'
929
+
930
+ // pmLabel :: PaymentMethod -> String
931
+ const pmLabel = (m) => m;
932
+ const ok = pmLabel('voucher'); // fine — 'voucher' is now part of the union
933
+ ```
934
+
935
+ Directives stack — each `::extend` adds further branches. Extending a
936
+ non-union alias turns it into a union; extending an unknown name declares a
937
+ new alias.
938
+
939
+ ### `::rep` — Constraint Representatives
940
+
941
+ Declare that a locally annotated method represents a constraint's like-named
942
+ method when discharging that constraint. `Type#method` registers an instance
943
+ method (with a `~>` receiver), `Type.method` a static one. The signature
944
+ must follow directly below the directive.
945
+
946
+ Useful when a type satisfies a constraint in spirit but the checker cannot
947
+ see the method — e.g. `Array` has no built-in `empty`, so a `Monoid`
948
+ constraint would reject it:
949
+
950
+ ```javascript
951
+ // ::constraint Monoid m { m :: { empty :: () -> m } }
952
+
953
+ // ::rep Monoid Array.empty
954
+ // Array.empty :: () -> Array a
955
+
956
+ // orEmpty :: Monoid m => m -> m
957
+ const orEmpty = (x) => x;
958
+
959
+ const r = orEmpty([1, 2]); // fine — without the ::rep this reports:
960
+ // Type 'Array' does not satisfy constraint 'Monoid': missing method 'empty'
961
+ ```
962
+
963
+ ### `::curried` — Curried Library Functions
964
+
965
+ Only in `.hm` files. `::curried` directly above a declaration lets that
966
+ function take its arguments in any grouping, the way the functions of Ramda
967
+ and similar libraries do. One `::curried` covers the overload lines of the
968
+ name below it:
969
+
970
+ ```
971
+ // fnkit.hm
972
+ ::curried
973
+ map :: (a -> b) -> [a] -> [b]
974
+ map :: (a -> b) -> Object String a -> Object String b
975
+ ::curried
976
+ subtract :: Number -> Number -> Number
977
+ negate :: Number -> Number
978
+ ```
979
+
980
+ ```javascript
981
+ map (f, xs); // all at once
982
+ map (f) (xs); // one at a time
983
+ F.map (f, xs); // through `import * as F from "fnkit"`
984
+ ```
985
+
986
+ Without the directive, a curried signature `a -> b -> c` takes one
987
+ argument per call, as a plain `a => b => c` does. A `::curried` that is
988
+ not directly above a function of at least two arguments is reported as a
989
+ warning in the `.hm` file.
990
+
991
+ In a JavaScript file `::curried` is reported (HM5002): there the code
992
+ shows whether a function is curried. A function built with a curry helper
993
+ accepts any grouping as soon as the helper has a curry signature, also
994
+ when the helper comes from a `.hm` file or a namespace import
995
+ (`R.curry (…)`), and also when the function carries its own annotation:
996
+
997
+ ```javascript
998
+ // discounted :: Number -> Number -> Number
999
+ const discounted = curry ((pct, price) => price * (1 - pct / 100));
1000
+ discounted (10, 250); // fine
1001
+ discounted (10) (250); // fine
1002
+ ```
1003
+
1004
+ A hand-written `pct => price => …` really needs one argument per call,
1005
+ and HinMil keeps checking it that way.
1006
+
1007
+ An argument whose type is `Placeholder` (declare `Placeholder ::
1008
+ Placeholder` and `__ :: Placeholder`) leaves its parameter open:
1009
+ `subtract (__, 10)` is `Number -> Number`.
1010
+
1011
+ ### `::hidden` / `::private` — Completion Visibility
1012
+
1013
+ Keep a method or property out of completion lists. Place the directive on the
1014
+ line above the annotation, or use the standalone form with a qualified name:
1015
+
1016
+ ```javascript
1017
+ // ::hidden
1018
+ // Invoice#recalculate :: Invoice ~> () -> ()
1019
+
1020
+ // ::hidden Invoice#internalId
1021
+ // ::private Invoice#cache
1022
+ ```
1023
+
1024
+ `::hidden` keeps a member out of every completion list; `::private` keeps it
1025
+ out too, except after `this.` — inside the type's own methods, where it is
1026
+ used.
1027
+ Several directives can be stacked above one chained annotation; a
1028
+ `::hidden <Name>` argument targets that specific member.
1029
+
1030
+ ### `::ignore` / `::ignore-file` / `::ignore-function`
1031
+
1032
+ Suppress diagnostics selectively:
1033
+
1034
+ ```javascript
1035
+ // ::ignore
1036
+ const x = untypedFunction(42); // diagnostics on the next line are suppressed
1037
+
1038
+ // ::ignore-function
1039
+ const legacy = (a, b) => {
1040
+ // no diagnostics anywhere in this function body
1041
+ };
1042
+
1043
+ // ::ignore-file
1044
+ // Anywhere in a file (usually at the top): no diagnostics in this file
1045
+ ```
1046
+
1047
+ `::ignore` suppresses exactly the line **below** the comment, so put it
1048
+ directly above the code line — below an annotation, not above it:
1049
+
1050
+ ```javascript
1051
+ // fee :: Number
1052
+ // ::ignore
1053
+ const fee = legacyFee ();
1054
+ ```
1055
+
1056
+ `::ignore-function` suppresses the whole function that follows it (an
1057
+ annotation in between is fine). `::ignore` and `::ignore-file` are also
1058
+ available as quick fixes on an existing diagnostic (see
1059
+ [Code Actions](#code-actions)).
1060
+
1061
+ ---
1062
+
1063
+ ## Type System
1064
+
1065
+ The engine is classic **rank-1 Hindley-Milner** with full inference — no
1066
+ annotation is ever required for the machinery to work, and inferred types are
1067
+ principal (most general). On top of that, **rank-N polymorphism is available
1068
+ opt-in** by writing an explicit `forall` in an annotation:
1069
+
1070
+ ```javascript
1071
+ // applyBoth :: (forall a. a -> a) -> (Number, String) -> [Number, String]
1072
+ const applyBoth = f => (n, s) => [f(n), f(s)];
1073
+
1074
+ const ok = applyBoth(x => x)(1, "one"); // ✓
1075
+ const bad = applyBoth(x => x + 1)(1, "one"); // ✗ Argument is not polymorphic enough
1076
+ ```
1077
+
1078
+ A `forall` parameter is bound as a real scheme in the body and arguments are
1079
+ checked by skolemization at the call site — including skolem-escape detection,
1080
+ constraints inside the `forall`, and polymorphic record fields. A `forall` is
1081
+ never inferred, only checked. Worked examples live in
1082
+ [sample/rankN/](sample/rankN/); the full design — along with everywhere else
1083
+ the engine extends or bends the textbook algorithm — is catalogued in
1084
+ [TYPE-SYSTEM.md](TYPE-SYSTEM.md).
1085
+
1086
+ ### Primitives
1087
+
1088
+ | Type | Description |
1089
+ |------|-------------|
1090
+ | `Number` | JavaScript numbers |
1091
+ | `String` | JavaScript strings |
1092
+ | `Boolean` | `true` / `false` |
1093
+ | `Null` | `null` |
1094
+ | `Undefined` | `undefined` |
1095
+ | `Void` | No return value |
1096
+ | `Any` | A value nothing is known about (an import from an untyped package, `globalThis`); fits everywhere |
1097
+
1098
+ Numeric refinements in the style of Sanctuary — `Integer`, `PositiveNumber`,
1099
+ `NegativeNumber`, `NonZeroInteger`, `PositiveInteger`, `NonNegativeInteger`,
1100
+ `FiniteNumber`, `ValidNumber`, `Float`, `Double`, … — are `Number` to the
1101
+ type checker. A numeric **literal** passed to such a parameter is checked
1102
+ against the refinement (`f (2.5)` for `f :: Integer -> …` reports
1103
+ `'2.5' is not an integer`); other values are not.
1104
+
1105
+ ### Calling Convention
1106
+
1107
+ JavaScript calls are **tuple-applied**: `f(a, b)` constructs `Tuple[A, B]`
1108
+ and unifies it against the function parameter. So a multi-argument JS
1109
+ function MUST be annotated in tuple form:
1110
+
1111
+ ```javascript
1112
+ // For factory(a, b):
1113
+ // factory :: (A, B) -> C
1114
+
1115
+ // For factory(a)(b) (curried):
1116
+ // factory :: A -> B -> C
1117
+ ```
1118
+
1119
+ This is the single most common source of confusion when authoring
1120
+ sidecars — see [Curry](#curry) for how curried forms are detected.
1121
+
1122
+ ### Functions
1123
+
1124
+ ```javascript
1125
+ // Single argument
1126
+ // formatAmount :: Number -> String
1127
+ const formatAmount = (n) => `€ ${n.toFixed(2)}`;
1128
+
1129
+ // Multiple arguments
1130
+ // applyVat :: (Number, Number) -> Number
1131
+ const applyVat = (amount, rate) => amount * (1 + rate);
1132
+
1133
+ // Higher-order
1134
+ // map :: ((a -> b), [a]) -> [b]
1135
+ const map = (fn, xs) => xs.map(fn);
1136
+ ```
1137
+
1138
+ An annotation is a promise the body must keep. Type variables are
1139
+ **rigid** inside the body: the caller chooses them, so the body may not
1140
+ pick one for them.
1141
+
1142
+ ```javascript
1143
+ // second :: (a, b) -> b
1144
+ const second = (x, y) => x;
1145
+ // HM1003: 'second' has type '(a, b) -> a' but annotation expects '(a, b) -> b'
1146
+ ```
1147
+
1148
+ Type variables are **scoped lexically**, like generics: a letter in a
1149
+ nested annotation that also appears in the enclosing annotation is the
1150
+ same variable, so closure helpers can be annotated:
1151
+
1152
+ ```javascript
1153
+ // keepWhere :: (a -> Boolean) -> [a] -> [a]
1154
+ const keepWhere = (keep) => (items) => {
1155
+ // The same `a` as in keepWhere:
1156
+ // check :: a -> Boolean
1157
+ const check = (item) => keep (item);
1158
+ return items.filter (check);
1159
+ };
1160
+ ```
1161
+
1162
+ A parameter with a JavaScript default value may be left out at a call
1163
+ site; the annotation names its type as usual:
1164
+
1165
+ ```javascript
1166
+ // padLabel :: (String, Number, String) -> String
1167
+ const padLabel = (label, width, fill = " ") => label.padEnd (width, fill);
1168
+
1169
+ padLabel ("Total", 10); // fine: `fill` has a default
1170
+ ```
1171
+
1172
+ ### Arrays & Tuples
1173
+
1174
+ ```javascript
1175
+ // Arrays — homogeneous
1176
+ // invoiceTotal :: [Number] -> Number
1177
+ const invoiceTotal = (amounts) => amounts.reduce((a, b) => a + b, 0);
1178
+
1179
+ // Tuples — fixed-length, heterogeneous: one type per position
1180
+ // formatLine :: [String, Number] -> String
1181
+ const formatLine = (line) => `${line[0]}: ${line[1]}`;
1182
+
1183
+ formatLine (["Coffee", 3]); // fine
1184
+ formatLine ([3, "Coffee"]); // Cannot unify 'Number' with 'String' (and back)
1185
+ ```
1186
+
1187
+ Do not confuse `[A, B]` (one tuple argument) with `(A, B)` (two arguments,
1188
+ see [Calling Convention](#calling-convention)).
1189
+
1190
+ ### Records & Row Polymorphism
1191
+
1192
+ ```javascript
1193
+ // Record types with named fields
1194
+ // customerLabel :: { name :: String, vatNumber :: String } -> String
1195
+ const customerLabel = (customer) => `${customer.name} (${customer.vatNumber})`;
1196
+ ```
1197
+
1198
+ Records use **structural typing** — any object with matching fields
1199
+ satisfies the type.
1200
+
1201
+ Use `...rest` to make a record open (extensible):
1202
+
1203
+ ```javascript
1204
+ // pickName :: { name :: String, ...rest } -> String
1205
+ const pickName = (o) => o.name;
1206
+
1207
+ // drop :: { x :: a, ...rest } -> { ...rest }
1208
+ ```
1209
+
1210
+ Open vs. open records unify their tails through a shared row variable;
1211
+ closed-vs-closed unification silently accepts extra caller fields for
1212
+ JS compatibility.
1213
+
1214
+ Reading a field that an open record does not list adds it to the row, as
1215
+ long as that row is still free. A callback typed from a library signature
1216
+ (`prop :: k -> { [k] :: a, ...r } -> a`) can read other fields this way:
1217
+
1218
+ ```javascript
1219
+ // isBigUnpaid :: { total :: Number, paid :: t, ...r } -> Boolean (inferred)
1220
+ const isBigUnpaid = both (complement (prop ("paid")), (order) => order.total > 50);
1221
+ ```
1222
+
1223
+ A function checked against its own annotation keeps its row fixed: with
1224
+ `pickName :: { name :: String, ...rest } -> String`, reading `o.title` is
1225
+ an error.
1226
+
1227
+ One exception catches typos: an **object literal** passed where a
1228
+ **named** closed record (an alias) is expected may not have fields the
1229
+ alias does not declare. That is reported as HM1010, with a "did you
1230
+ mean" hint when a declared field is close:
1231
+
1232
+ ```javascript
1233
+ // Customer :: { name :: String, vatNumber :: String, email :: String | Undefined }
1234
+
1235
+ // customerLabel :: Customer -> String
1236
+ const customerLabel = (c) => c.name;
1237
+
1238
+ customerLabel ({ name: "Acme", vatNumber: "NL001", emial: "info@acme.test" });
1239
+ // HM1010 Unknown field 'emial' on argument; expected 'Customer' (did you mean 'email'?)
1240
+ ```
1241
+
1242
+ Values that are not literals (a record built elsewhere, a destructured
1243
+ parameter) and inline record types keep the lenient rule.
1244
+
1245
+ A computed key is the key's *value*: `{ ["currency"]: "EUR" }` has a field
1246
+ `currency`, a label variable makes a label field (`k -> a -> { [k] :: a }`),
1247
+ and a key known only at runtime (`{ [field]: value }` with `field ::
1248
+ String`) gives a dictionary, `Object String v`, which `Object.assign` and
1249
+ spreads merge as dictionaries. The level is
1250
+ set with `diagnostics.excessRecordFields`.
1251
+
1252
+ ### Union & String-Literal Types
1253
+
1254
+ ```javascript
1255
+ // Explicit union
1256
+ // show :: Number | String -> String
1257
+ const show = (x) => String(x);
1258
+
1259
+ // Automatically inferred from conditionals
1260
+ const reference = Math.random() > 0.5 ? 2026001 : "draft";
1261
+ // reference :: Number | String
1262
+
1263
+ // Singleton string-literal types
1264
+ // statusLabel :: 'draft' | 'sent' | 'paid' -> String
1265
+ const statusLabel = (s) => `status: ${s}`;
1266
+ ```
1267
+
1268
+ String literals in type position parse as `TLabel` (a singleton type).
1269
+ At call sites a literal string must be one of the allowed values, and a
1270
+ plain `String` does not fit a literal union (it could hold any text):
1271
+
1272
+ ```javascript
1273
+ statusLabel ("paid"); // ok
1274
+ statusLabel ("piad"); // HM1001: 'piad' is not one of 'draft' | 'paid' | 'sent'
1275
+
1276
+ // fromInput :: String -> String
1277
+ const fromInput = (raw) => statusLabel (raw);
1278
+ // HM1001: 'String' does not fit 'draft' | 'paid' | 'sent'
1279
+ ```
1280
+
1281
+ A literal assigned to a `const` keeps its literal type (`const status =
1282
+ "sent"` fits), and so does a ternary of literals (`paid ? "paid" :
1283
+ "sent"`).
1284
+
1285
+ **Unions have a direction.** An argument must fit the parameter: every
1286
+ member of a union argument has to be accepted by the parameter, so
1287
+ `Number | Undefined` does not fit `Number | Null`. The other way round,
1288
+ a function may return *less* than its annotation promises: a body that
1289
+ returns `String | Null` satisfies `-> String | Number | Null`, but not
1290
+ `-> String` (a member it does not declare).
1291
+
1292
+ ```javascript
1293
+ // shown :: Number | Null -> String
1294
+ const shown = (n) => n == null ? "-" : String (n);
1295
+
1296
+ // countLabel :: Number | Undefined -> String
1297
+ const countLabel = (n) => shown (n);
1298
+ // HM1001: Cannot unify 'Number | Undefined' with 'Null | Number'
1299
+ ```
1300
+
1301
+ ### Generics & Higher-Kinded Types
1302
+
1303
+ Lowercase identifiers are type variables (parametric polymorphism).
1304
+ Constraint-bound variables can stand for higher-kinded types:
1305
+
1306
+ ```javascript
1307
+ // identity :: a -> a
1308
+ const identity = (x) => x;
1309
+
1310
+ // fmap :: Functor f => ((a -> b), f a) -> f b
1311
+ const fmap = (fn, fa) => fa.map(fn);
1312
+
1313
+ // chain :: Monad m => (a -> m b) -> m a -> m b
1314
+ ```
1315
+
1316
+ A constraint variable like `f` (declared in the constraint head) parses
1317
+ greedily — it absorbs juxtaposed atoms (`f a`, `m (Maybe a)`). Plain
1318
+ non-constraint vars only consume juxtaposition when followed by `(...)`.
1319
+
1320
+ Two-parameter constructors work the same way: `QueryTag p o`,
1321
+ `Either e a`, `Map k v`.
1322
+
1323
+ ### Label Polymorphism
1324
+
1325
+ A computed key — `o[k]`, or destructuring `({ [k]: v }) => v` — infers a
1326
+ *label variable* (a separate sort from type vars) so accessors can be
1327
+ polymorphic over field names:
1328
+
1329
+ ```javascript
1330
+ // pluck :: (k, { [k] :: a, ...r }) -> a
1331
+ const pluck = (k, o) => o[k];
1332
+
1333
+ pluck("x", { x: 1, y: 2 }); // k := 'x', a := Number
1334
+ pluck("y", { y: "hi" }); // k := 'y', a := String
1335
+ ```
1336
+
1337
+ ### Type Aliases
1338
+
1339
+ Uppercase top-level names that don't return a constructor are treated
1340
+ as aliases. Free type variables are recorded and re-instantiated at
1341
+ each use site:
1342
+
1343
+ ```javascript
1344
+ // LineItem :: { description :: String, quantity :: Number, unitPrice :: Number }
1345
+ // Selector :: String | Prop a | Limit
1346
+ ```
1347
+
1348
+ Aliases expand at unification time with cycle detection, and they are
1349
+ **nominal**: two aliases with the same fields are still different types, so a
1350
+ `Customer` is not accepted where a `Supplier` is expected. A plain record
1351
+ (an object literal, an unannotated value) fits any alias whose fields it has.
1352
+
1353
+ ### Properties & Private Members
1354
+
1355
+ Annotate non-method properties (no `~>`) directly:
1356
+
1357
+ ```javascript
1358
+ // Invoice#number :: String
1359
+ // Invoice#lines :: [LineItem]
1360
+ ```
1361
+
1362
+ Private members (JS `#name` syntax) use a double `##`:
1363
+
1364
+ ```javascript
1365
+ // Counter :: () -> Counter
1366
+ class Counter {
1367
+ #count = 0;
1368
+ // Counter##count :: Number
1369
+ // Counter#tick :: Counter ~> () -> ()
1370
+ tick() { this.#count++; }
1371
+ }
1372
+ ```
1373
+
1374
+ ### Instance-Callable Values
1375
+
1376
+ Annotate values whose runtime values are themselves callable
1377
+ (parser tag functions, builder factories, etc.):
1378
+
1379
+ ```javascript
1380
+ // The constructor:
1381
+ // SQLTag :: a -> SQLTag a
1382
+
1383
+ // Calling an SQLTag instance:
1384
+ // SQLTag() :: a -> Promise Error [b]
1385
+ ```
1386
+
1387
+ The `Type()` form lives in a separate namespace from the constructor;
1388
+ hovering on a value of that type surfaces only the instance-callable
1389
+ overloads.
1390
+
1391
+ ### Overloading
1392
+
1393
+ Repeating a top-level decl registers an additional call signature:
1394
+
1395
+ ```javascript
1396
+ // total :: Invoice -> Number
1397
+ // total :: [Invoice] -> Number
1398
+ ```
1399
+
1400
+ At each call site, the engine tries each branch in declaration order
1401
+ and picks the **first** that unifies. A branch only fits when the
1402
+ arguments fit its parameters [in their direction](#union--string-literal-types):
1403
+ a plain `String` does not take a `'asc' | 'desc'` branch.
1404
+
1405
+ A union argument whose members fit *different* branches is resolved per
1406
+ member, as it runs, when the results agree:
1407
+
1408
+ ```javascript
1409
+ // toPromise :: Promise e a -> Promise e a
1410
+ // toPromise :: a -> Promise e a
1411
+ const toPromise = (x) => x instanceof Promise ? x : Promise.resolve (x);
1412
+
1413
+ // Outcome :: { ok :: Boolean, field :: String }
1414
+ // RuleResult :: Outcome | Promise Error Outcome
1415
+
1416
+ // passed :: RuleResult -> Promise Error Boolean
1417
+ const passed = (result) => toPromise (result).then (outcome => outcome.ok);
1418
+ // Outcome takes the second branch, the promise the first: Promise Error Outcome
1419
+ ```
1420
+
1421
+ ### Picked Projection
1422
+
1423
+ `Picked Row Selectors` is a built-in type constructor that *projects* a
1424
+ row record at the call site. The introspect-style sidecar declares per-table
1425
+ overloads like:
1426
+
1427
+ ```hm
1428
+ Organisation :: [OrganisationSelector] -> QueryTag p (Picked OrganisationRow OrganisationSelector)
1429
+ ```
1430
+
1431
+ When called with a literal-array argument, the LSP narrows `Picked` to
1432
+ the actual selected fields. Method-shadows on the row type
1433
+ (`OrganisationRow#locations :: [LocationRow]`) drive nested projection
1434
+ for relations.
1435
+
1436
+ A nested query contributes **what calling it returns**, read off its
1437
+ type's instance-callable annotation, so a library controls the shape of a
1438
+ relation by how it types its query values:
1439
+
1440
+ ```hm
1441
+ QueryTag() :: p -> Promise e [o] // nested: a list relation
1442
+ QueryOne() :: p -> Promise e (o | Null) // nested: one related row, or null
1443
+ QueryExists() :: p -> Promise e Boolean // nested: a filter, adds no field
1444
+ ```
1445
+
1446
+ A callable whose result holds the row without an array (`o`, `o | Null`)
1447
+ also receives the host's row type, like `[o]` does. A project override in
1448
+ `hm-types/<pkg>.hm` may replace these callables, e.g. when the project runs
1449
+ the library's queries through a runner that returns a task:
1450
+
1451
+ ```hm
1452
+ QueryTag() :: p -> RTask r Error [o]
1453
+ ```
1454
+
1455
+ ### Curry
1456
+
1457
+ To curry a function, you need a `curry` helper with the right signature. The LSP detects curry wrappers by their annotation pattern — a function that takes a tuple-param function and returns a curried version:
1458
+
1459
+ ```javascript
1460
+ // curry :: ((a, b, ...) -> z) -> a -> b -> ... -> z
1461
+ export const curry = fn => {
1462
+ const curried = (...args) => {
1463
+ if (args.length >= fn.length) return fn(...args);
1464
+ return (...next) => curried(...args, ...next);
1465
+ };
1466
+ return curried;
1467
+ };
1468
+ ```
1469
+
1470
+ Wrap any multi-param function with `curry()` to enable partial application:
1471
+
1472
+ ```javascript
1473
+ // discountedTotal :: (Number, Number, Number) -> Number
1474
+ const discountedTotal = (quantity, unitPrice, discountPct) =>
1475
+ quantity * unitPrice * (1 - discountPct / 100);
1476
+
1477
+ const curriedTotal = curry(discountedTotal);
1478
+ // curriedTotal :: Number -> Number -> Number -> Number
1479
+ ```
1480
+
1481
+ All partial application forms are then valid:
1482
+
1483
+ ```javascript
1484
+ curriedTotal(2, 50, 10) // fully applied
1485
+ curriedTotal(2)(50)(10) // fully curried
1486
+ curriedTotal(2, 50)(10) // partial + apply
1487
+ curriedTotal(2)(50, 10) // apply + partial
1488
+ ```
1489
+
1490
+ > **Note:** Without wrapping in `curry()`, a function with signature `(a, b, c) -> d` simply expects all arguments at once. The LSP only generates curried overloads when it detects the `curry()` call.
1491
+
1492
+ A library whose functions are already curried (Ramda and its relatives) is
1493
+ described in a `.hm` file with [`::curried`](#curried--curried-library-functions);
1494
+ see [Ramda](#ramda) for a complete example.
1495
+
1496
+ ### Pipe & Compose
1497
+
1498
+ The LSP supports variadic `pipe` and `compose` functions using **spread tuple syntax** in annotations. It validates that chained functions connect properly — the output of one must match the input of the next.
1499
+
1500
+ #### Pipe (left-to-right)
1501
+
1502
+ ```javascript
1503
+ // pipe :: ((a -> b), (b -> c), ..., (y -> z)) -> a -> z
1504
+ const pipe = (...fns) => fns.reduce((acc, fn) => x => fn(acc(x)));
1505
+
1506
+ const invoiceLabel = pipe(
1507
+ x => x * 1.21, // Number -> Number (apply VAT)
1508
+ x => x.toFixed(2), // Number -> String (format)
1509
+ x => `€ ${x}`, // String -> String (prefix)
1510
+ );
1511
+ // invoiceLabel :: Number -> String
1512
+ ```
1513
+
1514
+ The LSP verifies each link in the chain — if the output of one function doesn't match the input of the next, it reports a type error:
1515
+
1516
+ ```javascript
1517
+ // withVat :: Number -> Number
1518
+ const withVat = x => x * 1.21;
1519
+
1520
+ // format :: Number -> String
1521
+ const format = x => x.toFixed(2);
1522
+
1523
+ const broken = pipe(format, withVat);
1524
+ // Cannot unify 'Number' with 'String': format gives a String, withVat wants a Number
1525
+ ```
1526
+
1527
+ The links are checked against what is known about each function: an
1528
+ unannotated lambda such as `x => x * 1.21` is checked leniently (JavaScript
1529
+ would coerce a String there), so give the steps signatures where the chain
1530
+ matters.
1531
+
1532
+ #### Compose (right-to-left)
1533
+
1534
+ ```javascript
1535
+ // compose :: ((y -> z), ..., (b -> c), (a -> b)) -> a -> z
1536
+ const compose = (...fns) => fns.reduceRight((acc, fn) => x => fn(acc(x)));
1537
+
1538
+ const invoiceLabel = compose(
1539
+ x => `€ ${x}`, // String -> String (prefix)
1540
+ x => x.toFixed(2), // Number -> String (format)
1541
+ x => x * 1.21, // Number -> Number (apply VAT)
1542
+ );
1543
+ // invoiceLabel :: Number -> String
1544
+ ```
1545
+
1546
+ The direction is detected automatically from the annotation — shared type variables between adjacent function positions determine whether the chain flows left-to-right (pipe) or right-to-left (compose).
1547
+
1548
+ ### Type Narrowing
1549
+
1550
+ Types are automatically narrowed inside conditional branches:
1551
+
1552
+ ```javascript
1553
+ // typeof guards
1554
+ if (typeof x === 'string') {
1555
+ // x: String
1556
+ }
1557
+
1558
+ // Null checks
1559
+ if (x != null) {
1560
+ // x: narrowed (null/undefined removed)
1561
+ }
1562
+
1563
+ // Truthiness
1564
+ if (x) {
1565
+ // x: narrowed (null/undefined removed)
1566
+ }
1567
+
1568
+ // ::narrow predicates
1569
+ // ::narrow Number
1570
+ // isNumber :: a -> Boolean
1571
+ const isNumber = (x) => typeof x === 'number';
1572
+
1573
+ if (isNumber(value)) {
1574
+ // value: Number
1575
+ }
1576
+ ```
1577
+
1578
+ A guard that leaves the function narrows the rest of it, and so does a
1579
+ default that is assigned in the guard:
1580
+
1581
+ ```javascript
1582
+ // Customer :: { name :: String, email :: String | Null }
1583
+
1584
+ // greeting :: Customer | Null -> String
1585
+ const greeting = (customer) => {
1586
+ if (!customer) return "Hello";
1587
+ return "Hello " + customer.name; // customer: Customer
1588
+ };
1589
+
1590
+ // pageSize :: Number | Null -> Boolean -> Number
1591
+ const pageSize = (size) => (compact) => {
1592
+ if (compact || size == null) return 10;
1593
+ return size * 2; // size: Number
1594
+ };
1595
+
1596
+ // displayName :: String | Null -> String
1597
+ const displayName = (name) => {
1598
+ if (name == null) name = "guest";
1599
+ return name.toUpperCase (); // name: String
1600
+ };
1601
+
1602
+ // emailOf :: Customer -> String
1603
+ const emailOf = (customer) => {
1604
+ if (customer.email == null) return "-";
1605
+ return customer.email.toLowerCase (); // customer.email: String
1606
+ };
1607
+ ```
1608
+
1609
+ Narrowing follows identifiers and member paths (`customer.email`), not
1610
+ computed expressions: for `orders[0].customer` bind the value to a
1611
+ `const` first.
1612
+
1613
+ #### Lookups that can miss
1614
+
1615
+ `Map#get` returns `v | Undefined`: the key may be absent. Three ways to
1616
+ handle it:
1617
+
1618
+ ```javascript
1619
+ // Fixture :: { id :: Number, team :: Number }
1620
+
1621
+ // rates :: Map String Number
1622
+ const rates = new Map ([["NL", 0.21], ["BE", 0.21]]);
1623
+
1624
+ // 1. Check the result.
1625
+ // vatOrZero :: String -> Number
1626
+ const vatOrZero = (country) => rates.get (country) ?? 0;
1627
+
1628
+ // 2. Check the key first: after `has` on the same map and key, `get`
1629
+ // cannot miss (also after `if (!m.has (k)) m.set (k, …);` and after
1630
+ // `if (!m.has (k)) return …;`).
1631
+ // vatOf :: String -> Number
1632
+ const vatOf = (country) => rates.has (country) ? rates.get (country) : 0;
1633
+
1634
+ // groupByTeam :: [Fixture] -> Map Number [Fixture]
1635
+ const groupByTeam = (fixtures) => {
1636
+ const byTeam = new Map ();
1637
+ fixtures.forEach (f => {
1638
+ if (!byTeam.has (f.team)) byTeam.set (f.team, []);
1639
+ byTeam.get (f.team).push (f);
1640
+ });
1641
+ return byTeam;
1642
+ };
1643
+
1644
+ // 3. State it: you know the key is there (an invariant hinmil cannot see).
1645
+ // dutchVat :: Number
1646
+ const dutchVat = rates.get ("NL");
1647
+ ```
1648
+
1649
+ The third form works for any `const` whose value comes from a lookup —
1650
+ a call, a member access or an `await` — that may give `Undefined` or
1651
+ `Null`: the annotation may leave those out. The rest of the type must
1652
+ still match (`// dutchVat :: String` is an error), and a value that is
1653
+ `undefined` by construction (`member ? 10 : undefined`) is still
1654
+ reported. The map and key of a `has`/`get` pair are compared as paths
1655
+ (`m`, `this.cache`, `state.byTeam`; `key`, `row.teamId`, `"NL"`): a key
1656
+ computed by a call (`m.get (keyOf (row))`) needs a `const` first.
1657
+
1658
+ ---
1659
+
1660
+ ## Publishing types for an npm package
1661
+
1662
+ As a package author you have three independent ways to ship HM signatures
1663
+ with your code. Pick whichever fits — or mix them. A consumer never has to
1664
+ configure anything: the LSP discovers your signatures automatically when they
1665
+ `import` your package.
1666
+
1667
+ ### 1. Inline annotations (zero config)
1668
+
1669
+ Write `// Name :: Type` comments directly above your JS definitions.
1670
+ No extra files, no `package.json` entry, no build step:
1671
+
1672
+ ```javascript
1673
+ // node_modules/mylib/index.js
1674
+
1675
+ // limit :: Number -> Limit
1676
+ exports.limit = (n) => ({ tag: 'limit', n });
1677
+
1678
+ // add :: Number -> Number -> Number
1679
+ exports.add = (a) => (b) => a + b;
1680
+ ```
1681
+
1682
+ When a consumer does `import { limit } from 'mylib'`, the LSP
1683
+ BFS-walks your package starting from `main` / `module`, follows
1684
+ `import` / `export ... from` / `require` edges, **stays inside the
1685
+ package root** (no `../` escapes), and collects every inline
1686
+ signature it finds. The walk is capped at 256 files per package.
1687
+
1688
+ Anything that works in source — `::constraint`, sum type declarations,
1689
+ type aliases, `Type#method`, `Type() ::`, `::types <pkg>` chaining —
1690
+ works inline too:
1691
+
1692
+ ```javascript
1693
+ // node_modules/mylib/index.js
1694
+ // ::constraint Runnable r { r :: (a -> r) | r }
1695
+ // Pull in another lib's types too:
1696
+ // ::types some-other-lib
1697
+
1698
+ // runIt :: Runnable r => r -> Limit r
1699
+ exports.runIt = (r) => ({ tag: 'limit', r });
1700
+ ```
1701
+
1702
+ ### 2. Sidecar `.hm` files
1703
+
1704
+ For authors who prefer to keep types out of the JS source, or version
1705
+ them separately. Declare them under `"hinmil"` in `package.json`:
1706
+
1707
+ ```json
1708
+ {
1709
+ "name": "mylib",
1710
+ "main": "index.js",
1711
+ "hinmil": {
1712
+ "sidecars": "./types.hm"
1713
+ }
1714
+ }
1715
+ ```
1716
+
1717
+ A sidecar contains the same declarations you would write in-source
1718
+ (top-level signatures, `Type#method`, `Type.static`, `Type() ::`,
1719
+ sum type declarations, `::constraint`, type aliases, …) but without
1720
+ the `// ` comment prefix — it's pure HM source. In a `.hm` file `//`
1721
+ starts a comment, on a line of its own or after a declaration
1722
+ (`Status :: 'open' | 'paid' // as the provider sends it`); `/* … */`
1723
+ blocks are comments too. Directives are written bare as well
1724
+ (`::types other-lib`, `::constraint …`): a `// ::types …` line in a
1725
+ `.hm` file is a comment.
1726
+
1727
+ Multiple sidecars are supported; later entries **override** earlier
1728
+ ones for both value exports and type aliases:
1729
+
1730
+ ```json
1731
+ {
1732
+ "hinmil": {
1733
+ "sidecars": [
1734
+ "./sqlkit.hm",
1735
+ "../.sqlkit/client/index.hm"
1736
+ ]
1737
+ }
1738
+ }
1739
+ ```
1740
+
1741
+ Sidecar files are watched: edits trigger transitive cache invalidation
1742
+ so downstream files re-check immediately.
1743
+
1744
+ ### 3. Package globals
1745
+
1746
+ For symbols that should be in scope for every file in a consumer
1747
+ project — type aliases, ambient constraints, shared kinds — without
1748
+ each consumer file needing a `// ::types` directive. This is a config
1749
+ key, not to be confused with the [`::global` directive](#global--extend-built-in-types)
1750
+ (which registers methods/statics on types): `"globals"` makes a whole
1751
+ declaration file ambient. Declare under the same `"hinmil"` block:
1752
+
1753
+ ```json
1754
+ {
1755
+ "hinmil": {
1756
+ "sidecars": "./sqlkit.hm",
1757
+ "globals": ["./sqlkit.hm"]
1758
+ }
1759
+ }
1760
+ ```
1761
+
1762
+ `"globals"` **must be an array** (a bare string is rejected with a
1763
+ warning). Every consumer file in the workspace automatically gets
1764
+ these declarations merged into its environment.
1765
+
1766
+ ### Merge order
1767
+
1768
+ When the same name appears in multiple sources, later wins:
1769
+
1770
+ ```
1771
+ bundled builtin < inline < sidecar < companion package < project-local override
1772
+ ```
1773
+
1774
+ A *bundled builtin* is a signature file shipped with the extension itself
1775
+ ([hm-types-builtin/](hm-types-builtin/)): `react` and `react-dom`, and the
1776
+ Node modules `assert`, `buffer`, `child_process`, `crypto`, `fs`, `http`,
1777
+ `os`, `path`, `url` and `zlib` (`node:fs` is the same as `fs`). It is the
1778
+ weakest layer, and any package backed by one is *open-world*: importing a
1779
+ name no layer declares binds it to `Any` instead of erroring, so an
1780
+ outdated bundle can never be worse than no typings. A Node module without
1781
+ a bundled file (for example `readline`) gives HM3003; add a project stub
1782
+ in `hm-types/<module>.hm` (methods as `Type#method :: Type ~> …`).
1783
+
1784
+ A built-in type that has no `Name ::` declaration (such as `ReactElement`)
1785
+ is documented in its bundled file with an anchor line `// ::builtin Name`;
1786
+ go to definition on the type name jumps there.
1787
+
1788
+ A *companion package* is an `@hm/<pkg>` package that ships sidecars
1789
+ for a package that has none itself (like `@types/*` in the TypeScript
1790
+ world): `lodash` → `@hm/lodash`, `@scope/pkg` → `@hm/scope__pkg`. It
1791
+ is only consulted when the package provides neither inline annotations
1792
+ nor its own sidecar.
1793
+
1794
+ So a project can always shadow a published signature by declaring it
1795
+ locally, a sidecar shadows inline annotations, and inline is the
1796
+ fallback when nothing else is declared.
1797
+
1798
+ ### Cross-package chaining
1799
+
1800
+ A `.js` or `.hm` source can pull in another package's types
1801
+ explicitly with `// ::types`:
1802
+
1803
+ ```javascript
1804
+ // A bare specifier: recurse into that package's scan.
1805
+ // ::types other-pkg
1806
+
1807
+ // A sibling JS file, and a sibling sidecar:
1808
+ // ::types ./helper.js
1809
+ // ::types ./types.hm
1810
+ ```
1811
+
1812
+ This is useful when your signatures reference types declared in a
1813
+ dependency. Results are cached per package root, so transitive chains
1814
+ don't re-scan on every import.
1815
+
1816
+ ## Using a typed npm package (consumer side)
1817
+
1818
+ There is nothing to configure. Install and import:
1819
+
1820
+ ```javascript
1821
+ const { limit, add } = require('mylib');
1822
+
1823
+ const x = add(1)(2); // hover shows: Number
1824
+ const y = limit('hi'); // diagnostic: expected Number, got String
1825
+ ```
1826
+
1827
+ The LSP resolves `mylib` via Node's normal `node_modules` lookup,
1828
+ applies sidecar (if any), falls back to inline scan, merges globals,
1829
+ and caches the result per package root. Subsequent imports of the
1830
+ same package are free.
1831
+
1832
+ The package's methods (`Type#method` in its sidecar or inline annotations)
1833
+ come along with the import: `makeCart ().count ()` is typed as soon as
1834
+ `makeCart` is imported. A `::types` directive is only needed for type-only
1835
+ use — a file that names the package's types in its annotations but imports
1836
+ nothing from it:
1837
+
1838
+ ```javascript
1839
+ // ::types sqlkit
1840
+ // queryOf :: SqlKit -> String
1841
+ const queryOf = (kit) => kit.toString ();
1842
+ ```
1843
+
1844
+ ### When signatures don't show up
1845
+
1846
+ A few common gotchas:
1847
+
1848
+ - **No `main` / `module` in `package.json`** — the inline scan falls
1849
+ back to `index.{js,mjs,cjs}`. If that's also absent, no signatures.
1850
+ - **Symlinked / linked package in dev (`npm link`, `pnpm`)** — usually
1851
+ works, but cache may go stale after edits inside `node_modules`.
1852
+ Restart the LSP if you're not seeing fresh signatures.
1853
+ - **Annotation lives outside the package root** — the BFS won't follow
1854
+ `../` escapes. Use `// ::types <relative-or-bare>` to chain
1855
+ explicitly.
1856
+ - **`"globals"` config key declared as a string** — ignored, with a
1857
+ warning. Always an array (see
1858
+ [Package globals](#3-package-globals)).
1859
+ - **Re-export chain >256 files** — scan cap is hit; declare a sidecar
1860
+ for the affected names.
1861
+
1862
+ ### Ramda
1863
+
1864
+ Ramda does not ship HM types itself. The example project
1865
+ [hinmil-example](https://github.com/tureluren/hinmil-example) has a
1866
+ [`hm-types/ramda.hm`](https://github.com/tureluren/hinmil-example/blob/main/hm-types/ramda.hm)
1867
+ for 84 of its most used functions (Ramda 0.29 and later), written with
1868
+ [`::curried`](#curried--curried-library-functions). Copy it to
1869
+ `hm-types/ramda.hm` in your project, and named and namespace imports are
1870
+ typed, in Ramda's curried style, with the `__` placeholder:
1871
+
1872
+ ```javascript
1873
+ import * as R from "ramda";
1874
+
1875
+ const orders = [
1876
+ { id: "o1", customer: "Ada", total: 120, paid: true },
1877
+ { id: "o2", customer: "Alan", total: 35, paid: false },
1878
+ ];
1879
+
1880
+ const unpaid = R.filter (R.propEq (false, "paid"), orders); // the full order type
1881
+ const byCustomer = R.groupBy (R.prop ("customer")) (orders); // orders per customer: { [String] :: [{ id, customer, … }] }
1882
+ const outstanding = R.pipe (R.map (R.prop ("total")), R.sum); // [{ total :: Number, ...r }] -> Number
1883
+ const withoutFee = R.subtract (R.__, 2.5); // Number -> Number
1884
+
1885
+ const broken = R.pipe (R.map (R.prop ("total")), R.sum, R.toUpper);
1886
+ // ✗ Type mismatch: Cannot unify 'String' with 'Number'
1887
+ ```
1888
+
1889
+ A function that is not in the file is `Any` once Ramda is installed.
1890
+
1891
+ ---
1892
+
1893
+ ## Built-in Method Types
1894
+
1895
+ The LSP ships type definitions for the standard JavaScript built-ins: Array,
1896
+ String, Object, Number, BigInt, RegExp, Promise, Map, Set, Math, Date
1897
+ (including `Date.UTC` and the `setUTC…` setters), JSON, `Intl` formatters,
1898
+ `URLSearchParams`, `AbortController`/`AbortSignal`, the timers
1899
+ (`setTimeout`, … — their ids are `TimeoutId`/`IntervalId`) and, with
1900
+ `hinmil.dom.globalTypes`, the browser DOM. `globalThis` is `Any`. Node
1901
+ modules are typed through the bundled files listed under
1902
+ [Merge order](#merge-order). The tables below show the most common methods —
1903
+ hover any method call to see the exact signature.
1904
+ Optional trailing parameters are written as `| Undefined`. A callback
1905
+ result written `t` may be anything: `filter`, `find`, `some`, `every`,
1906
+ `findIndex` and `findLast(Index)` read it as truthy/falsy, so
1907
+ `orders.filter (o => o.paidAt)` needs no `Boolean`. `Awaited b` is `b`
1908
+ with a returned promise unwrapped (`then (x => fetchNext (x))` gives
1909
+ `Promise e Next`, not a promise of a promise).
1910
+
1911
+ ### Array Methods
1912
+
1913
+ | Method | Type |
1914
+ |--------|------|
1915
+ | `map` | `((a, Number, [a]) -> b) -> [b]` |
1916
+ | `filter` | `((a, Number, [a]) -> t) -> [a]` |
1917
+ | `reduce` | `((b, a, Number, [a]) -> b, b \| Undefined) -> b` |
1918
+ | `find` | `((a, Number, [a]) -> t) -> a` |
1919
+ | `some` | `((a, Number, [a]) -> t) -> Boolean` |
1920
+ | `every` | `((a, Number, [a]) -> t) -> Boolean` |
1921
+ | `flatMap` | `((a, Number, [a]) -> [b]) -> [b]` |
1922
+ | `forEach` | `((a, Number, [a]) -> b) -> ()` |
1923
+ | `concat` | `[a] ~> ([b] \| b) -> [a \| b]` |
1924
+ | `includes` | `(a, Number \| Undefined) -> Boolean` |
1925
+ | `indexOf` | `(a, Number \| Undefined) -> Number` |
1926
+ | `slice` | `(Number \| Undefined, Number \| Undefined) -> [a]` |
1927
+ | `join` | `(String \| Undefined) -> String` |
1928
+ | `reverse` | `[a]` |
1929
+ | `length` | `Number` (property) |
1930
+ | ... | and more |
1931
+
1932
+ ### String Methods
1933
+
1934
+ | Method | Type |
1935
+ |--------|------|
1936
+ | `charAt` | `(Number \| Undefined) -> String` |
1937
+ | `includes` | `(String, Number \| Undefined) -> Boolean` |
1938
+ | `indexOf` | `(String, Number \| Undefined) -> Number` |
1939
+ | `split` | `(String \| RegExp \| Undefined, Number \| Undefined) -> [String]` |
1940
+ | `slice` | `(Number \| Undefined, Number \| Undefined) -> String` |
1941
+ | `startsWith` | `(String, Number \| Undefined) -> Boolean` |
1942
+ | `replace` | `(RegExp \| String, String) -> String` |
1943
+ | `padStart` | `(Number, String \| Undefined) -> String` |
1944
+ | `toLowerCase` | `String` |
1945
+ | `toUpperCase` | `String` |
1946
+ | `trim` | `String` |
1947
+ | `length` | `Number` (property) |
1948
+ | ... | and more |
1949
+
1950
+ ### Object Static Methods
1951
+
1952
+ | Method | Type |
1953
+ |--------|------|
1954
+ | `Object.keys` | `a -> [String]` |
1955
+ | `Object.values` | `a -> [b]` |
1956
+ | `Object.entries` | `a -> [[b]]` |
1957
+ | `Object.fromEntries` | `[[b]] -> a` |
1958
+ | `Object.assign` | `(a, b) -> { ...a, ...b }` (overloads for 1–4 arguments; dictionaries `Object k a` merge to `Object k (a ∪ b)`) |
1959
+ | `Object.freeze` | `a -> a` |
1960
+ | `Object.is` | `(a, a) -> Boolean` |
1961
+ | `Object.hasOwn` | `(a, String) -> Boolean` |
1962
+ | ... | and more |
1963
+
1964
+ These stay deliberately loose — objects flow through them without
1965
+ forcing a specific record shape.
1966
+
1967
+ ### Promise Methods
1968
+
1969
+ Promises are typed as `Promise e a` — error type first, value type second.
1970
+
1971
+ | Method | Type |
1972
+ |--------|------|
1973
+ | `then` | `(a -> b, (e -> c) \| Undefined) -> Promise e (Awaited b)` |
1974
+ | `catch` | `(e -> b) -> Promise e b` |
1975
+ | `finally` | `(() -> ()) -> Promise e a` |
1976
+ | `Promise.resolve` | `a -> Promise e a` |
1977
+ | `Promise.reject` | `e -> Promise e a` |
1978
+ | `Promise.all` | `[Promise e a] -> Promise e [a]` |
1979
+ | `Promise.race` | `[Promise e a] -> Promise e a` |
1980
+ | `Promise.allSettled` | `[Promise e a] -> Promise e [a]` |
1981
+ | `Promise.any` | `[Promise e a] -> Promise e a` |
1982
+
1983
+ ### Map Methods
1984
+
1985
+ Typed as `Map k v`.
1986
+
1987
+ | Method | Type |
1988
+ |--------|------|
1989
+ | `get` | `k -> (v \| Undefined)` — see [lookups that can miss](#lookups-that-can-miss) |
1990
+ | `set` | `(k, v) -> Map k v` |
1991
+ | `has` | `k -> Boolean` |
1992
+ | `delete` | `k -> Boolean` |
1993
+ | `forEach` | `((v, k, Map k v) -> b) -> ()` |
1994
+ | `keys` | `[k]` |
1995
+ | `values` | `[v]` |
1996
+ | `entries` | `[(k, v)]` |
1997
+ | `size` | `Number` (property) |
1998
+ | `Map.groupBy` | `([a], (a -> k)) -> Map k [a]` |
1999
+
2000
+ ### Set Methods
2001
+
2002
+ Typed as `Set a`, including the newer set-operation methods.
2003
+
2004
+ | Method | Type |
2005
+ |--------|------|
2006
+ | `add` | `a -> Set a` |
2007
+ | `has` | `a -> Boolean` |
2008
+ | `delete` | `a -> Boolean` |
2009
+ | `forEach` | `((a, a, Set a) -> b) -> ()` |
2010
+ | `values` / `keys` | `[a]` |
2011
+ | `entries` | `[(a, a)]` |
2012
+ | `union` / `intersection` / `difference` / `symmetricDifference` | `Set a -> Set a` |
2013
+ | `isSubsetOf` / `isSupersetOf` / `isDisjointFrom` | `Set a -> Boolean` |
2014
+ | `size` | `Number` (property) |
2015
+
2016
+ ---
2017
+
2018
+ ## Configuration
2019
+
2020
+ HinMil reads settings from two places:
2021
+
2022
+ 1. **Editor settings** — the `hinmil.*` namespace in VS Code (Settings UI or `settings.json`).
2023
+ 2. **Project file** — a `"settings"` key in the project config (`package.json#hinmil`, `hinmil.config.json` or `hinmil.config.js`). Project-file settings **override** editor settings, so a repository can pin its own diagnostics policy for every contributor.
2024
+
2025
+ Diagnostic categories share a uniform level enum — `off`, `hint`, `information`, `warning`, `error` — where `off` disables the category entirely.
2026
+
2027
+ ### Configuration per folder (monorepos)
2028
+
2029
+ A file uses the **nearest** folder above it that has HinMil configuration
2030
+ (`hinmil.config.json`, `hinmil.config.js` or a `"hinmil"` key in
2031
+ `package.json`), up to the workspace root (or the CLI's `--project`).
2032
+ Each such folder is its own *project scope* with its own `globals`,
2033
+ `typesDir`, `overrides` and `settings`, so a `server/` and a `client/`
2034
+ application can each declare their own `Order` type:
2035
+
2036
+ ```text
2037
+ shop/
2038
+ ├── hinmil.config.json { } ← workspace root (the editor needs one here)
2039
+ ├── server/
2040
+ │ ├── hinmil.config.json { "globals": ["./globals.hm"] }
2041
+ │ ├── globals.hm Order :: { id :: String, total :: Number }
2042
+ │ └── src/orders.js ← uses server/globals.hm
2043
+ └── client/
2044
+ ├── hinmil.config.json { "globals": ["./globals.hm"] }
2045
+ ├── globals.hm Order :: { id :: String, lines :: [String] }
2046
+ └── src/summary.js ← uses client/globals.hm
2047
+ ```
2048
+
2049
+ **Multi-root workspaces.** Every folder of a multi-root workspace is a
2050
+ project of its own, with its own configuration, globals, file selection
2051
+ (`files`) and project-file settings, and folders can be added or removed
2052
+ while the editor runs. A folder with `"enable": false` in its
2053
+ configuration is skipped: its files get no diagnostics, hover or other
2054
+ answers. Settings that apply to the server as a whole (the diagnostics
2055
+ debounce and the `dom` group) follow the first folder that is checked.
2056
+
2057
+ Within one workspace folder, the file selection (`files`) and the
2058
+ project-file settings come from the editor and that folder's root
2059
+ configuration; a configuration in a subfolder contributes its globals,
2060
+ `typesDir` and `overrides`. Paths in a configuration (`globals`,
2061
+ `typesDir`) are relative to its own folder. With `hinmil.requiresConfig`,
2062
+ the language server starts only when a workspace folder itself has
2063
+ configuration (an empty `{}` is enough), and only such folders are
2064
+ checked.
2065
+
2066
+ ### Enabling / disabling the language server
2067
+
2068
+ Once the extension is installed it activates for every JavaScript file. Two settings and one project-config key control whether the language server actually runs:
2069
+
2070
+ - **`hinmil.enable`** (editor setting, default `true`) — the master switch. Put `"hinmil.enable": false` in a project's `.vscode/settings.json` to turn HinMil off for that project while keeping it on everywhere else, or set it in your user settings to disable it globally.
2071
+ - **`"enable": false`** (project config) — opt a repository out from within the repository itself, without touching editor settings. Works in `hinmil.config.json`, `hinmil.config.js`, and the `"hinmil"` key of `package.json`:
2072
+
2073
+ ```jsonc
2074
+ // hinmil.config.json (or package.json → "hinmil": { "enable": false })
2075
+ { "enable": false }
2076
+ ```
2077
+
2078
+ - **`hinmil.requiresConfig`** (editor setting, default `false`) — opt-in mode. When `true`, the server only starts if at least one workspace folder has explicit HinMil project configuration **at its root**: a `hinmil.config.json` / `hinmil.config.js` file or a `"hinmil"` key in `package.json` (a configuration only in a subfolder does not count). In a multi-root workspace the folders without such configuration are then not checked. Set this once in your **user** settings and HinMil stays dormant in every project that hasn't opted in — no per-project settings needed.
2079
+
2080
+ All of these take effect immediately (no reload): toggling them starts or stops the server, and config-file changes are picked up the moment they happen. `hinmil.enable: false` wins over everything, including the restart command. Note that syntax highlighting of HM annotations is controlled separately by `hinmil.syntaxHighlighting.enabled`.
2081
+
2082
+ | Setting | Default | Description |
2083
+ |---------|---------|-------------|
2084
+ | `hinmil.enable` | `true` | Run the language server at all. Set to `false` in a workspace's `.vscode/settings.json` — or `"enable": false` in the project config file — to disable HinMil for one project only |
2085
+ | `hinmil.requiresConfig` | `false` | Only start the language server when a workspace folder contains explicit HinMil project configuration (see below) |
2086
+ | `hinmil.files.extensions` | `.js`, `.jsx`, `.mjs`, `.cjs`, `.hm` | Source extensions HinMil checks (see [Command-Line Checker](#command-line-checker)); also settable as `files` in the project config |
2087
+ | `hinmil.files.include` | `**/*` | Globs of files to check |
2088
+ | `hinmil.files.exclude` | `node_modules`, `.git`, `dist`, `build`, `coverage` | Globs of files not to check on their own (still inferred when imported). A list you set replaces the defaults |
2089
+ | `hinmil.diagnostics.enabled` | `true` | Master switch for all diagnostics |
2090
+ | `hinmil.diagnostics.typeErrors` | `error` | Level for type mismatch / unification errors (codes 1001–1004, 1009, 7001) |
2091
+ | `hinmil.diagnostics.unknownPropertyAccess` | `error` | Level for property access on unknown or unconstrained types (codes 1005, 1006) |
2092
+ | `hinmil.diagnostics.missingRecordFields` | `error` | Level for record values missing required fields (code 1008) |
2093
+ | `hinmil.diagnostics.excessRecordFields` | `error` | Level for object-literal arguments with fields their named record type does not declare (code 1010) |
2094
+ | `hinmil.diagnostics.annotationNarrowing` | `error` | Reserved: level for code 2009, which no check emits at the moment (an annotation narrower than the inferred union is reported as 1003, or allowed for a [lookup](#lookups-that-can-miss)). Kept so existing configurations stay valid |
2095
+ | `hinmil.diagnostics.missingSignatures` | `information` | Level for functions without an HM annotation |
2096
+ | `hinmil.diagnostics.missingVariableSignatures` | `off` | Level for variables without an HM annotation |
2097
+ | `hinmil.diagnostics.trustAnnotations` | `off` | Trust user annotations and suppress diagnostics inside trusted bodies — see levels below |
2098
+ | `hinmil.diagnostics.debounceMs` | `500` | Delay (ms) before publishing diagnostics after an edit. Only affects diagnostics — hover, completion and signature help respond immediately |
2099
+ | `hinmil.display.typeVariables` | `pretty` | Type-variable display: `pretty` (a, b, c) or `raw` (internal names) |
2100
+ | `hinmil.hover.enabled` | `true` | Show inferred types on hover |
2101
+ | `hinmil.completion.enabled` | `true` | Enable autocompletion |
2102
+ | `hinmil.completion.autoImports` | `true` | Suggest exports from other workspace files with an automatic import edit |
2103
+ | `hinmil.signatureHelp.enabled` | `true` | Show parameter info on function calls |
2104
+ | `hinmil.navigation.definitions` | `auto` | Go to definition for module paths, imported names and local names (see [Go to definition](#go-to-definition)): `auto` (only when VS Code's built-in TypeScript/JavaScript extension is not active), `always`, `off` |
2105
+ | `hinmil.dom.globalTypes` | `true` | Typed browser globals (`document` → `Document`, …) with IntelliSense on the compact DOM catalogue; DOM type names become valid in annotations. Off reverts the globals to `Any` |
2106
+ | `hinmil.dom.strictNulls` | `false` | DOM lookups that can miss (`getElementById`, `querySelector`, `getAttribute`, `getItem`, …) return `T \| Null` |
2107
+ | `hinmil.syntaxHighlighting.enabled` | `true` | Highlight HM annotations in comments (requires reload) |
2108
+ | `hinmil.trace.server` | `off` | LSP message tracing between VS Code and the server (`off`, `messages`, `verbose`) |
2109
+
2110
+ ### Project-file settings
2111
+
2112
+ The project config has these top-level keys: `enable` (opt the project out, see above), `globals`, `overrides`, `typesDir`, `files` (the file selection, see [Command-Line Checker](#command-line-checker)) and `settings`. Inside `settings` go the setting groups of the table above — `diagnostics`, `display`, `hover`, `completion`, `signatureHelp`, `navigation`, `dom` — without the `hinmil.` prefix. `requiresConfig`, `syntaxHighlighting` and `trace` are editor-only. Project-file settings win over editor settings and are hot-reloaded when the file changes:
2113
+
2114
+ ```jsonc
2115
+ // package.json
2116
+ {
2117
+ "hinmil": {
2118
+ "globals": ["./globals.hm"],
2119
+ "settings": {
2120
+ "diagnostics": { "typeErrors": "warning", "missingSignatures": "off" },
2121
+ "display": { "typeVariables": "raw" }
2122
+ }
2123
+ }
2124
+ }
2125
+ ```
2126
+
2127
+ The same `"settings"` key works in a standalone `hinmil.config.json` or `hinmil.config.js` (`module.exports = { settings: { … } }`).
2128
+
2129
+ #### `trustAnnotations` levels
2130
+
2131
+ Cumulative tiers — each level includes everything the previous one does.
2132
+ `missingSignatures` / `missingVariableSignatures` are **orthogonal** and remain
2133
+ active on every level.
2134
+
2135
+ | Level | Behaviour |
2136
+ |-------|-----------|
2137
+ | `"off"` *(default)* | Full validation. Annotation-vs-inferred mismatches and every in-body type error are reported. |
2138
+ | `"signatures"` | Trust signatures: drop annotation mismatches (code 1003) so a `::` annotation is treated as ground truth, but body type errors are still surfaced. |
2139
+ | `"annotated-bodies"` | Above, plus suppress every diagnostic whose range falls **inside a binding that carries a `::` annotation**. Use when annotated bodies are considered "audited" and you only want errors in unannotated code. |
2140
+ | `"all-bodies"` | Above, plus suppress diagnostics inside **every** top-level binding (annotated or not). Only diagnostics outside binding bodies (e.g. top-level expression statements, missing-signature notices) remain. |
2141
+
2142
+ Any unrecognized value falls back to `"off"` with a warning.
2143
+
2144
+ ---
2145
+
2146
+ ## Command-Line Checker
2147
+
2148
+ Install the npm CLI as a development dependency and run the same project-aware checker outside the editor:
2149
+
2150
+ ```bash
2151
+ npm install --save-dev hinmil
2152
+ npx hinmil .
2153
+ ```
2154
+
2155
+ ```text
2156
+ hinmil [paths...] [options]
2157
+
2158
+ --project <directory> Project root (default: current directory)
2159
+ --config <file> Explicit hinmil JSON or JS config
2160
+ --format stylish|json Human-readable or machine-readable output
2161
+ --ext <extension> Add an extension (repeatable; e.g. --ext .vue)
2162
+ --help, -h Show usage
2163
+ --version, -v Show the package version
2164
+ ```
2165
+
2166
+ With no paths the project root is scanned. File selection is loaded **before** discovery. The built-in extensions are `.js`, `.jsx`, `.mjs`, `.cjs`, and `.hm`; `--ext` adds to (rather than replaces) the effective list. Explicit file and directory arguments obey the same extension/include/exclude filters as discovered files.
2167
+
2168
+ Configure selection in `package.json#hinmil`, `hinmil.config.json`, or `hinmil.config.js`:
2169
+
2170
+ ```json
2171
+ {
2172
+ "files": {
2173
+ "extensions": [".js", ".jsx", ".mjs", ".cjs", ".hm", ".custom"],
2174
+ "include": ["src/**", "types/**"],
2175
+ "exclude": ["**/*.generated.js", "**/vendor/**"]
2176
+ }
2177
+ }
2178
+ ```
2179
+
2180
+ The precedence is built-in defaults → VS Code `hinmil.files.*` → project `files`; each specified array replaces the lower layer. So an `exclude` of your own must repeat the defaults you still want (`**/node_modules/**`, `**/.git/**`, `**/dist/**`, `**/build/**`, `**/coverage/**`). CLI `--ext` additions apply last. An explicitly empty `include` array selects no files. Exclusion suppresses only standalone diagnostics: an excluded module imported by a selected file is still parsed and inferred. Discovery visits each real directory once and follows symlinked directories only when they stay inside the project root.
2181
+
2182
+ For custom source extensions in VS Code, map them to JavaScript so the editor sends the document with the right language id:
2183
+
2184
+ ```json
2185
+ {
2186
+ "files.associations": { "*.custom": "javascript" },
2187
+ "hinmil.files.extensions": [".js", ".jsx", ".mjs", ".cjs", ".hm", ".custom"]
2188
+ }
2189
+ ```
2190
+
2191
+ Without `--config`, each file is checked with the configuration of its nearest folder (see [Configuration per folder](#configuration-per-folder-monorepos)); within one folder, discovery uses `package.json#hinmil`, then `hinmil.config.js`, then `hinmil.config.json`. An explicit `--config` applies to every file. The file selection (`files`) always comes from the project root (or `--config`). JavaScript config is limited to a JSON-compatible `module.exports` object and is not executed. Exit status is `0` without error diagnostics, `1` with errors, and `2` for argument/config/input failures.
2192
+
2193
+ Use `--format json` for machine-readable output. It emits one object containing `project`, the ordered `checkedFiles`, configuration `warnings`, and ordered `diagnostics`; each diagnostic contains its absolute `file`, severity, HM code, message, and zero-based LSP `range`. A typical CI script can rely directly on the exit status:
2194
+
2195
+ ```json
2196
+ {
2197
+ "scripts": {
2198
+ "typecheck:hm": "hinmil --format json"
2199
+ }
2200
+ }
2201
+ ```
2202
+
2203
+ ```bash
2204
+ npm run typecheck:hm
2205
+ ```
2206
+
2207
+ ---
2208
+
2209
+ ## Diagnostic Codes Reference
2210
+
2211
+ | Code | Category | Description |
2212
+ |------|----------|-------------|
2213
+ | **1001** | Type Error | Type mismatch — cannot unify types |
2214
+ | **1002** | Type Error | Infinite type detected |
2215
+ | **1003** | Type Error | Annotation mismatch |
2216
+ | **1004** | Type Error | Return type doesn't match annotation |
2217
+ | **1005** | Type Error | Missing property on record |
2218
+ | **1006** | Type Error | Unconstrained property access on type variable |
2219
+ | **1007** | Type Error | Unbound variable |
2220
+ | **1008** | Type Error | Record value missing required fields |
2221
+ | **1009** | Type Error | Value is not callable |
2222
+ | **1010** | Type Error | Object literal has a field its named record type (alias) does not declare — usually a typo in an optional field (`form` for `from :: Date \| Undefined`); comes with a "did you mean" hint |
2223
+ | **2001** | Annotation | Invalid annotation syntax |
2224
+ | **2002** | Annotation | Declaration name doesn't match annotation name |
2225
+ | **2003** | Annotation | Method name mismatch |
2226
+ | **2004** | Annotation | Unknown type constructor |
2227
+ | **2005** | Annotation | Using variant method instead of parent method |
2228
+ | **2006** | Annotation | Method type mismatch |
2229
+ | **2007** | Annotation | Nameless annotation (`:: Type`) placed on a named declaration |
2230
+ | **2008** | Annotation | Type constructor applied to the wrong number of arguments |
2231
+ | **2009** | Annotation | Reserved (not emitted at the moment; see `annotationNarrowing`) |
2232
+ | **2010** | Annotation | Missing runtime argument for a `TypeRep` parameter |
2233
+ | **2011** | Annotation | Bare type variable used as a value annotation |
2234
+ | **2012** | Annotation | Method annotation on a bare value type |
2235
+ | **2013** | Annotation | Instance-callable annotation (`Type() ::`) on a type with no constructor |
2236
+ | **2014** | Annotation | Method or static annotation on a type with no constructor |
2237
+ | **2015** | Annotation | Invalid `::narrow` directive |
2238
+ | **3001** | Module | Missing export |
2239
+ | **3002** | Module | Unresolved `::types` path |
2240
+ | **3003** | Module | Unresolved import |
2241
+ | **3004** | Module | Duplicate import |
2242
+ | **3005** | Module | Circular import |
2243
+ | **4001** | Constraint | Unknown constraint name |
2244
+ | **4002** | Constraint | Constraint violation |
2245
+ | **4003** | Constraint | Invalid constraint definition |
2246
+ | **4004** | Constraint | Constraint kind mismatch (e.g. concrete type where a container is required) |
2247
+ | **5001** | Curry | Curry arity mismatch |
2248
+ | **5002** | Curry | Curry type error, or `::curried` in a JavaScript file (only `.hm` files) |
2249
+ | **5003** | Curry | Over-application of curried function |
2250
+ | **5004** | Curry | Fan-out arity mismatch |
2251
+ | **6001** | Info | Missing annotation (informational). Not reported for a point-free binding (`const total = pipe (map (prop ("total")), sum)`); a call that wraps one function literal (`curry ((a, b) => …)`) is still asked |
2252
+ | **6002** | Info | Sum type variant missing an annotated method implementation |
2253
+ | **7001** | Relation | Invalid table relation / picked projection |
2254
+ | **9001** | Parse | Source code parse error |
2255
+
2256
+ ---
2257
+
2258
+ ## Example: Full Workflow
2259
+
2260
+ A small module that combines annotations, a sum type, a constraint, and
2261
+ narrowing:
2262
+
2263
+ ```javascript
2264
+ // Maybe :: Just a | Nothing
2265
+
2266
+ class Just {
2267
+ // Just :: a -> Maybe a
2268
+ constructor(value) { this.value = value; }
2269
+ // Maybe#map :: Maybe a ~> (a -> b) -> Maybe b
2270
+ map(fn) { return new Just(fn(this.value)); }
2271
+ }
2272
+
2273
+ // Nothing :: Maybe a
2274
+ class Nothing {
2275
+ map(_fn) { return new Nothing(); }
2276
+ }
2277
+
2278
+ // ::constraint Functor f { f :: { map :: f a ~> (a -> b) -> f b } }
2279
+
2280
+ // fmap :: Functor f => ((a -> b), f a) -> f b
2281
+ const fmap = (fn, f) => f.map(fn);
2282
+
2283
+ // findDiscount :: Number -> Maybe Number
2284
+ const findDiscount = (total) =>
2285
+ total < 500 ? new Nothing() : new Just(total * 0.05);
2286
+
2287
+ // discounts :: [Number] -> [Maybe Number]
2288
+ const discounts = (totals) => totals.map(findDiscount);
2289
+
2290
+ // ::narrow Number
2291
+ // isNumber :: a -> Boolean
2292
+ const isNumber = (x) => typeof x === 'number';
2293
+
2294
+ // formatReference :: (Number | String) -> String
2295
+ const formatReference = (x) => {
2296
+ if (isNumber(x)) {
2297
+ return x.toFixed(0); // x: Number (narrowed)
2298
+ }
2299
+ return x; // x: String (narrowed)
2300
+ };
2301
+ ```
2302
+
2303
+ ---
2304
+
2305
+ ## License
2306
+
2307
+ MIT — see [LICENSE](LICENSE).