hinmil 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +2306 -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 +384 -0
- package/dist/commentParser.d.ts.map +1 -0
- package/dist/commentParser.js +2487 -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 +277 -0
- package/dist/infer/annotations.d.ts.map +1 -0
- package/dist/infer/annotations.js +1343 -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 +1468 -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 +20 -0
- package/dist/infer/expr-functions.d.ts.map +1 -0
- package/dist/infer/expr-functions.js +1359 -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 +1154 -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 +1035 -0
- package/dist/infer/functionPatterns.js.map +1 -0
- package/dist/infer/helpers.d.ts +73 -0
- package/dist/infer/helpers.d.ts.map +1 -0
- package/dist/infer/helpers.js +187 -0
- package/dist/infer/helpers.js.map +1 -0
- package/dist/infer/index.d.ts +551 -0
- package/dist/infer/index.d.ts.map +1 -0
- package/dist/infer/index.js +1127 -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 +524 -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 +239 -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 +665 -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 +342 -0
- package/dist/services/files.d.ts.map +1 -0
- package/dist/services/files.js +1712 -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 +686 -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 +53 -4
- package/schemas/hinmil.config.schema.json +261 -0
- package/schemas/package-hinmil.schema.json +59 -0
|
@@ -0,0 +1,1482 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ============================================================================
|
|
3
|
+
// Named-binding & function-declaration inference: annotation validation,
|
|
4
|
+
// display-type alignment, generative-var freshening (extracted from statements.ts)
|
|
5
|
+
//
|
|
6
|
+
// Plain language: handles giving a name a type — `const x = …` and
|
|
7
|
+
// `function f() { … }`. The inferred type of the right-hand side is
|
|
8
|
+
// compared against any `::` annotation above it (mismatches become
|
|
9
|
+
// diagnostics), and the finished type is sealed into a reusable template
|
|
10
|
+
// (generalized) and entered into the environment under the name.
|
|
11
|
+
// ============================================================================
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.inferNamedBinding = inferNamedBinding;
|
|
14
|
+
exports.inferFunctionDeclaration = inferFunctionDeclaration;
|
|
15
|
+
const types_1 = require("../hm/types");
|
|
16
|
+
const env_1 = require("../hm/env");
|
|
17
|
+
const unify_1 = require("../hm/unify");
|
|
18
|
+
const typeUtils_1 = require("../hm/typeUtils");
|
|
19
|
+
const narrowing_1 = require("./narrowing");
|
|
20
|
+
const annotation_rigid_1 = require("./annotation-rigid");
|
|
21
|
+
const annotations_1 = require("./annotations");
|
|
22
|
+
const helpers_1 = require("./helpers");
|
|
23
|
+
const dataTypeRegistry_1 = require("../registries/dataTypeRegistry");
|
|
24
|
+
const methodRegistry_1 = require("../registries/methodRegistry");
|
|
25
|
+
const expr_member_1 = require("./expr-member");
|
|
26
|
+
const debugLog_1 = require("../debugLog");
|
|
27
|
+
const commentParser_1 = require("../commentParser");
|
|
28
|
+
/**
|
|
29
|
+
* Collect 0-based indices of function parameters that have a JS default
|
|
30
|
+
* value (Acorn `AssignmentPattern`). Used to mark trailing parameters as
|
|
31
|
+
* optional at call sites — `Path("p", [1,2])` is allowed when the
|
|
32
|
+
* implementation declares `(k, r, defaultValue = undefined) => …`.
|
|
33
|
+
*/
|
|
34
|
+
function collectOptionalParamSlots(params) {
|
|
35
|
+
if (!params || params.length === 0)
|
|
36
|
+
return [];
|
|
37
|
+
const result = [];
|
|
38
|
+
for (let i = 0; i < params.length; i++) {
|
|
39
|
+
if (params[i]?.type === 'AssignmentPattern')
|
|
40
|
+
result.push(i);
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* When true, the function is a factory/constructor for that sum type and
|
|
46
|
+
* record-vs-TCon mismatches should be suppressed (the annotation is the
|
|
47
|
+
* source of truth).
|
|
48
|
+
*/
|
|
49
|
+
function annotationReturnsSumType(scheme) {
|
|
50
|
+
const ret = (0, types_1.getReturnType)(scheme.type);
|
|
51
|
+
return ret.tag === 'TCon' && (0, dataTypeRegistry_1.isDataType)(ret.name);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Check whether an annotation scheme's return type is a user-defined nominal
|
|
55
|
+
* type constructor: not a builtin and not a type alias. This covers sumtypes,
|
|
56
|
+
* classes, ADT factories with `Type#method` annotations, AND plain record
|
|
57
|
+
* factories that introduce a type by their annotation alone
|
|
58
|
+
* (`// Box :: a -> Box a` above `x => ({ value: x })`): the record literal is
|
|
59
|
+
* the runtime representation and the constructor annotation names it.
|
|
60
|
+
*/
|
|
61
|
+
function annotationReturnsNominalUserType(scheme, typeAliases) {
|
|
62
|
+
const ret = (0, types_1.getReturnType)(scheme.type);
|
|
63
|
+
return ret.tag === 'TCon' && !(0, methodRegistry_1.isBuiltinType)(ret.name) && !typeAliases.has(ret.name);
|
|
64
|
+
}
|
|
65
|
+
/** User type with `Type#method`/property annotations (class, ADT factory). */
|
|
66
|
+
function annotationReturnsTConWithMethods(scheme) {
|
|
67
|
+
const ret = (0, types_1.getReturnType)(scheme.type);
|
|
68
|
+
return ret.tag === 'TCon' && !(0, methodRegistry_1.isBuiltinType)(ret.name) && (0, methodRegistry_1.getMethodNames)(ret.name).length > 0;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Check whether the sumtype factory guard should suppress type checking.
|
|
72
|
+
* Only suppress when:
|
|
73
|
+
* 1. The annotation's return type is a sumtype or a TCon with registered
|
|
74
|
+
* methods (a nominal type known only from the annotation accepts ONLY
|
|
75
|
+
* a record literal), AND
|
|
76
|
+
* 2. The inferred return type is:
|
|
77
|
+
* - TRecord (the body returns a record literal — the runtime representation), or
|
|
78
|
+
* - TVar (return type not yet resolved, e.g. helper defined later), or
|
|
79
|
+
* - a sumtype TCon (body delegates to another function returning the
|
|
80
|
+
* same or another registered sumtype).
|
|
81
|
+
* TCon primitives (Number, String, Void, …) and TFun are real mismatches.
|
|
82
|
+
*/
|
|
83
|
+
function shouldSuppressSumTypeCheck(scheme, inferredType, typeAliases) {
|
|
84
|
+
if (!annotationReturnsSumType(scheme) && !annotationReturnsNominalUserType(scheme, typeAliases))
|
|
85
|
+
return false;
|
|
86
|
+
let inferredReturn = (0, types_1.getReturnType)(inferredType);
|
|
87
|
+
// A body checked against rigid skolems returns the parameter's skolem
|
|
88
|
+
// where an unannotated body would return a free var — same leniency.
|
|
89
|
+
if ((0, types_1.isSkolem)(inferredReturn))
|
|
90
|
+
inferredReturn = (0, types_1.tVar)();
|
|
91
|
+
// A nominal type known ONLY from this annotation (no sumtype, no
|
|
92
|
+
// `Type#method`s) is introduced by a record literal and nothing else:
|
|
93
|
+
// returning a parameter (`a => a` for `a -> Box a`) or a primitive is a
|
|
94
|
+
// real mismatch.
|
|
95
|
+
if (!annotationReturnsSumType(scheme) && !annotationReturnsTConWithMethods(scheme)) {
|
|
96
|
+
return inferredReturn.tag === 'TRecord';
|
|
97
|
+
}
|
|
98
|
+
if (inferredReturn.tag === 'TVar'
|
|
99
|
+
|| (inferredReturn.tag === 'TCon' && (0, dataTypeRegistry_1.isDataType)(inferredReturn.name))) {
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
// Empty-body constructor trust: a stub/empty body infers a Void/Undefined
|
|
103
|
+
// return (e.g. `function Nothing() {}`), but the annotation legitimately
|
|
104
|
+
// declares a data/sum type return (`() -> Maybe a`). The annotation is the
|
|
105
|
+
// source of truth for such constructors, so suppress the mismatch.
|
|
106
|
+
if (inferredReturn.tag === 'TCon'
|
|
107
|
+
&& (inferredReturn.name === 'Void' || inferredReturn.name === 'Undefined')) {
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
if (inferredReturn.tag === 'TRecord') {
|
|
111
|
+
// Suppress unification for factory functions returning a TCon with
|
|
112
|
+
// registered methods so that checkMissingRecordFields can produce a
|
|
113
|
+
// more helpful diagnostic when fields are missing, instead of the
|
|
114
|
+
// generic "Cannot unify {} with Type" error.
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
/**
|
|
120
|
+
* When the sumtype factory guard suppressed the full type check (inferred
|
|
121
|
+
* return is TRecord with all required keys), validate that each field's type
|
|
122
|
+
* matches the registered method/property signature.
|
|
123
|
+
*
|
|
124
|
+
* Uses the instantiated expectedType to get the correct fresh type variables
|
|
125
|
+
* for the sumtype's type parameters, then builds an expected record from the
|
|
126
|
+
* registered method factories and unifies it against the inferred record.
|
|
127
|
+
*
|
|
128
|
+
* Union types (e.g. `a | e` from `Either2#value :: Either2 e a ~> a | e`) are
|
|
129
|
+
* replaced with fresh TVars before unifying so that variant-specific property
|
|
130
|
+
* types don't cause infinite-type errors against the general union.
|
|
131
|
+
*/
|
|
132
|
+
function validateSumTypeFactoryFields(engine, scheme, inferredType, expectedType, node) {
|
|
133
|
+
const inferredReturn = (0, types_1.getReturnType)(inferredType);
|
|
134
|
+
if (inferredReturn.tag !== 'TRecord')
|
|
135
|
+
return;
|
|
136
|
+
const annReturn = (0, types_1.getReturnType)(scheme.type);
|
|
137
|
+
if (annReturn.tag !== 'TCon')
|
|
138
|
+
return;
|
|
139
|
+
const typeName = annReturn.name;
|
|
140
|
+
const methodNames = (0, methodRegistry_1.getMethodNames)(typeName);
|
|
141
|
+
if (methodNames.length === 0)
|
|
142
|
+
return;
|
|
143
|
+
// Use the instantiated expected type to get fresh type vars for type params
|
|
144
|
+
const expReturn = expectedType ? (0, types_1.getReturnType)(expectedType) : null;
|
|
145
|
+
const typeArgs = (expReturn?.tag === 'TCon' ? expReturn.args : []);
|
|
146
|
+
const expectedFields = {};
|
|
147
|
+
for (const mn of methodNames) {
|
|
148
|
+
const entry = (0, methodRegistry_1.lookupMethod)(typeName, mn);
|
|
149
|
+
if (entry && !entry.isStatic) {
|
|
150
|
+
expectedFields[mn] = (0, typeUtils_1.neutralizeUnions)(entry.factory(typeArgs));
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const expectedRecord = (0, types_1.tRecord)(expectedFields);
|
|
154
|
+
engine.unifyWithDiagnostic(inferredReturn, expectedRecord, node);
|
|
155
|
+
}
|
|
156
|
+
/** A record field that may be absent from an object literal: its type
|
|
157
|
+
* admits `Undefined` (`T | Undefined`). */
|
|
158
|
+
function isOptionalRecordField(engine, fieldType) {
|
|
159
|
+
return (0, narrowing_1.typeAcceptsUndefined)(engine.subst, fieldType);
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Check whether a function's inferred return type (record) is missing fields
|
|
163
|
+
* compared to the annotation's return type (after alias expansion).
|
|
164
|
+
* Produces a diagnostic listing the missing fields.
|
|
165
|
+
*/
|
|
166
|
+
function checkMissingRecordFields(engine, inferredType, annotationScheme, node) {
|
|
167
|
+
const inferredReturn = (0, types_1.getReturnType)(engine.subst.apply(inferredType));
|
|
168
|
+
if (inferredReturn.tag !== 'TRecord')
|
|
169
|
+
return;
|
|
170
|
+
const annotReturn = (0, types_1.getReturnType)(annotationScheme.type);
|
|
171
|
+
const expandedReturn = (0, annotations_1.expandAliases)(engine.typeAliases, annotReturn, undefined, engine.typeAliasVars);
|
|
172
|
+
let expectedKeys;
|
|
173
|
+
let typeName;
|
|
174
|
+
if (expandedReturn.tag === 'TRecord') {
|
|
175
|
+
expectedKeys = Object.keys(expandedReturn.fields);
|
|
176
|
+
typeName = expandedReturn.alias ?? (0, types_1.prettyTypeToString)(expandedReturn);
|
|
177
|
+
}
|
|
178
|
+
else if (expandedReturn.tag === 'TCon' && !(0, methodRegistry_1.isBuiltinType)(expandedReturn.name) && (0, methodRegistry_1.getMethodNames)(expandedReturn.name).length > 0) {
|
|
179
|
+
// For TCon return types with registered methods (sumtype, classes, ADT
|
|
180
|
+
// factories), use registered instance methods as expected fields
|
|
181
|
+
expectedKeys = (0, methodRegistry_1.getMethodNames)(expandedReturn.name).filter(n => {
|
|
182
|
+
const entry = (0, methodRegistry_1.lookupMethod)(expandedReturn.name, n);
|
|
183
|
+
return !entry?.isStatic;
|
|
184
|
+
});
|
|
185
|
+
typeName = expandedReturn.name;
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (expectedKeys.length === 0)
|
|
191
|
+
return;
|
|
192
|
+
const inferredKeys = new Set(Object.keys(inferredReturn.fields));
|
|
193
|
+
// A field typed `T | Undefined` may be left out (reading it gives
|
|
194
|
+
// `undefined`), as for an argument (`findMissingRecordFields`).
|
|
195
|
+
const optionalKeys = expandedReturn.tag === 'TRecord'
|
|
196
|
+
? new Set(expectedKeys.filter(k => isOptionalRecordField(engine, expandedReturn.fields[k])))
|
|
197
|
+
: new Set();
|
|
198
|
+
const missingKeys = expectedKeys.filter(k => !inferredKeys.has(k) && !optionalKeys.has(k));
|
|
199
|
+
if (missingKeys.length > 0) {
|
|
200
|
+
engine.addDiag(`Missing record fields: ${missingKeys.map(k => `'${k}'`).join(', ')} required by ${typeName}`, (0, annotations_1.narrowToIdentifier)(node));
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Check if a type contains any wildcard ('*' or '*:name') anywhere.
|
|
205
|
+
* When `vars` is given, only check if TVars with those ids would be
|
|
206
|
+
* wildcards (used to inspect the annotation's original type shape).
|
|
207
|
+
*/
|
|
208
|
+
function wildcardInType(t, vars) {
|
|
209
|
+
return (0, typeUtils_1.someType)(t, n => {
|
|
210
|
+
if (!vars)
|
|
211
|
+
return (0, types_1.isWildcard)(n);
|
|
212
|
+
if (n.tag === 'TVar' || n.tag === 'TRow')
|
|
213
|
+
return vars.has(n.id);
|
|
214
|
+
if (n.tag === 'TLabel' && n.kind === 'var')
|
|
215
|
+
return vars.has(n.id);
|
|
216
|
+
return false;
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Infer and verify a simple named variable binding that has an initialiser.
|
|
221
|
+
* Handles annotation lookup, expected-type setup, body inference,
|
|
222
|
+
* polymorphic / concrete rigid checks, and pending curry / conditional-return
|
|
223
|
+
/**
|
|
224
|
+
* Collect names of unknown type constructors that already have a
|
|
225
|
+
* "Unknown type constructor 'X'" diagnostic recorded. Used by
|
|
226
|
+
* `emitAnnotationUnify` so we don't double-report a mismatch whose
|
|
227
|
+
* cause is already a missing type.
|
|
228
|
+
*/
|
|
229
|
+
function collectUnknownTConNames(diagnostics) {
|
|
230
|
+
const names = new Set();
|
|
231
|
+
for (const d of diagnostics) {
|
|
232
|
+
const m = d.message.match(/Unknown type constructor '([^']+)'/);
|
|
233
|
+
if (m)
|
|
234
|
+
names.add(m[1]);
|
|
235
|
+
}
|
|
236
|
+
return names;
|
|
237
|
+
}
|
|
238
|
+
/** Whether a type mentions any of the given (unknown) TCon names. */
|
|
239
|
+
function typeMentions(t, names) {
|
|
240
|
+
if (names.size === 0)
|
|
241
|
+
return false;
|
|
242
|
+
let found = false;
|
|
243
|
+
(0, typeUtils_1.eachType)(t, n => { if (n.tag === 'TCon' && names.has(n.name))
|
|
244
|
+
found = true; });
|
|
245
|
+
return found;
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Run a unify(initType, annotatedType) inside annotation validation and
|
|
249
|
+
* emit the unified `Type mismatch: '<name>' has type ...` diagnostic on
|
|
250
|
+
* failure. Suppresses the diagnostic when the failing sub-types reference
|
|
251
|
+
* an unknown type constructor that already has its own diagnostic — the
|
|
252
|
+
* mismatch is then a consequence of the missing type, not a real error.
|
|
253
|
+
*/
|
|
254
|
+
function emitAnnotationUnify(engine, initType, annotatedType, decl) {
|
|
255
|
+
// Closed-vs-record annotations: surface fields declared in the annotation
|
|
256
|
+
// that the inferred value doesn't actually carry. Done BEFORE unify so
|
|
257
|
+
// that an open record's row variable hasn't yet absorbed the surplus.
|
|
258
|
+
// - inferred closed + annotation closed: lenient unifier won't flag this
|
|
259
|
+
// - inferred open + annotation closed: row variable would silently
|
|
260
|
+
// absorb annotation-only fields ("the row could contain x"), but the
|
|
261
|
+
// value clearly doesn't, so we flag it explicitly.
|
|
262
|
+
{
|
|
263
|
+
const r1 = engine.resolve(initType);
|
|
264
|
+
const r2 = engine.resolve(annotatedType);
|
|
265
|
+
if (r1.tag === 'TRecord' && r2.tag === 'TRecord' && !r2.rest) {
|
|
266
|
+
const inferredKeys = new Set(Object.keys(r1.fields));
|
|
267
|
+
const missing = Object.keys(r2.fields).filter(k => !inferredKeys.has(k) && !isOptionalRecordField(engine, r2.fields[k]));
|
|
268
|
+
if (missing.length > 0) {
|
|
269
|
+
engine.addDiag(`Missing record fields: ${missing.map(k => `'${k}'`).join(', ')} required by ${(0, types_1.prettyTypeToString)(r2)}`, (0, annotations_1.narrowToIdentifier)(decl));
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
try {
|
|
274
|
+
const s = (0, unify_1.unify)(engine.resolve(initType), engine.resolve(annotatedType));
|
|
275
|
+
engine.subst.mergeFrom(s);
|
|
276
|
+
}
|
|
277
|
+
catch (e) {
|
|
278
|
+
if (!(e instanceof unify_1.UnificationError))
|
|
279
|
+
throw e;
|
|
280
|
+
const r1 = engine.resolve(initType);
|
|
281
|
+
const r2 = engine.resolve(annotatedType);
|
|
282
|
+
if ((0, types_1.containsErrorType)(r1) || (0, types_1.containsErrorType)(r2))
|
|
283
|
+
return;
|
|
284
|
+
// TCon → callable overload promotion.
|
|
285
|
+
// When the inferred type is a bare TCon (e.g. `QueryTag b` returned by a
|
|
286
|
+
// call to `Organisation([...])`) and that constructor has an overloaded
|
|
287
|
+
// callable form declared in the annotation map or imported sidecar
|
|
288
|
+
// (e.g. `QueryTag :: a -> RTask r e [b]`), accept the user's annotation
|
|
289
|
+
// when it unifies against ANY of those callable branches. This mirrors
|
|
290
|
+
// the constructor-as-callable bridge in `inferCallExpression`.
|
|
291
|
+
if (r1.tag === 'TCon' && /^[A-Z]/.test(r1.name)) {
|
|
292
|
+
// Honour the file-local annotation only. A sidecar / globals /
|
|
293
|
+
// `::types` entry for a constructor name owned by a different module
|
|
294
|
+
// must not promote this file's TCon into a callable shape.
|
|
295
|
+
const localAnn = engine.annotationMap.get(r1.name);
|
|
296
|
+
const localScheme = (0, commentParser_1.isLocalAnnotation)(localAnn) ? localAnn?.scheme : undefined;
|
|
297
|
+
const importedScheme = engine.importedConstructors.get(r1.name);
|
|
298
|
+
const scheme = localScheme ?? importedScheme;
|
|
299
|
+
if (scheme) {
|
|
300
|
+
const inst = (0, env_1.instantiate)(scheme);
|
|
301
|
+
const candidates = inst.tag === 'TCon' && inst.name === types_1.T_UNION
|
|
302
|
+
? inst.args
|
|
303
|
+
: [inst];
|
|
304
|
+
for (const cand of candidates) {
|
|
305
|
+
try {
|
|
306
|
+
const s = (0, unify_1.unify)(cand, r2);
|
|
307
|
+
engine.subst.mergeFrom(s);
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
catch (err) {
|
|
311
|
+
if (!(err instanceof unify_1.UnificationError))
|
|
312
|
+
throw err;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
// Fold-completion leniency (mirrors unifyWithDiagnostic): a TOP-LEVEL
|
|
318
|
+
// spread arrow chain reconciled against a non-function annotation stands
|
|
319
|
+
// for "the chain once fully applied" — retry with the chain's terminal
|
|
320
|
+
// result before surfacing a mismatch.
|
|
321
|
+
{
|
|
322
|
+
const pair = r1.tag === 'TFun' && (0, typeUtils_1.hasTopLevelSpreadChain)(r1) && r2.tag !== 'TFun' ? [r1, r2] :
|
|
323
|
+
r2.tag === 'TFun' && (0, typeUtils_1.hasTopLevelSpreadChain)(r2) && r1.tag !== 'TFun' ? [r2, r1] :
|
|
324
|
+
null;
|
|
325
|
+
if (pair) {
|
|
326
|
+
try {
|
|
327
|
+
const s = (0, unify_1.unify)((0, types_1.flattenCurriedType)(pair[0]).result, pair[1]);
|
|
328
|
+
engine.subst.mergeFrom(s);
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
catch (err) {
|
|
332
|
+
if (!(err instanceof unify_1.UnificationError))
|
|
333
|
+
throw err;
|
|
334
|
+
// fall through to normal diagnostic path
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
// A narrower union where a wider one is declared: a function that
|
|
339
|
+
// returns `ReactElement | Null` satisfies `… -> ReactElement | String |
|
|
340
|
+
// Null` (covariant result). Symmetric unification rejects two different
|
|
341
|
+
// unions, so check the direction here, at the annotation.
|
|
342
|
+
{
|
|
343
|
+
const widened = (0, unify_1.unifyWidening)(r1, r2);
|
|
344
|
+
if (widened) {
|
|
345
|
+
engine.subst.mergeFrom(widened);
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const unknownNames = collectUnknownTConNames(engine.diagnostics);
|
|
350
|
+
if (typeMentions(e.left, unknownNames) || typeMentions(e.right, unknownNames))
|
|
351
|
+
return;
|
|
352
|
+
if ((0, types_1.containsErrorType)(r1) || (0, types_1.containsErrorType)(r2))
|
|
353
|
+
return;
|
|
354
|
+
engine.addDiag((0, annotations_1.annotationMismatchMessage)((0, annotations_1.bindingNameFromNode)(decl), r1, r2), (0, annotations_1.narrowToIdentifier)(decl));
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Validate the inferred type of an annotated binding against its annotation.
|
|
359
|
+
* Handles both polymorphic (quantified) and concrete annotations:
|
|
360
|
+
* wildcard return checks, rigid checks, union narrowing, sum-type factory
|
|
361
|
+
* field validation, and missing record field checks.
|
|
362
|
+
*/
|
|
363
|
+
function validateAnnotatedBindingType(engine, scheme, initType, expectedType, decl, naturalRecordFields = null) {
|
|
364
|
+
// Closed-record annotations: when a trial inference revealed the
|
|
365
|
+
// value's natural fields, complain about annotation-only fields up
|
|
366
|
+
// front (the expected-type-driven inference would otherwise have
|
|
367
|
+
// silently absorbed them into a row variable).
|
|
368
|
+
if (naturalRecordFields && expectedType) {
|
|
369
|
+
const annReturn = (0, types_1.getReturnType)(expectedType);
|
|
370
|
+
if (annReturn.tag === 'TRecord' && !annReturn.rest) {
|
|
371
|
+
const missing = Object.keys(annReturn.fields).filter(k => !naturalRecordFields.has(k) && !isOptionalRecordField(engine, annReturn.fields[k]));
|
|
372
|
+
if (missing.length > 0) {
|
|
373
|
+
engine.addDiag(`Missing record fields: ${missing.map(k => `'${k}'`).join(', ')} required by ${(0, types_1.prettyTypeToString)(annReturn)}`, (0, annotations_1.narrowToIdentifier)(decl));
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
if (scheme.vars.length > 0) {
|
|
378
|
+
// Wildcard return check: when instantiateWithAny was used, a quantified
|
|
379
|
+
// var in param position (e.g. `a` in `a -> String`) becomes a wildcard.
|
|
380
|
+
// If the implementation returns that wildcard (e.g. `return x`) the
|
|
381
|
+
// unifier silently accepts it against the concrete return type.
|
|
382
|
+
// Detect this: if the annotation return type is concrete but the
|
|
383
|
+
// inferred return type (before substitution flattened it) still
|
|
384
|
+
// contains a wildcard, then the implementation doesn't actually
|
|
385
|
+
// produce the declared return type.
|
|
386
|
+
const hasConstraints = scheme.constraints && scheme.constraints.length > 0;
|
|
387
|
+
if (!hasConstraints && scheme.vars.length > 0) {
|
|
388
|
+
const annReturnType = (0, types_1.getReturnType)(scheme.type);
|
|
389
|
+
const inferredReturnType = (0, types_1.getReturnType)(initType);
|
|
390
|
+
const resolvedReturn = engine.subst.apply(inferredReturnType);
|
|
391
|
+
if (!wildcardInType(annReturnType, new Set(scheme.vars)) && wildcardInType(resolvedReturn)) {
|
|
392
|
+
const expectedReturn = (0, types_1.getReturnType)((0, env_1.instantiate)(scheme));
|
|
393
|
+
if (!(0, types_1.containsErrorType)(resolvedReturn) && !(0, types_1.containsErrorType)(expectedReturn)
|
|
394
|
+
// Sumtype factories: the annotation is the source of truth and
|
|
395
|
+
// the body typically returns a record with wildcard fields from
|
|
396
|
+
// unannotated params (e.g. `Object.create(proto)` in Param.js).
|
|
397
|
+
&& !annotationReturnsSumType(scheme)) {
|
|
398
|
+
const subject = (0, annotations_1.bindingNameFromNode)(decl);
|
|
399
|
+
const subjectStr = subject ? `'${subject}'` : 'value';
|
|
400
|
+
engine.addDiag(`Type mismatch: ${subjectStr} returns a generic value but annotation expects '${(0, types_1.prettyTypeToString)(expectedReturn)}'`, (0, annotations_1.narrowToIdentifier)(decl));
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
// Polymorphic annotation — run rigid check when appropriate.
|
|
405
|
+
// Skip for factory functions whose return type is a sumtype TCon —
|
|
406
|
+
// the returned record literal IS the runtime representation and the
|
|
407
|
+
// annotation is the source of truth.
|
|
408
|
+
if ((0, annotations_1.hasUnknownTConDiagForScheme)(engine.diagnostics, scheme)) {
|
|
409
|
+
// Annotation references unknown type constructors — skip all
|
|
410
|
+
// mismatch checks; the "unknown type constructor" diagnostic is
|
|
411
|
+
// sufficient.
|
|
412
|
+
}
|
|
413
|
+
else if (!shouldSuppressSumTypeCheck(scheme, initType, engine.typeAliases)) {
|
|
414
|
+
const isFunctionInit = decl.init
|
|
415
|
+
&& (decl.init.type === 'ArrowFunctionExpression' || decl.init.type === 'FunctionExpression');
|
|
416
|
+
// A function BUILT by a call (`const f = curry ((a, b) => …)`,
|
|
417
|
+
// `compose (g) (h)`) is checked as rigidly as a literal arrow: its
|
|
418
|
+
// annotation must be an instance of what the call produces, so a
|
|
419
|
+
// signature like `tap :: (a -> b) -> a -> b` for a body that returns its
|
|
420
|
+
// second argument is reported instead of unified away.
|
|
421
|
+
const isCallBuiltFunction = decl.init?.type === 'CallExpression'
|
|
422
|
+
&& engine.subst.apply(initType).tag === 'TFun'
|
|
423
|
+
&& scheme.type.tag === 'TFun';
|
|
424
|
+
if ((isFunctionInit || isCallBuiltFunction) && !(0, annotation_rigid_1.usesLenientArrowCheck)(scheme)) {
|
|
425
|
+
// Same rigid check as `function` declarations.
|
|
426
|
+
engine.checkRigid(initType, scheme, decl);
|
|
427
|
+
}
|
|
428
|
+
else {
|
|
429
|
+
(0, annotations_1.maybeRigidCheck)({ subst: engine.subst, typeAliases: engine.typeAliases, diagnostics: engine.diagnostics, addDiag: engine.boundAddDiag, aliasVars: engine.typeAliasVars }, initType, scheme, decl);
|
|
430
|
+
}
|
|
431
|
+
// Catch trivially-broken bodies that the rigid check skips for
|
|
432
|
+
// spread-annotated polymorphic functions: when the annotation's
|
|
433
|
+
// immediate return type is itself a function but the body returns
|
|
434
|
+
// a concrete non-function value (e.g. an empty block returning `Void`).
|
|
435
|
+
const annOuterReturn = scheme.type.tag === 'TFun' ? scheme.type.result : scheme.type;
|
|
436
|
+
const inferredAppliedInit = engine.subst.apply(initType);
|
|
437
|
+
const inferredOuterReturn = inferredAppliedInit.tag === 'TFun'
|
|
438
|
+
? engine.subst.apply(inferredAppliedInit.result)
|
|
439
|
+
: inferredAppliedInit;
|
|
440
|
+
if (annOuterReturn.tag === 'TFun'
|
|
441
|
+
&& inferredOuterReturn.tag === 'TCon'
|
|
442
|
+
&& (inferredOuterReturn.name === 'Void' || inferredOuterReturn.name === 'Undefined')
|
|
443
|
+
&& !engine.diagnostics.some(d => d.message.startsWith('Type mismatch:'))) {
|
|
444
|
+
const annotatedType = expectedType ?? (0, env_1.instantiate)(scheme);
|
|
445
|
+
if (!(0, types_1.containsErrorType)(inferredAppliedInit) && !(0, types_1.containsErrorType)(annotatedType)) {
|
|
446
|
+
engine.addDiag((0, annotations_1.annotationMismatchMessage)((0, annotations_1.bindingNameFromNode)(decl), inferredAppliedInit, annotatedType), (0, annotations_1.narrowToIdentifier)(decl));
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
// When an infinite type error was suppressed during constrained
|
|
450
|
+
// annotation body inference, the body's usage of a parameter
|
|
451
|
+
// conflicts with its declared annotation type (e.g. annotation says
|
|
452
|
+
// `a -> b` but a constraint method requires `a -> m b`). The rigid
|
|
453
|
+
// check can't catch this because the annotation drives inference,
|
|
454
|
+
// making the inferred type match trivially.
|
|
455
|
+
if (hasConstraints && engine.infiniteTypeSuppressedDuringAnnotation) {
|
|
456
|
+
const annotatedType = expectedType ?? (0, env_1.instantiate)(scheme);
|
|
457
|
+
const inferredApplied = engine.subst.apply(initType);
|
|
458
|
+
if (!(0, types_1.containsErrorType)(inferredApplied) && !(0, types_1.containsErrorType)(annotatedType)) {
|
|
459
|
+
engine.addDiag((0, annotations_1.annotationMismatchMessage)((0, annotations_1.bindingNameFromNode)(decl), inferredApplied, annotatedType), (0, annotations_1.narrowToIdentifier)(decl));
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
// For sumtype factory annotations that weren't suppressed (e.g.
|
|
463
|
+
// body returns a primitive instead of a record), also unify to
|
|
464
|
+
// produce the unified mismatch diagnostic.
|
|
465
|
+
if (annotationReturnsSumType(scheme)) {
|
|
466
|
+
const annotatedType = expectedType ?? (0, env_1.instantiate)(scheme);
|
|
467
|
+
emitAnnotationUnify(engine, initType, annotatedType, decl);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
else {
|
|
471
|
+
validateSumTypeFactoryFields(engine, scheme, initType, expectedType, decl);
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
else {
|
|
475
|
+
// Concrete annotation — still verify inferred matches.
|
|
476
|
+
// Skip for factory functions that return a sumtype TCon.
|
|
477
|
+
// (Note: per-failure suppression for unknown TCons is handled by
|
|
478
|
+
// `emitAnnotationUnify` so a real mismatch in an unrelated part of
|
|
479
|
+
// the type still fires even when an alias references an unknown type.)
|
|
480
|
+
if (!shouldSuppressSumTypeCheck(scheme, initType, engine.typeAliases)) {
|
|
481
|
+
const annotatedType = expectedType ?? (0, env_1.instantiate)(scheme);
|
|
482
|
+
// Detect unsafe union narrowing: the inferred type is a union but the
|
|
483
|
+
// annotation is a non-union concrete type that matches only a subset.
|
|
484
|
+
// This is reported up-front because tryAutoUnion may otherwise let
|
|
485
|
+
// unification silently pick a matching member.
|
|
486
|
+
const resolvedInit = engine.subst.apply(initType);
|
|
487
|
+
if ((0, types_1.isUnion)(resolvedInit) && !(0, types_1.isUnion)(annotatedType)
|
|
488
|
+
&& assertsPresentLookup(engine, decl, resolvedInit, annotatedType)) {
|
|
489
|
+
// The annotation states that a lookup did not miss (see
|
|
490
|
+
// `assertsPresentLookup`): the binding has the annotated type.
|
|
491
|
+
}
|
|
492
|
+
else if ((0, types_1.isUnion)(resolvedInit) && !(0, types_1.isUnion)(annotatedType)) {
|
|
493
|
+
if (!(0, types_1.containsErrorType)(resolvedInit) && !(0, types_1.containsErrorType)(annotatedType)) {
|
|
494
|
+
engine.addDiag((0, annotations_1.annotationMismatchMessage)((0, annotations_1.bindingNameFromNode)(decl), resolvedInit, annotatedType), (0, annotations_1.narrowToIdentifier)(decl));
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
else {
|
|
498
|
+
emitAnnotationUnify(engine, initType, annotatedType, decl);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
else {
|
|
502
|
+
validateSumTypeFactoryFields(engine, scheme, initType, expectedType, decl);
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
// Check for missing record fields in the return type
|
|
506
|
+
checkMissingRecordFields(engine, initType, scheme, decl);
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Validate a `::narrow` type-predicate against the JS function it is attached
|
|
510
|
+
* to. The narrowed parameter is always the last curried parameter (resolved
|
|
511
|
+
* at parse time), so the only remaining runtime check is that a `[k]` label
|
|
512
|
+
* referenced by the narrowed type is supplied by some signature parameter.
|
|
513
|
+
*/
|
|
514
|
+
function resolveNarrowPredicate(engine, annotation) {
|
|
515
|
+
const pred = annotation.scheme?.typePredicate;
|
|
516
|
+
if (!pred)
|
|
517
|
+
return;
|
|
518
|
+
const loc = annotation.narrowLoc ?? { start: annotation.commentStart, end: annotation.commentEnd };
|
|
519
|
+
// The narrowed type references a label `[k]` but no signature parameter
|
|
520
|
+
// supplies its value.
|
|
521
|
+
if (pred.keyVarName && pred.keyParamIndex === undefined) {
|
|
522
|
+
engine.addDiag(`::narrow label '[${pred.keyVarName}]' does not match any parameter of this function`, loc);
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* The function expression produced by a thunk body — either an expression-bodied
|
|
527
|
+
* arrow (`() => g`) or a block whose (last) `return` yields a function
|
|
528
|
+
* (`() => { …; return g; }`). Returns undefined when the thunk does not
|
|
529
|
+
* directly return a function.
|
|
530
|
+
*/
|
|
531
|
+
function returnedFunctionNode(body) {
|
|
532
|
+
if (!body)
|
|
533
|
+
return undefined;
|
|
534
|
+
if (body.type === 'ArrowFunctionExpression' || body.type === 'FunctionExpression') {
|
|
535
|
+
return body;
|
|
536
|
+
}
|
|
537
|
+
if (body.type === 'BlockStatement') {
|
|
538
|
+
const stmts = body.body;
|
|
539
|
+
for (let i = stmts.length - 1; i >= 0; i--) {
|
|
540
|
+
const s = stmts[i];
|
|
541
|
+
if (s.type === 'ReturnStatement') {
|
|
542
|
+
const arg = s.argument;
|
|
543
|
+
return arg && (arg.type === 'ArrowFunctionExpression' || arg.type === 'FunctionExpression')
|
|
544
|
+
? arg
|
|
545
|
+
: undefined;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
return undefined;
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* Resolve the function node whose parameter chain an overload-union display
|
|
553
|
+
* should annotate. Normally this is the initializer itself (a direct arrow /
|
|
554
|
+
* function), but for an IIFE — `const f = (() => … return g)()` — the relevant
|
|
555
|
+
* function is the one the thunk RETURNS, so descend through a zero-arg call of
|
|
556
|
+
* a zero-param thunk to its returned function expression.
|
|
557
|
+
*/
|
|
558
|
+
function effectiveAnnotatedFunctionNode(init) {
|
|
559
|
+
if (!init)
|
|
560
|
+
return undefined;
|
|
561
|
+
if (init.type === 'ArrowFunctionExpression' || init.type === 'FunctionExpression') {
|
|
562
|
+
return init;
|
|
563
|
+
}
|
|
564
|
+
if (init.type === 'CallExpression') {
|
|
565
|
+
const call = init;
|
|
566
|
+
const callee = call.callee;
|
|
567
|
+
if ((callee.type === 'ArrowFunctionExpression' || callee.type === 'FunctionExpression')
|
|
568
|
+
&& callee.params.length === 0
|
|
569
|
+
&& call.arguments.length === 0) {
|
|
570
|
+
return returnedFunctionNode(callee.body);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
return undefined;
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Align a freshly-instantiated *display* type's kv-encoded constraint-constructor
|
|
577
|
+
* heads (the higher-kinded constraint variable, e.g. `Category c`) with those of
|
|
578
|
+
* the *body* instantiation, so inner bindings that reference the body's
|
|
579
|
+
* constraint variable render with the SAME display letter as the enclosing
|
|
580
|
+
* function's recorded (scope) type.
|
|
581
|
+
*
|
|
582
|
+
* An annotated function is instantiated twice: once for body inference
|
|
583
|
+
* (`expectedType`) and once for the recorded node/display type. The two
|
|
584
|
+
* instantiations allocate independent fresh ids, so a body binding such as
|
|
585
|
+
* `const idd = id(C)` (whose category head is the body's `$kv:c:377`) is
|
|
586
|
+
* pretty-printed with a *different* letter than the enclosing function's
|
|
587
|
+
* recorded head (`$kv:c:398`). Renaming the display type's kv head onto the
|
|
588
|
+
* body id reunites them.
|
|
589
|
+
*
|
|
590
|
+
* The kv-encoded constructor head (the constraint variable, e.g. `c` from the
|
|
591
|
+
* `TypeRep c` parameter) is aligned, AND every plain type-variable / row-variable
|
|
592
|
+
* is aligned onto the body id at the structurally-corresponding position. This
|
|
593
|
+
* makes the recorded scope type use the SAME variable identities as the body, so
|
|
594
|
+
* an inner binding whose type shares a variable with the enclosing function (a
|
|
595
|
+
* PARAMETRIC variable — e.g. `noVal = map(f)(u) :: f b` where `b` is `f`'s
|
|
596
|
+
* codomain) renders with the shared display letter.
|
|
597
|
+
*
|
|
598
|
+
* A callee's *generative* result variable (one introduced from no argument, e.g.
|
|
599
|
+
* the `a` of `id :: Category c => TypeRep c -> c a a`) must still render as its
|
|
600
|
+
* OWN distinct letter (`idd :: Category c => c b b`, not `c a a`). That is NOT
|
|
601
|
+
* handled here — after unification a generative variable may share the same id as
|
|
602
|
+
* an enclosing variable — but by per-binding generative freshening at the call
|
|
603
|
+
* site (see `freshenGenerativeResultVars`).
|
|
604
|
+
*
|
|
605
|
+
* Returns `from` with its kv-encoded TCon head names and plain var ids renamed to
|
|
606
|
+
* the structurally-corresponding ones in `bodyType`, or `null` when the two types
|
|
607
|
+
* are not structurally identical — i.e. body inference specialized the
|
|
608
|
+
* annotation — in which case the caller keeps the untouched display type.
|
|
609
|
+
*/
|
|
610
|
+
function alignDisplayVarIds(from, bodyType) {
|
|
611
|
+
const kvMap = new Map();
|
|
612
|
+
// Maps a display-instance var/row id onto the structurally-corresponding body
|
|
613
|
+
// node, so the recorded scope type adopts the body's variable identities.
|
|
614
|
+
const varMap = new Map();
|
|
615
|
+
const collect = (a, b) => {
|
|
616
|
+
// A plain annotation type-variable can be specialized to a higher-kinded
|
|
617
|
+
// (kv-encoded) variable in the body — e.g. `f` appears as `TypeRep f` (a
|
|
618
|
+
// bare TVar in the display instance) but is used as `f a` elsewhere, so body
|
|
619
|
+
// inference resolves it to `$kv:f:ID`. Align the display var onto the body's
|
|
620
|
+
// kv node so the recorded scope type adopts the body's higher-kinded identity
|
|
621
|
+
// (otherwise the tag mismatch below aborts the whole alignment and inner
|
|
622
|
+
// bindings that reference the kv head render with divergent letters).
|
|
623
|
+
if (a.tag === 'TVar' && b.tag === 'TCon' && (0, types_1.parseKvName)(b.name)) {
|
|
624
|
+
varMap.set(a.id, b);
|
|
625
|
+
return true;
|
|
626
|
+
}
|
|
627
|
+
if (a.tag !== b.tag)
|
|
628
|
+
return false;
|
|
629
|
+
switch (a.tag) {
|
|
630
|
+
case 'TVar': {
|
|
631
|
+
const bv = b;
|
|
632
|
+
if (a.id !== bv.id)
|
|
633
|
+
varMap.set(a.id, bv);
|
|
634
|
+
return true;
|
|
635
|
+
}
|
|
636
|
+
case 'TRow': {
|
|
637
|
+
const br = b;
|
|
638
|
+
if (a.id !== br.id)
|
|
639
|
+
varMap.set(a.id, br);
|
|
640
|
+
return true;
|
|
641
|
+
}
|
|
642
|
+
case 'TLabel': {
|
|
643
|
+
const bl = b;
|
|
644
|
+
if (a.kind !== bl.kind)
|
|
645
|
+
return false;
|
|
646
|
+
if (a.kind === 'lit')
|
|
647
|
+
return a.value === bl.value;
|
|
648
|
+
return true;
|
|
649
|
+
}
|
|
650
|
+
case 'TCon': {
|
|
651
|
+
const bc = b;
|
|
652
|
+
const ak = (0, types_1.parseKvName)(a.name);
|
|
653
|
+
const bk = (0, types_1.parseKvName)(bc.name);
|
|
654
|
+
if (ak && bk) {
|
|
655
|
+
if (ak.varName !== bk.varName)
|
|
656
|
+
return false;
|
|
657
|
+
if (a.name !== bc.name)
|
|
658
|
+
kvMap.set(a.name, bc.name);
|
|
659
|
+
}
|
|
660
|
+
else if (a.name !== bc.name) {
|
|
661
|
+
return false;
|
|
662
|
+
}
|
|
663
|
+
if (a.args.length !== bc.args.length)
|
|
664
|
+
return false;
|
|
665
|
+
return a.args.every((x, i) => collect(x, bc.args[i]));
|
|
666
|
+
}
|
|
667
|
+
case 'TFun': {
|
|
668
|
+
const bf = b;
|
|
669
|
+
return collect(a.param, bf.param) && collect(a.result, bf.result);
|
|
670
|
+
}
|
|
671
|
+
case 'TRecord': {
|
|
672
|
+
const br = b;
|
|
673
|
+
const aKeys = Object.keys(a.fields);
|
|
674
|
+
const bKeys = Object.keys(br.fields);
|
|
675
|
+
if (aKeys.length !== bKeys.length)
|
|
676
|
+
return false;
|
|
677
|
+
for (const k of aKeys) {
|
|
678
|
+
if (!(k in br.fields))
|
|
679
|
+
return false;
|
|
680
|
+
if (!collect(a.fields[k], br.fields[k]))
|
|
681
|
+
return false;
|
|
682
|
+
}
|
|
683
|
+
if (!!a.rest !== !!br.rest)
|
|
684
|
+
return false;
|
|
685
|
+
if (a.rest && br.rest && !collect(a.rest, br.rest))
|
|
686
|
+
return false;
|
|
687
|
+
if ((a.labelFields?.length ?? 0) !== (br.labelFields?.length ?? 0))
|
|
688
|
+
return false;
|
|
689
|
+
if (a.labelFields && br.labelFields) {
|
|
690
|
+
for (let i = 0; i < a.labelFields.length; i++) {
|
|
691
|
+
if (!collect(a.labelFields[i].label, br.labelFields[i].label))
|
|
692
|
+
return false;
|
|
693
|
+
if (!collect(a.labelFields[i].type, br.labelFields[i].type))
|
|
694
|
+
return false;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
return true;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
return false;
|
|
701
|
+
};
|
|
702
|
+
if (!collect(from, bodyType))
|
|
703
|
+
return null;
|
|
704
|
+
if (kvMap.size === 0 && varMap.size === 0)
|
|
705
|
+
return from;
|
|
706
|
+
const rename = (t) => {
|
|
707
|
+
switch (t.tag) {
|
|
708
|
+
case 'TVar': {
|
|
709
|
+
const mapped = varMap.get(t.id);
|
|
710
|
+
return mapped ? mapped : t;
|
|
711
|
+
}
|
|
712
|
+
case 'TRow': {
|
|
713
|
+
const mapped = varMap.get(t.id);
|
|
714
|
+
return mapped ? mapped : t;
|
|
715
|
+
}
|
|
716
|
+
case 'TCon': {
|
|
717
|
+
const name = kvMap.get(t.name) ?? t.name;
|
|
718
|
+
return { ...t, name, args: t.args.map(rename) };
|
|
719
|
+
}
|
|
720
|
+
case 'TFun':
|
|
721
|
+
return { ...t, param: rename(t.param), result: rename(t.result) };
|
|
722
|
+
case 'TRecord': {
|
|
723
|
+
const fields = {};
|
|
724
|
+
for (const k of Object.keys(t.fields))
|
|
725
|
+
fields[k] = rename(t.fields[k]);
|
|
726
|
+
const out = { ...t, fields };
|
|
727
|
+
if (t.rest)
|
|
728
|
+
out.rest = rename(t.rest);
|
|
729
|
+
if (t.labelFields) {
|
|
730
|
+
out.labelFields = t.labelFields.map(lf => ({
|
|
731
|
+
label: rename(lf.label),
|
|
732
|
+
type: rename(lf.type),
|
|
733
|
+
}));
|
|
734
|
+
}
|
|
735
|
+
return out;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
return t;
|
|
739
|
+
};
|
|
740
|
+
return rename(from);
|
|
741
|
+
}
|
|
742
|
+
/** Collect all type-, row- and label-variable ids reachable in `t`. */
|
|
743
|
+
function collectAllVarIds(t, out) {
|
|
744
|
+
switch (t.tag) {
|
|
745
|
+
case 'TVar':
|
|
746
|
+
out.add(t.id);
|
|
747
|
+
return;
|
|
748
|
+
case 'TRow':
|
|
749
|
+
out.add(t.id);
|
|
750
|
+
return;
|
|
751
|
+
case 'TLabel':
|
|
752
|
+
if (t.kind === 'var')
|
|
753
|
+
out.add(t.id);
|
|
754
|
+
return;
|
|
755
|
+
case 'TCon':
|
|
756
|
+
t.args.forEach(a => collectAllVarIds(a, out));
|
|
757
|
+
return;
|
|
758
|
+
case 'TFun':
|
|
759
|
+
collectAllVarIds(t.param, out);
|
|
760
|
+
collectAllVarIds(t.result, out);
|
|
761
|
+
return;
|
|
762
|
+
case 'TRecord':
|
|
763
|
+
for (const k in t.fields)
|
|
764
|
+
collectAllVarIds(t.fields[k], out);
|
|
765
|
+
if (t.rest)
|
|
766
|
+
collectAllVarIds(t.rest, out);
|
|
767
|
+
if (t.labelFields)
|
|
768
|
+
for (const lf of t.labelFields) {
|
|
769
|
+
collectAllVarIds(lf.label, out);
|
|
770
|
+
collectAllVarIds(lf.type, out);
|
|
771
|
+
}
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
/**
|
|
776
|
+
* Per-binding *generative* result-variable freshening for the DISPLAY type of a
|
|
777
|
+
* binding whose initializer is a (possibly curried) call `x = f(a)(b)…`.
|
|
778
|
+
*
|
|
779
|
+
* A callee's type variable is PARAMETRIC when it occurs in one of the callee's
|
|
780
|
+
* parameters (it flows in from an argument — e.g. `b` in
|
|
781
|
+
* `map :: Functor f => (a -> b) -> f a -> f b`, which is `f`'s codomain), and
|
|
782
|
+
* GENERATIVE when it occurs ONLY in the callee's result (it is introduced from
|
|
783
|
+
* no argument — e.g. `a` in `id :: Category c => TypeRep c -> c a a`).
|
|
784
|
+
*
|
|
785
|
+
* Parametric variables legitimately unify with — and should render with the same
|
|
786
|
+
* display letter as — the enclosing scope (handled by `alignDisplayVarIds`).
|
|
787
|
+
* Generative variables must render as their OWN fresh letters even though
|
|
788
|
+
* unification may have collapsed them onto an enclosing variable's id (e.g.
|
|
789
|
+
* `id`'s `a` unifies onto the law's `a` via the kv-arity TypeRep rule, yet
|
|
790
|
+
* `idd = id(C)` must still hover as `Category c => c b b`, not `c a a`).
|
|
791
|
+
*
|
|
792
|
+
* We determine generativity from the callee's pristine SCHEME (before body
|
|
793
|
+
* unification, where parameters and result are still cleanly separable), then
|
|
794
|
+
* structurally map the generative scheme variables onto the binding's resolved
|
|
795
|
+
* type and replace those positions with fresh display variables. Returns the
|
|
796
|
+
* (possibly rewritten) display type; on any structural mismatch it returns
|
|
797
|
+
* `resolved` unchanged.
|
|
798
|
+
*/
|
|
799
|
+
function freshenGenerativeResultVars(engine, init, resolved, env) {
|
|
800
|
+
if (!init || init.type !== 'CallExpression')
|
|
801
|
+
return resolved;
|
|
802
|
+
// Walk the (curried) call chain to the base callee, counting total arguments.
|
|
803
|
+
let numArgs = 0;
|
|
804
|
+
let cur = init;
|
|
805
|
+
while (cur.type === 'CallExpression') {
|
|
806
|
+
numArgs += cur.arguments.length;
|
|
807
|
+
cur = cur.callee;
|
|
808
|
+
}
|
|
809
|
+
if (cur.type !== 'Identifier')
|
|
810
|
+
return resolved;
|
|
811
|
+
const calleeName = cur.name;
|
|
812
|
+
const scheme = env.lookup(calleeName) ?? engine.annotationMap.get(calleeName)?.scheme;
|
|
813
|
+
if (!scheme)
|
|
814
|
+
return resolved;
|
|
815
|
+
// Candidate overload branches: a Union of TFun branches, else the type itself.
|
|
816
|
+
const branches = scheme.type.tag === 'TCon' && scheme.type.name === types_1.T_UNION
|
|
817
|
+
? scheme.type.args.filter(a => a.tag === 'TFun')
|
|
818
|
+
: [scheme.type];
|
|
819
|
+
for (const branch of branches) {
|
|
820
|
+
const { params, result } = (0, types_1.flattenCurriedType)(branch);
|
|
821
|
+
if (numArgs > params.length)
|
|
822
|
+
continue;
|
|
823
|
+
// Generative scheme vars: in the final result but in NO parameter.
|
|
824
|
+
const paramVars = new Set();
|
|
825
|
+
params.forEach(p => collectAllVarIds(p, paramVars));
|
|
826
|
+
const resultVars = new Set();
|
|
827
|
+
collectAllVarIds(result, resultVars);
|
|
828
|
+
const generative = new Set([...resultVars].filter(v => !paramVars.has(v)));
|
|
829
|
+
if (generative.size === 0)
|
|
830
|
+
continue;
|
|
831
|
+
// The binding's type corresponds to the scheme tail after `numArgs` params.
|
|
832
|
+
let tail = branch;
|
|
833
|
+
for (let i = 0; i < numArgs; i++) {
|
|
834
|
+
if (tail.tag !== 'TFun') {
|
|
835
|
+
tail = branch;
|
|
836
|
+
break;
|
|
837
|
+
}
|
|
838
|
+
tail = tail.result;
|
|
839
|
+
}
|
|
840
|
+
// Structurally align the scheme tail with the resolved binding type; at each
|
|
841
|
+
// generative-variable position emit a fresh display variable (one per
|
|
842
|
+
// distinct scheme variable, so `c a a` stays `c b b`).
|
|
843
|
+
const freshFor = new Map();
|
|
844
|
+
let ok = true;
|
|
845
|
+
const build = (s, r) => {
|
|
846
|
+
if (!ok)
|
|
847
|
+
return r;
|
|
848
|
+
if (s.tag === 'TVar' && generative.has(s.id)) {
|
|
849
|
+
let f = freshFor.get(s.id);
|
|
850
|
+
if (!f) {
|
|
851
|
+
f = (0, types_1.tVar)();
|
|
852
|
+
freshFor.set(s.id, f);
|
|
853
|
+
}
|
|
854
|
+
return f;
|
|
855
|
+
}
|
|
856
|
+
if (s.tag === 'TVar' || s.tag === 'TRow' || s.tag === 'TLabel')
|
|
857
|
+
return r;
|
|
858
|
+
if (s.tag !== r.tag) {
|
|
859
|
+
ok = false;
|
|
860
|
+
return r;
|
|
861
|
+
}
|
|
862
|
+
switch (s.tag) {
|
|
863
|
+
case 'TCon': {
|
|
864
|
+
const rc = r;
|
|
865
|
+
const sk = (0, types_1.parseKvName)(s.name);
|
|
866
|
+
const rk = (0, types_1.parseKvName)(rc.name);
|
|
867
|
+
const headOk = (sk && rk) ? sk.varName === rk.varName : s.name === rc.name;
|
|
868
|
+
if (!headOk || s.args.length !== rc.args.length) {
|
|
869
|
+
ok = false;
|
|
870
|
+
return r;
|
|
871
|
+
}
|
|
872
|
+
return { ...rc, args: s.args.map((a, i) => build(a, rc.args[i])) };
|
|
873
|
+
}
|
|
874
|
+
case 'TFun': {
|
|
875
|
+
const rf = r;
|
|
876
|
+
return { ...rf, param: build(s.param, rf.param), result: build(s.result, rf.result) };
|
|
877
|
+
}
|
|
878
|
+
case 'TRecord': {
|
|
879
|
+
const rr = r;
|
|
880
|
+
const sKeys = Object.keys(s.fields);
|
|
881
|
+
if (sKeys.length !== Object.keys(rr.fields).length) {
|
|
882
|
+
ok = false;
|
|
883
|
+
return r;
|
|
884
|
+
}
|
|
885
|
+
const fields = {};
|
|
886
|
+
for (const k of sKeys) {
|
|
887
|
+
if (!(k in rr.fields)) {
|
|
888
|
+
ok = false;
|
|
889
|
+
return r;
|
|
890
|
+
}
|
|
891
|
+
fields[k] = build(s.fields[k], rr.fields[k]);
|
|
892
|
+
}
|
|
893
|
+
return { ...rr, fields };
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
return r;
|
|
897
|
+
};
|
|
898
|
+
const built = build(tail, resolved);
|
|
899
|
+
if (ok && freshFor.size > 0)
|
|
900
|
+
return built;
|
|
901
|
+
}
|
|
902
|
+
return resolved;
|
|
903
|
+
}
|
|
904
|
+
/**
|
|
905
|
+
* Infer type of a named variable binding (e.g. `const x = expr`).
|
|
906
|
+
*
|
|
907
|
+
* Handles annotation lookup, self-recursion env extension, annotation
|
|
908
|
+
* validation (wildcard return, rigid check, concrete unify), scheme
|
|
909
|
+
* generalization, and isCurriedResult / conditionalReturn
|
|
910
|
+
* flag propagation.
|
|
911
|
+
*
|
|
912
|
+
* Called from `inferVariableDeclaration` for every declarator of the form
|
|
913
|
+
* `const/let/var name = init`
|
|
914
|
+
* where `name` is a plain identifier (not a destructuring pattern).
|
|
915
|
+
*/
|
|
916
|
+
function inferNamedBinding(engine, name, decl, env, nodeKind, parentStart) {
|
|
917
|
+
// Check for HM annotation on this variable.
|
|
918
|
+
// Verify the annotation belongs to this specific declaration by checking
|
|
919
|
+
// that nodeStart falls within the declaration's range. This prevents
|
|
920
|
+
// annotations for same-named variables in different scopes from leaking.
|
|
921
|
+
const rangeStart = parentStart ?? decl.start;
|
|
922
|
+
// Track `const f = function* () {}` generators by name so call sites can
|
|
923
|
+
// wrap their result in `Generator <element>`.
|
|
924
|
+
if (decl.init?.type === 'FunctionExpression'
|
|
925
|
+
&& decl.init.generator) {
|
|
926
|
+
engine.generatorFunctionNames.add(name);
|
|
927
|
+
}
|
|
928
|
+
let annotation = engine.annotationMap.get(name);
|
|
929
|
+
// Drop non-local annotations: a sidecar / globals / `::types` entry for
|
|
930
|
+
// `name` must not type-check (and thus reject) a user's own `const name =
|
|
931
|
+
// ...` binding. A locally-declared value SHADOWS an ambient global of the
|
|
932
|
+
// same name (e.g. `const test = propOrElse(...)` next to a Jest `test ::
|
|
933
|
+
// (String, () -> ()) -> ()` global), so the global signature is irrelevant
|
|
934
|
+
// here. Mirrors the no-initializer branch above.
|
|
935
|
+
if (annotation && !(0, commentParser_1.isLocalAnnotation)(annotation))
|
|
936
|
+
annotation = undefined;
|
|
937
|
+
if (annotation && annotation.nodeStart !== undefined
|
|
938
|
+
&& (annotation.nodeStart < rangeStart || annotation.nodeStart > decl.end)) {
|
|
939
|
+
// The name's map entry belongs to another declaration (a same-named
|
|
940
|
+
// helper in another scope); look for this declaration's own annotation.
|
|
941
|
+
// Its key is the annotated node, which can be the declaration, the
|
|
942
|
+
// declarator or (for a nested `const`) the initializer: take the entry
|
|
943
|
+
// for `name` inside this declaration's range.
|
|
944
|
+
let own = engine.annotationsByDeclaration.get(rangeStart)
|
|
945
|
+
?? engine.annotationsByDeclaration.get(decl.start);
|
|
946
|
+
if (own?.name !== name) {
|
|
947
|
+
own = undefined;
|
|
948
|
+
for (const [at, ann] of engine.annotationsByDeclaration) {
|
|
949
|
+
if (at >= rangeStart && at <= decl.end && ann.name === name) {
|
|
950
|
+
own = ann;
|
|
951
|
+
break;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
annotation = own?.name === name ? own : undefined;
|
|
956
|
+
}
|
|
957
|
+
// For annotated declarations, pre-extend env to enable self-recursion
|
|
958
|
+
let inferEnv = env;
|
|
959
|
+
let expectedType;
|
|
960
|
+
let selfRecTv;
|
|
961
|
+
if (annotation?.scheme) {
|
|
962
|
+
inferEnv = inferEnv.extend(name, annotation.scheme);
|
|
963
|
+
// Instantiate annotation early so parameter types are known during body inference
|
|
964
|
+
// Use constraint-aware instantiation to track kv constraints.
|
|
965
|
+
// `asGiven` marks these pending constraints as the binding's DECLARED
|
|
966
|
+
// (given) constraints so validateMissingConstraints can check that callee-
|
|
967
|
+
// required (wanted) constraints on the same type vars are entailed by them.
|
|
968
|
+
expectedType = engine.instantiateWithConstraints(annotation.scheme, decl, annotation, false, undefined, true);
|
|
969
|
+
// For polymorphic annotations WITHOUT constraints (e.g. `RTask String a b`),
|
|
970
|
+
// replace expectedType with one using wildcards (*) for free vars.
|
|
971
|
+
// This way concrete parts are enforced while free vars allow any type.
|
|
972
|
+
// Constrained schemes (e.g. `Functor f => ...`) need the real fresh
|
|
973
|
+
// vars for kv constraint tracking, so they keep the normal flow.
|
|
974
|
+
//
|
|
975
|
+
// However, for non-function value declarations (e.g. `arr :: [Either2 String a]`),
|
|
976
|
+
// keep real TVars so that free variables bind once and are shared across
|
|
977
|
+
// all elements. This way `a` means "one specific type" (not `Any`).
|
|
978
|
+
const hasConstraints = annotation.scheme.constraints && annotation.scheme.constraints.length > 0;
|
|
979
|
+
const isFunction = decl.init &&
|
|
980
|
+
(decl.init.type === 'ArrowFunctionExpression' || decl.init.type === 'FunctionExpression');
|
|
981
|
+
// Function-valued bindings keep the real fresh vars (like `function`
|
|
982
|
+
// declarations): wildcards here would let the body return the wrong
|
|
983
|
+
// variable (`(a, b) -> b` with body `(x, y) => x`) unnoticed. The
|
|
984
|
+
// rigid check in validateAnnotatedBindingType enforces the annotation.
|
|
985
|
+
if (annotation.scheme.vars.length > 0 && !hasConstraints && isFunction && (0, annotation_rigid_1.usesLenientArrowCheck)(annotation.scheme)) {
|
|
986
|
+
expectedType = (0, env_1.instantiateWithAny)(annotation.scheme);
|
|
987
|
+
}
|
|
988
|
+
// Suppress auto-union inside annotated declarations so that concrete
|
|
989
|
+
// constraints from the annotation produce real errors instead of
|
|
990
|
+
// being silently merged into union types.
|
|
991
|
+
engine.suppressAutoUnion = true;
|
|
992
|
+
// For constrained annotations (e.g. Monad m => ...), suppress
|
|
993
|
+
// "Infinite type" diagnostics from recursive self-references.
|
|
994
|
+
// The recursive call creates fresh constraint vars that the occurs
|
|
995
|
+
// check rejects, but this is safe — the annotation IS the type.
|
|
996
|
+
if (hasConstraints) {
|
|
997
|
+
engine.suppressInfiniteType = true;
|
|
998
|
+
engine.infiniteTypeSuppressedDuringAnnotation = false;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
else if (nodeKind === 'const' &&
|
|
1002
|
+
decl.init &&
|
|
1003
|
+
(decl.init.type === 'ArrowFunctionExpression' || decl.init.type === 'FunctionExpression')) {
|
|
1004
|
+
// Non-annotated const function: pre-extend env with a fresh type
|
|
1005
|
+
// variable to allow self-recursion (like `let rec` in ML).
|
|
1006
|
+
selfRecTv = (0, types_1.tVar)();
|
|
1007
|
+
inferEnv = inferEnv.extend(name, (0, types_1.mono)(selfRecTv));
|
|
1008
|
+
}
|
|
1009
|
+
let initType;
|
|
1010
|
+
// For annotated function bindings (`const fn = x => ...`), anchor any
|
|
1011
|
+
// body-level return-type diagnostics on the variable name rather than
|
|
1012
|
+
// on inner expressions or the entire block body.
|
|
1013
|
+
const isFunctionInit = decl.init &&
|
|
1014
|
+
(decl.init.type === 'ArrowFunctionExpression' || decl.init.type === 'FunctionExpression');
|
|
1015
|
+
const prevAnnotationMethodNode = engine.annotationMethodNode;
|
|
1016
|
+
if (annotation?.scheme && isFunctionInit) {
|
|
1017
|
+
engine.annotationMethodNode = decl;
|
|
1018
|
+
}
|
|
1019
|
+
// ---- Trial inference for closed-record annotations -----------------
|
|
1020
|
+
// When the annotation expects a *closed* record, the real pass below
|
|
1021
|
+
// would feed that record as the expected type into call inference,
|
|
1022
|
+
// and any open-record callee result would silently absorb annotation-
|
|
1023
|
+
// only fields into its row variable. Detect missing fields by running
|
|
1024
|
+
// a one-shot trial inference WITHOUT expected type, capturing the
|
|
1025
|
+
// value's natural fields, then rolling back substitution + diagnostics.
|
|
1026
|
+
let naturalRecordFields = null;
|
|
1027
|
+
if (annotation?.scheme && expectedType && decl.init && !isFunctionInit) {
|
|
1028
|
+
const annReturn = (0, types_1.getReturnType)(expectedType);
|
|
1029
|
+
if (annReturn.tag === 'TRecord' && !annReturn.rest) {
|
|
1030
|
+
(0, helpers_1.speculate)(engine, () => {
|
|
1031
|
+
const trial = engine.inferExpressionWithExpected(decl.init, inferEnv, undefined);
|
|
1032
|
+
const resolved = engine.subst.apply(trial);
|
|
1033
|
+
if (resolved.tag === 'TRecord') {
|
|
1034
|
+
naturalRecordFields = new Set(Object.keys(resolved.fields));
|
|
1035
|
+
}
|
|
1036
|
+
});
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
try {
|
|
1040
|
+
const prevBindingName = engine.currentBindingName;
|
|
1041
|
+
engine.currentBindingName = name;
|
|
1042
|
+
const occursCheckBefore = engine.occursCheckCount;
|
|
1043
|
+
// Check the body of an annotated polymorphic function against RIGID
|
|
1044
|
+
// skolems, exactly like a `function` declaration (whose annotation sits on
|
|
1045
|
+
// its own node start): distinct annotation vars can then never be unified
|
|
1046
|
+
// by the body (`flag ? x : y` for `(Boolean, a, b) -> a | b` stays a
|
|
1047
|
+
// union instead of pinning `a := b`). Constrained schemes keep their
|
|
1048
|
+
// constraint-aware instantiation; overloads/variadics stay lenient.
|
|
1049
|
+
const skolemInit = !!(annotation?.scheme && isFunctionInit
|
|
1050
|
+
&& annotation.scheme.vars.length > 0
|
|
1051
|
+
&& !(annotation.scheme.constraints && annotation.scheme.constraints.length > 0)
|
|
1052
|
+
&& !annotation.receiver
|
|
1053
|
+
&& !(0, annotation_rigid_1.usesLenientArrowCheck)(annotation.scheme)
|
|
1054
|
+
&& !(0, annotations_1.hasUnknownTConDiagForScheme)(engine.diagnostics, annotation.scheme)
|
|
1055
|
+
&& !engine.annotationByOffset.has(decl.init.start));
|
|
1056
|
+
const prevCheckedByBinding = engine.annotationCheckedByBinding;
|
|
1057
|
+
if (skolemInit) {
|
|
1058
|
+
engine.annotationByOffset.set(decl.init.start, annotation);
|
|
1059
|
+
engine.annotationCheckedByBinding = decl.init;
|
|
1060
|
+
}
|
|
1061
|
+
try {
|
|
1062
|
+
initType = engine.inferExpressionWithExpected(decl.init, inferEnv, expectedType);
|
|
1063
|
+
}
|
|
1064
|
+
finally {
|
|
1065
|
+
if (skolemInit) {
|
|
1066
|
+
engine.annotationByOffset.delete(decl.init.start);
|
|
1067
|
+
engine.annotationCheckedByBinding = prevCheckedByBinding;
|
|
1068
|
+
}
|
|
1069
|
+
engine.currentBindingName = prevBindingName;
|
|
1070
|
+
}
|
|
1071
|
+
// A binding whose body produced an infinite type (occurs check) cannot be
|
|
1072
|
+
// faithfully reconciled against its annotation — the inferred body type is
|
|
1073
|
+
// unrepresentable. The signature is authoritative, so record that the body
|
|
1074
|
+
// was infinite to suppress the downstream annotation-vs-body mismatch.
|
|
1075
|
+
const bodyHadOccursCheck = engine.occursCheckCount > occursCheckBefore;
|
|
1076
|
+
// Unify the self-recursion type variable with the inferred type.
|
|
1077
|
+
// This may fail with an "Infinite type" error for complex recursive
|
|
1078
|
+
// patterns (e.g. the curry helper pattern). In that case, silently
|
|
1079
|
+
// skip — the recursive reference will remain polymorphic via the
|
|
1080
|
+
// fresh TVar, which is acceptable for runtime-focused helper functions.
|
|
1081
|
+
if (selfRecTv) {
|
|
1082
|
+
try {
|
|
1083
|
+
const recSubst = (0, unify_1.unify)(selfRecTv, initType);
|
|
1084
|
+
engine.subst = engine.subst.compose(recSubst);
|
|
1085
|
+
}
|
|
1086
|
+
catch (e) {
|
|
1087
|
+
// "Infinite type" failures here are expected (curry helper pattern,
|
|
1088
|
+
// mutually recursive shapes); log anything else for diagnosis.
|
|
1089
|
+
if (!(e instanceof unify_1.UnificationError))
|
|
1090
|
+
(0, debugLog_1.debugLog)('statements.selfRecursionUnify', e);
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
if (annotation?.scheme && !bodyHadOccursCheck) {
|
|
1094
|
+
validateAnnotatedBindingType(engine, annotation.scheme, initType, expectedType, decl, naturalRecordFields);
|
|
1095
|
+
}
|
|
1096
|
+
// Validate the `::narrow` directive (the narrowed param index is resolved at
|
|
1097
|
+
// parse time; this only checks that any `[k]` label is satisfied).
|
|
1098
|
+
if (annotation?.scheme?.typePredicate && isFunctionInit && decl.init) {
|
|
1099
|
+
resolveNarrowPredicate(engine, annotation);
|
|
1100
|
+
}
|
|
1101
|
+
// Overload parameter display: when the binding's annotation is a Union of
|
|
1102
|
+
// function branches (overloads) with consistent arity, display each
|
|
1103
|
+
// parameter as the union of its type across all overloads (e.g.
|
|
1104
|
+
// `arr :: [a] | {a}`). Computed from a CLEAN instantiation of the scheme so
|
|
1105
|
+
// the row variables aren't polluted by wildcard instantiation or by body
|
|
1106
|
+
// unification, then recorded as a display-only override on the parameters.
|
|
1107
|
+
//
|
|
1108
|
+
// Curried lambdas (`apply1 => apply2 => …`) are walked level-by-level so
|
|
1109
|
+
// every parameter — including those of nested arrows — receives the union
|
|
1110
|
+
// of its position across all branches.
|
|
1111
|
+
//
|
|
1112
|
+
// The annotated function may be wrapped in an IIFE (`const equals =
|
|
1113
|
+
// (() => … return value1 => value2 => …)()`); in that case descend through
|
|
1114
|
+
// the thunk to the returned arrow chain so its parameters get the unions too.
|
|
1115
|
+
const overloadFnNode = annotation?.scheme && decl.init
|
|
1116
|
+
? effectiveAnnotatedFunctionNode(decl.init)
|
|
1117
|
+
: undefined;
|
|
1118
|
+
if (annotation?.scheme && overloadFnNode) {
|
|
1119
|
+
// Use a constraint-aware instantiation so kind-variable constraints
|
|
1120
|
+
// (e.g. `Apply f =>`) survive into the displayed parameter unions: the
|
|
1121
|
+
// `$kv:f:id` TCons are preserved and registered, letting hover render the
|
|
1122
|
+
// constraint prefix on parameters such as `apply1 :: Apply f => … | f (a -> b)`.
|
|
1123
|
+
const cleanAnn = annotation.scheme.constraints?.length
|
|
1124
|
+
? engine.instantiateWithConstraints(annotation.scheme, decl, annotation, true)
|
|
1125
|
+
: (0, env_1.instantiate)(annotation.scheme);
|
|
1126
|
+
if (cleanAnn.tag === 'TCon' && cleanAnn.name === types_1.T_UNION
|
|
1127
|
+
&& cleanAnn.args.length >= 2
|
|
1128
|
+
&& cleanAnn.args.every(b => b.tag === 'TFun')) {
|
|
1129
|
+
// Walk the function's arrow LEVELS. Each level contributes its own
|
|
1130
|
+
// parameter list; a single-arrow multi-parameter function packs them
|
|
1131
|
+
// into one tuple TFun param (`(arr, arr2) => …`), while a curried
|
|
1132
|
+
// function spreads them across nested single-param arrows
|
|
1133
|
+
// (`apply1 => apply2 => …`). Recording the level structure lets us
|
|
1134
|
+
// decompose each branch with the right per-level arity.
|
|
1135
|
+
const levels = [];
|
|
1136
|
+
let fn = overloadFnNode;
|
|
1137
|
+
while (fn && (fn.type === 'ArrowFunctionExpression' || fn.type === 'FunctionExpression')) {
|
|
1138
|
+
const fnParams = fn.params;
|
|
1139
|
+
levels.push(fnParams);
|
|
1140
|
+
// Only descend into a nested arrow when this level has exactly one
|
|
1141
|
+
// parameter and its body is itself a function expression — the
|
|
1142
|
+
// classic curried shape. Anything else terminates the chain.
|
|
1143
|
+
const body = fn.body;
|
|
1144
|
+
if (fnParams.length === 1 && body &&
|
|
1145
|
+
(body.type === 'ArrowFunctionExpression' || body.type === 'FunctionExpression')) {
|
|
1146
|
+
fn = body;
|
|
1147
|
+
}
|
|
1148
|
+
else {
|
|
1149
|
+
fn = undefined;
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
// Walk each branch's TFun chain in lockstep with the arrow levels.
|
|
1153
|
+
const branchCursors = cleanAnn.args.slice();
|
|
1154
|
+
for (const levelParams of levels) {
|
|
1155
|
+
const arity = levelParams.length;
|
|
1156
|
+
// Decompose this level from every branch, then advance each cursor.
|
|
1157
|
+
const perBranch = branchCursors.map(c => (c ? (0, types_1.decomposeFunParams)(c, arity) : null));
|
|
1158
|
+
for (let b = 0; b < branchCursors.length; b++) {
|
|
1159
|
+
branchCursors[b] = perBranch[b] ? perBranch[b].restType : null;
|
|
1160
|
+
}
|
|
1161
|
+
// Only record overrides when EVERY branch contributes the full set of
|
|
1162
|
+
// parameters at this level; otherwise arities diverge and a union
|
|
1163
|
+
// would be misleading.
|
|
1164
|
+
if (!perBranch.every(d => d != null && d.paramTypes.length === arity))
|
|
1165
|
+
continue;
|
|
1166
|
+
for (let i = 0; i < arity; i++) {
|
|
1167
|
+
const p = levelParams[i];
|
|
1168
|
+
if (!p || p.type !== 'Identifier')
|
|
1169
|
+
continue;
|
|
1170
|
+
// Collapse same-named vars across branches onto one id so the
|
|
1171
|
+
// pretty-printer keeps each branch's source name (`[a] | { a }`,
|
|
1172
|
+
// not `[a] | { b }`). Display-only.
|
|
1173
|
+
engine.recordNodeType(p, (0, types_1.canonicalizeDisplayVarsByName)((0, types_1.tUnion)(perBranch.map(d => d.paramTypes[i]))));
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
else if (cleanAnn.tag === 'TFun' && overloadFnNode !== decl.init) {
|
|
1178
|
+
// Single (non-overload) annotation wrapped in an IIFE — e.g. FP-library
|
|
1179
|
+
// `fl/lte.js`: `const lte = (() => { …; return v1 => v2 => …; })();`.
|
|
1180
|
+
// During thunk inference the annotation's expectedType is NOT threaded
|
|
1181
|
+
// through the zero-arg call, so the returned arrow's parameters were
|
|
1182
|
+
// bound to FRESH unconstrained vars. Re-record them from the
|
|
1183
|
+
// constraint-aware annotation instantiation so they behave exactly like
|
|
1184
|
+
// direct parameters: same constrained type variable, so hover shows the
|
|
1185
|
+
// constraint prefix (`value1 :: Ord a => a`) and tracks the annotation's
|
|
1186
|
+
// own variable name. Gated on `overloadFnNode !== decl.init` so direct
|
|
1187
|
+
// arrows (which already bind their params from expectedType) are left
|
|
1188
|
+
// untouched.
|
|
1189
|
+
const levels = [];
|
|
1190
|
+
let fn = overloadFnNode;
|
|
1191
|
+
while (fn && (fn.type === 'ArrowFunctionExpression' || fn.type === 'FunctionExpression')) {
|
|
1192
|
+
const fnParams = fn.params;
|
|
1193
|
+
levels.push(fnParams);
|
|
1194
|
+
const body = fn.body;
|
|
1195
|
+
if (fnParams.length === 1 && body &&
|
|
1196
|
+
(body.type === 'ArrowFunctionExpression' || body.type === 'FunctionExpression')) {
|
|
1197
|
+
fn = body;
|
|
1198
|
+
}
|
|
1199
|
+
else {
|
|
1200
|
+
fn = undefined;
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
let cursor = cleanAnn;
|
|
1204
|
+
for (const levelParams of levels) {
|
|
1205
|
+
const arity = levelParams.length;
|
|
1206
|
+
const d = cursor ? (0, types_1.decomposeFunParams)(cursor, arity) : null;
|
|
1207
|
+
cursor = d ? d.restType : null;
|
|
1208
|
+
if (!d || d.paramTypes.length !== arity)
|
|
1209
|
+
break;
|
|
1210
|
+
for (let i = 0; i < arity; i++) {
|
|
1211
|
+
const p = levelParams[i];
|
|
1212
|
+
if (!p || p.type !== 'Identifier')
|
|
1213
|
+
continue;
|
|
1214
|
+
engine.recordNodeType(p, d.paramTypes[i]);
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
finally {
|
|
1221
|
+
// Restore suppression flags after annotated inference + validation.
|
|
1222
|
+
engine.suppressAutoUnion = false;
|
|
1223
|
+
engine.suppressInfiniteType = false;
|
|
1224
|
+
engine.infiniteTypeSuppressedDuringAnnotation = false;
|
|
1225
|
+
engine.annotationMethodNode = prevAnnotationMethodNode;
|
|
1226
|
+
}
|
|
1227
|
+
// Generalize for `const`, monomorphic for `let`/`var`.
|
|
1228
|
+
// Exception: don't generalize a bare TVar that carries kvConstraint
|
|
1229
|
+
// entries — generalization would quantify the TVar and instantiation
|
|
1230
|
+
// would create a fresh id, losing the constraint mapping.
|
|
1231
|
+
// Before generalizing, retry property accesses that were parked on a
|
|
1232
|
+
// then-unresolved TVar receiver — the initializer is now fully inferred,
|
|
1233
|
+
// so a receiver pinned by a later argument (curried calls) resolves here
|
|
1234
|
+
// instead of leaving a spuriously quantified result var (`[b]` → `[Number]`).
|
|
1235
|
+
(0, expr_member_1.flushDeferredMemberAccesses)(engine);
|
|
1236
|
+
let resolved = engine.subst.apply(initType);
|
|
1237
|
+
// Null-initialised mutable binding: `let x = null; x = value;` is a
|
|
1238
|
+
// standard JS initialisation idiom (e.g. an FP library's chainRec sync/async flag
|
|
1239
|
+
// `let isSync = null; isSync = true;`). Widen the binding to `Null | a`
|
|
1240
|
+
// so the first non-null assignment pins `a` — later conflicting
|
|
1241
|
+
// assignments are still rejected, and `x === null` narrowing keeps
|
|
1242
|
+
// working. Only for UNANNOTATED `let`/`var` with a literal `null` init.
|
|
1243
|
+
if (!annotation?.scheme && nodeKind !== 'const'
|
|
1244
|
+
&& decl.init?.type === 'Literal' && decl.init.value === null
|
|
1245
|
+
&& decl.init.raw === 'null'
|
|
1246
|
+
&& resolved.tag === 'TCon' && resolved.name === 'Null' && resolved.args.length === 0) {
|
|
1247
|
+
resolved = (0, types_1.tUnion)([resolved, (0, types_1.tVar)()]);
|
|
1248
|
+
}
|
|
1249
|
+
const useAnnotationType = !!annotation?.scheme;
|
|
1250
|
+
let displayType = useAnnotationType
|
|
1251
|
+
? (annotation.scheme.constraints?.length
|
|
1252
|
+
? engine.instantiateWithConstraints(annotation.scheme, decl, annotation, true)
|
|
1253
|
+
: (0, env_1.instantiate)(annotation.scheme))
|
|
1254
|
+
: resolved;
|
|
1255
|
+
// Option 3: reunite the display type's kv-encoded constraint head with the
|
|
1256
|
+
// body instantiation (`expectedType`) so inner bindings that reference the
|
|
1257
|
+
// body's higher-kinded constraint variable (e.g. `const idd = id(C)` inside a
|
|
1258
|
+
// `Category c => …` law) render its head with the SAME display letter as the
|
|
1259
|
+
// enclosing function's recorded scope type. Only the constraint constructor
|
|
1260
|
+
// is aligned — plain object type-variables stay distinct so a callee's fresh
|
|
1261
|
+
// result var (id's `a`) does not collapse onto the law's `a`. Only for
|
|
1262
|
+
// constrained function annotations, and only when the body did not specialize
|
|
1263
|
+
// the annotation (structural match).
|
|
1264
|
+
if (useAnnotationType && expectedType && annotation.scheme.constraints?.length) {
|
|
1265
|
+
const aligned = alignDisplayVarIds(displayType, engine.subst.apply(expectedType));
|
|
1266
|
+
if (aligned)
|
|
1267
|
+
displayType = aligned;
|
|
1268
|
+
}
|
|
1269
|
+
// For a non-annotated binding whose initializer is a call, render a callee's
|
|
1270
|
+
// GENERATIVE result variables (introduced from no argument) with fresh display
|
|
1271
|
+
// letters, so e.g. `idd = id(C)` hovers as `Category c => c b b` even though
|
|
1272
|
+
// unification collapsed id's `a` onto the enclosing law's `a`. Parametric
|
|
1273
|
+
// variables are left shared (see alignDisplayVarIds).
|
|
1274
|
+
if (!useAnnotationType && decl.init) {
|
|
1275
|
+
displayType = freshenGenerativeResultVars(engine, decl.init, displayType, env);
|
|
1276
|
+
}
|
|
1277
|
+
const hasKvConstraints = resolved.tag === 'TVar' &&
|
|
1278
|
+
(engine.kvConstraints.has(resolved.id) || engine.kvConstructorConstraints.has(resolved.id));
|
|
1279
|
+
let scheme = annotation?.scheme
|
|
1280
|
+
? annotation.scheme // use the annotation scheme (preserves quantification)
|
|
1281
|
+
: nodeKind === 'const'
|
|
1282
|
+
? hasKvConstraints
|
|
1283
|
+
? (0, types_1.mono)(resolved)
|
|
1284
|
+
: (0, env_1.generalize)(env, resolved, engine.subst)
|
|
1285
|
+
: (0, types_1.mono)(resolved);
|
|
1286
|
+
// NOTE: for `let`/`var` we deliberately store `resolved` (the same
|
|
1287
|
+
// instance as `displayType`) rather than the pre-subst `initType`.
|
|
1288
|
+
// This way later record-extension mutations (in `inferAssignmentExpression`,
|
|
1289
|
+
// e.g. `builtIn.Array = …` after `let builtIn = {}`) that mutate
|
|
1290
|
+
// `sch.type.fields` are visible to hover lookups that resolve through
|
|
1291
|
+
// the recorded `displayType` of the declaration.
|
|
1292
|
+
// Propagate isCurriedResult from curry wrapper calls — only when the
|
|
1293
|
+
// initializer IS that call (`const f = curry (…)`, `const g = f (a)`). For
|
|
1294
|
+
// a function initializer the flag was left behind by a call inside its
|
|
1295
|
+
// body (FP-library validateSpec: `(k, rules, obj, updating) => … objOf (k) …`),
|
|
1296
|
+
// and marking the 4-parameter function itself as curried produced a false
|
|
1297
|
+
// HM5003 "Curried function called with 4 arguments" at every call site.
|
|
1298
|
+
if (engine.pendingIsCurriedResult) {
|
|
1299
|
+
engine.pendingIsCurriedResult = false;
|
|
1300
|
+
if (decl.init && decl.init.type === 'CallExpression') {
|
|
1301
|
+
scheme = { ...scheme, isCurriedResult: true };
|
|
1302
|
+
engine.curriedNodes.add(decl.start);
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
// Propagate conditional return info (literal guard narrowing)
|
|
1306
|
+
if (engine.pendingConditionalReturn) {
|
|
1307
|
+
const cr = engine.pendingConditionalReturn;
|
|
1308
|
+
engine.pendingConditionalReturn = null;
|
|
1309
|
+
// Only attach when the init is a direct function or curry wrapper call
|
|
1310
|
+
if (decl.init &&
|
|
1311
|
+
(decl.init.type === 'ArrowFunctionExpression' ||
|
|
1312
|
+
decl.init.type === 'FunctionExpression' ||
|
|
1313
|
+
(decl.init.type === 'CallExpression' &&
|
|
1314
|
+
decl.init.callee?.type === 'Identifier' &&
|
|
1315
|
+
engine.curryFunctionNames.has(decl.init.callee.name)))) {
|
|
1316
|
+
scheme = { ...scheme, conditionalReturn: cr };
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
// Propagate JS-body parameter defaults: when the binding's init is a
|
|
1320
|
+
// function expression with `(x = ...)` parameters, record the indices on
|
|
1321
|
+
// the scheme so call sites can treat trailing missing args as optional.
|
|
1322
|
+
// Also unwrap chained `name = obj.prop = (…) => …` assignment patterns
|
|
1323
|
+
// so member-access syntax shares the same metadata.
|
|
1324
|
+
{
|
|
1325
|
+
let initFn = decl.init;
|
|
1326
|
+
while (initFn && initFn.type === 'AssignmentExpression') {
|
|
1327
|
+
initFn = initFn.right;
|
|
1328
|
+
}
|
|
1329
|
+
if (initFn &&
|
|
1330
|
+
(initFn.type === 'ArrowFunctionExpression' ||
|
|
1331
|
+
initFn.type === 'FunctionExpression')) {
|
|
1332
|
+
const slots = collectOptionalParamSlots(initFn.params);
|
|
1333
|
+
if (slots.length > 0)
|
|
1334
|
+
scheme = { ...scheme, optionalParamSlots: slots };
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
return { scheme, displayType };
|
|
1338
|
+
}
|
|
1339
|
+
function inferFunctionDeclaration(engine, node, env) {
|
|
1340
|
+
const name = node.id?.name;
|
|
1341
|
+
// Track generator functions by name so call sites can wrap the result in
|
|
1342
|
+
// `Generator <element>` (the function type itself carries the element type).
|
|
1343
|
+
if (name && node.generator) {
|
|
1344
|
+
engine.generatorFunctionNames.add(name);
|
|
1345
|
+
}
|
|
1346
|
+
// Provenance: a `function Foo(){ this.x = ... }` is a constructor; any
|
|
1347
|
+
// other function gets no entry (regular call expected).
|
|
1348
|
+
if (name && node.body?.type === 'BlockStatement' && (0, narrowing_1.blockHasThisAssignment)(node.body)
|
|
1349
|
+
&& !(0, narrowing_1.hasSelfNewGuard)(node.body, name)) {
|
|
1350
|
+
engine.constructorProvenance.set(name, (0, dataTypeRegistry_1.isVariant)(name) ? 'sumtype-variant' : 'function-this');
|
|
1351
|
+
}
|
|
1352
|
+
// Check for HM annotation and pass expected type for early param binding
|
|
1353
|
+
const annotation = engine.lookupAnnotation(name, node.start);
|
|
1354
|
+
let expectedType;
|
|
1355
|
+
let thisType;
|
|
1356
|
+
if (annotation?.scheme) {
|
|
1357
|
+
if (annotation.receiver && annotation.methodType) {
|
|
1358
|
+
// Method annotation: create coordinated instantiation so receiver and
|
|
1359
|
+
// method type share the same fresh type variables.
|
|
1360
|
+
({ thisType, expectedType } = engine.coordinateInstantiate(annotation));
|
|
1361
|
+
}
|
|
1362
|
+
else {
|
|
1363
|
+
expectedType = engine.instantiateWithConstraints(annotation.scheme, node, annotation);
|
|
1364
|
+
// Detect constructor function: non-method annotation whose body uses
|
|
1365
|
+
// `this.x = ...` assignments. Bind `this` to the annotation's return
|
|
1366
|
+
// type so that property assignments type-check, and
|
|
1367
|
+
// inferBlockReturnType can return it instead of Undefined.
|
|
1368
|
+
if (!annotation.receiver && name && node.body?.type === 'BlockStatement'
|
|
1369
|
+
&& (0, narrowing_1.blockHasThisAssignment)(node.body)) {
|
|
1370
|
+
const retType = (0, types_1.getReturnType)(expectedType);
|
|
1371
|
+
thisType = retType;
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
// If we have a receiver type from a method annotation, bind `this` in env
|
|
1376
|
+
let funcEnv = env;
|
|
1377
|
+
if (thisType) {
|
|
1378
|
+
funcEnv = env.extend('this', (0, types_1.mono)(thisType));
|
|
1379
|
+
}
|
|
1380
|
+
if (annotation?.scheme)
|
|
1381
|
+
engine.annotationMethodNode = node;
|
|
1382
|
+
const funcType = engine.inferFunctionExpression(node, funcEnv, expectedType);
|
|
1383
|
+
engine.annotationMethodNode = null;
|
|
1384
|
+
if (name) {
|
|
1385
|
+
if (annotation?.scheme) {
|
|
1386
|
+
// Skip rigid check and unification for factory functions that return
|
|
1387
|
+
// a sumtype TCon — the returned record literal IS the runtime
|
|
1388
|
+
// representation and the annotation is the source of truth.
|
|
1389
|
+
if ((0, annotations_1.hasUnknownTConDiagForScheme)(engine.diagnostics, annotation.scheme)) {
|
|
1390
|
+
// Annotation references unknown type constructors — skip all
|
|
1391
|
+
// mismatch checks; the "unknown type constructor" diagnostic is
|
|
1392
|
+
// sufficient.
|
|
1393
|
+
}
|
|
1394
|
+
else if (!shouldSuppressSumTypeCheck(annotation.scheme, funcType, engine.typeAliases)) {
|
|
1395
|
+
const diagsBefore = engine.diagnostics.length;
|
|
1396
|
+
engine.checkRigid(funcType, annotation.scheme, node);
|
|
1397
|
+
// When the rigid check already produced a mismatch diagnostic the
|
|
1398
|
+
// follow-up unification would only restate the same conflict in a
|
|
1399
|
+
// less informative form ("Cannot unify '()' with 'RTask r e b'"),
|
|
1400
|
+
// so skip it. Still run unification when rigid was clean so the
|
|
1401
|
+
// engine's substitution stays in sync with the annotation.
|
|
1402
|
+
if (engine.diagnostics.length === diagsBefore) {
|
|
1403
|
+
// Reuse expectedType to preserve kv constraint id mapping
|
|
1404
|
+
const annotatedType = expectedType ?? (0, env_1.instantiate)(annotation.scheme);
|
|
1405
|
+
// A narrower union result passed the rigid check; bind it the same
|
|
1406
|
+
// way instead of restating a union mismatch.
|
|
1407
|
+
const widened = (0, unify_1.unifyWidening)(engine.subst.apply(funcType), engine.subst.apply(annotatedType));
|
|
1408
|
+
if (widened)
|
|
1409
|
+
engine.subst.mergeFrom(widened);
|
|
1410
|
+
else
|
|
1411
|
+
engine.unifyWithDiagnostic(funcType, annotatedType, node);
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
else {
|
|
1415
|
+
validateSumTypeFactoryFields(engine, annotation.scheme, funcType, expectedType, node);
|
|
1416
|
+
}
|
|
1417
|
+
// Check for missing record fields in the return type
|
|
1418
|
+
checkMissingRecordFields(engine, funcType, annotation.scheme, node);
|
|
1419
|
+
let annotatedScheme = annotation.scheme;
|
|
1420
|
+
const declSlots = collectOptionalParamSlots(node.params);
|
|
1421
|
+
if (declSlots.length > 0)
|
|
1422
|
+
annotatedScheme = { ...annotatedScheme, optionalParamSlots: declSlots };
|
|
1423
|
+
const newEnv = env.extend(name, annotatedScheme);
|
|
1424
|
+
const displayType = (0, env_1.instantiate)(annotatedScheme);
|
|
1425
|
+
if (node.id)
|
|
1426
|
+
engine.recordNodeType(node.id, displayType);
|
|
1427
|
+
return [newEnv, engine.subst.apply(funcType)];
|
|
1428
|
+
}
|
|
1429
|
+
const resolved = engine.subst.apply(funcType);
|
|
1430
|
+
let scheme = (0, env_1.generalize)(env, resolved);
|
|
1431
|
+
const declSlots = collectOptionalParamSlots(node.params);
|
|
1432
|
+
if (declSlots.length > 0)
|
|
1433
|
+
scheme = { ...scheme, optionalParamSlots: declSlots };
|
|
1434
|
+
const newEnv = env.extend(name, scheme);
|
|
1435
|
+
if (node.id)
|
|
1436
|
+
engine.recordNodeType(node.id, resolved);
|
|
1437
|
+
if (node.id && scheme.vars.length > 0) {
|
|
1438
|
+
engine.declaredSchemes.set(node.id.start, scheme);
|
|
1439
|
+
}
|
|
1440
|
+
return [newEnv, funcType];
|
|
1441
|
+
}
|
|
1442
|
+
return [env, funcType];
|
|
1443
|
+
}
|
|
1444
|
+
/** `Null`/`Undefined`, the members a lookup adds when it misses. */
|
|
1445
|
+
function isNullish(t) {
|
|
1446
|
+
return t.tag === 'TCon' && t.args.length === 0 && (t.name === 'Undefined' || t.name === 'Null');
|
|
1447
|
+
}
|
|
1448
|
+
/**
|
|
1449
|
+
* An annotation on a `const` may state that a lookup did not miss: the value
|
|
1450
|
+
* comes from a call, a member access or an `await` (`rates.get (code)`,
|
|
1451
|
+
* `orders.find (…)`, `invoice.paidAt`), its type is a union with `Undefined`
|
|
1452
|
+
* or `Null`, and the annotation is that union without them (`// rate ::
|
|
1453
|
+
* Number`). Unifies the rest with the annotation and returns true; returns
|
|
1454
|
+
* false (nothing bound) when the annotation says anything else.
|
|
1455
|
+
*/
|
|
1456
|
+
function assertsPresentLookup(engine, decl, inferred, annotated) {
|
|
1457
|
+
let init = decl.init;
|
|
1458
|
+
if (!init)
|
|
1459
|
+
return false;
|
|
1460
|
+
if (init.type === 'AwaitExpression')
|
|
1461
|
+
init = init.argument;
|
|
1462
|
+
if (init.type !== 'CallExpression' && init.type !== 'MemberExpression')
|
|
1463
|
+
return false;
|
|
1464
|
+
if (inferred.tag !== 'TCon' || inferred.name !== types_1.T_UNION)
|
|
1465
|
+
return false;
|
|
1466
|
+
const present = inferred.args.filter(m => !isNullish(m));
|
|
1467
|
+
if (present.length === inferred.args.length || present.length === 0)
|
|
1468
|
+
return false;
|
|
1469
|
+
if ((0, types_1.containsErrorType)(inferred) || (0, types_1.containsErrorType)(annotated))
|
|
1470
|
+
return false;
|
|
1471
|
+
const rest = present.length === 1 ? present[0] : (0, types_1.tUnion)(present);
|
|
1472
|
+
try {
|
|
1473
|
+
engine.subst.mergeFrom((0, unify_1.unify)(engine.subst.apply(rest), engine.subst.apply(annotated)));
|
|
1474
|
+
return true;
|
|
1475
|
+
}
|
|
1476
|
+
catch (e) {
|
|
1477
|
+
if (e instanceof unify_1.UnificationError)
|
|
1478
|
+
return false;
|
|
1479
|
+
throw e;
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
//# sourceMappingURL=stmt-bindings.js.map
|