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