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,1359 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ============================================================================
|
|
3
|
+
// Function-expression inference: inline-annotation validation, parameter
|
|
4
|
+
// binding, block return-type inference (extracted from expressions.ts)
|
|
5
|
+
//
|
|
6
|
+
// Plain language: when the checker meets a function being defined —
|
|
7
|
+
// `(a, b) => a + b` or `function f(x) { … }` — this file works out its type:
|
|
8
|
+
// give each parameter a placeholder (or the type from an annotation), walk
|
|
9
|
+
// the body to see how the parameters are used and what is returned, and
|
|
10
|
+
// assemble the resulting `param -> result` type.
|
|
11
|
+
// ============================================================================
|
|
12
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
13
|
+
if (k2 === undefined) k2 = k;
|
|
14
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
15
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
16
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
17
|
+
}
|
|
18
|
+
Object.defineProperty(o, k2, desc);
|
|
19
|
+
}) : (function(o, m, k, k2) {
|
|
20
|
+
if (k2 === undefined) k2 = k;
|
|
21
|
+
o[k2] = m[k];
|
|
22
|
+
}));
|
|
23
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
24
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
25
|
+
}) : function(o, v) {
|
|
26
|
+
o["default"] = v;
|
|
27
|
+
});
|
|
28
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
29
|
+
var ownKeys = function(o) {
|
|
30
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
31
|
+
var ar = [];
|
|
32
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
33
|
+
return ar;
|
|
34
|
+
};
|
|
35
|
+
return ownKeys(o);
|
|
36
|
+
};
|
|
37
|
+
return function (mod) {
|
|
38
|
+
if (mod && mod.__esModule) return mod;
|
|
39
|
+
var result = {};
|
|
40
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
41
|
+
__setModuleDefault(result, mod);
|
|
42
|
+
return result;
|
|
43
|
+
};
|
|
44
|
+
})();
|
|
45
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
46
|
+
exports.inferFunctionExpression = inferFunctionExpression;
|
|
47
|
+
exports.bindFunctionParams = bindFunctionParams;
|
|
48
|
+
exports.tryDetectConditionalReturn = tryDetectConditionalReturn;
|
|
49
|
+
exports.checkUnionVsExpected = checkUnionVsExpected;
|
|
50
|
+
exports.inferBlockReturnType = inferBlockReturnType;
|
|
51
|
+
exports.collectAllReturnTypes = collectAllReturnTypes;
|
|
52
|
+
const walk = __importStar(require("../walking"));
|
|
53
|
+
const types_1 = require("../hm/types");
|
|
54
|
+
const env_1 = require("../hm/env");
|
|
55
|
+
const statements_1 = require("./statements");
|
|
56
|
+
const unify_1 = require("../hm/unify");
|
|
57
|
+
const methodRegistry_1 = require("../registries/methodRegistry");
|
|
58
|
+
const dataTypeRegistry_1 = require("../registries/dataTypeRegistry");
|
|
59
|
+
const typeUtils_1 = require("../hm/typeUtils");
|
|
60
|
+
const narrowing_1 = require("./narrowing");
|
|
61
|
+
const annotations_1 = require("./annotations");
|
|
62
|
+
const expressions_1 = require("./expressions");
|
|
63
|
+
/**
|
|
64
|
+
* Validate a function expression's inferred type against its inline annotation.
|
|
65
|
+
* Detects sumtype factory functions (where the annotation is the source of truth)
|
|
66
|
+
* and runs rigid check + unification for normal annotated functions.
|
|
67
|
+
* Returns the (possibly updated) function type.
|
|
68
|
+
*/
|
|
69
|
+
function validateInlineAnnotation(engine, funcType, inlineAnnotation, inlineExpectedType, node) {
|
|
70
|
+
const annReturn = (0, types_1.getReturnType)(inlineAnnotation.scheme.type);
|
|
71
|
+
const inferredReturn = (0, types_1.getReturnType)(funcType);
|
|
72
|
+
let isSumTypeFactory = false;
|
|
73
|
+
if (annReturn.tag === 'TCon' && (0, dataTypeRegistry_1.isDataType)(annReturn.name)) {
|
|
74
|
+
if (inferredReturn.tag === 'TVar'
|
|
75
|
+
|| (inferredReturn.tag === 'TCon' && (0, dataTypeRegistry_1.isDataType)(inferredReturn.name))) {
|
|
76
|
+
isSumTypeFactory = true;
|
|
77
|
+
}
|
|
78
|
+
else if (inferredReturn.tag === 'TRecord') {
|
|
79
|
+
const required = (0, methodRegistry_1.getMethodNames)(annReturn.name);
|
|
80
|
+
isSumTypeFactory = required.length === 0
|
|
81
|
+
|| required.every(m => m in inferredReturn.fields);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (!isSumTypeFactory) {
|
|
85
|
+
const diagNode = inlineAnnotation.nameStart != null && inlineAnnotation.nameEnd != null
|
|
86
|
+
? { start: inlineAnnotation.nameStart, end: inlineAnnotation.nameEnd }
|
|
87
|
+
: node;
|
|
88
|
+
const diagsBefore = engine.diagnostics.length;
|
|
89
|
+
engine.checkRigid(funcType, inlineAnnotation.scheme, diagNode);
|
|
90
|
+
if (engine.diagnostics.length === diagsBefore) {
|
|
91
|
+
engine.unifyWithDiagnostic(funcType, inlineExpectedType, diagNode);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
if (isSumTypeFactory) {
|
|
95
|
+
// For sumtype factory functions, trust the annotation completely.
|
|
96
|
+
// Still validate the record fields' types against registered methods.
|
|
97
|
+
if (inferredReturn.tag === 'TRecord' && annReturn.tag === 'TCon') {
|
|
98
|
+
const methodNames = (0, methodRegistry_1.getMethodNames)(annReturn.name);
|
|
99
|
+
if (methodNames.length > 0) {
|
|
100
|
+
const expReturn = (0, types_1.getReturnType)(inlineExpectedType);
|
|
101
|
+
const typeArgs = (expReturn?.tag === 'TCon' ? expReturn.args : []);
|
|
102
|
+
const expectedFields = {};
|
|
103
|
+
for (const mn of methodNames) {
|
|
104
|
+
const entry = (0, methodRegistry_1.lookupMethod)(annReturn.name, mn);
|
|
105
|
+
if (entry)
|
|
106
|
+
expectedFields[mn] = (0, typeUtils_1.neutralizeUnions)(entry.factory(typeArgs));
|
|
107
|
+
}
|
|
108
|
+
engine.unifyWithDiagnostic(inferredReturn, (0, types_1.tRecord)(expectedFields), node);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return inlineExpectedType;
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
return engine.subst.apply(funcType);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Collect the identifier names bound by a list of binding patterns
|
|
119
|
+
* (function parameters or `var`/`let`/`const` declarator targets):
|
|
120
|
+
* plain identifiers, defaults (`x = …`), rest (`...xs`), and array/object
|
|
121
|
+
* destructuring.
|
|
122
|
+
*/
|
|
123
|
+
function collectPatternNames(nodes, out) {
|
|
124
|
+
for (const n of nodes) {
|
|
125
|
+
if (!n)
|
|
126
|
+
continue;
|
|
127
|
+
switch (n.type) {
|
|
128
|
+
case 'Identifier':
|
|
129
|
+
out.add(n.name);
|
|
130
|
+
break;
|
|
131
|
+
case 'AssignmentPattern':
|
|
132
|
+
collectPatternNames([n.left], out);
|
|
133
|
+
break;
|
|
134
|
+
case 'RestElement':
|
|
135
|
+
collectPatternNames([n.argument], out);
|
|
136
|
+
break;
|
|
137
|
+
case 'ArrayPattern':
|
|
138
|
+
collectPatternNames(n.elements, out);
|
|
139
|
+
break;
|
|
140
|
+
case 'ObjectPattern':
|
|
141
|
+
for (const p of n.properties) {
|
|
142
|
+
if (p.type === 'RestElement')
|
|
143
|
+
collectPatternNames([p.argument], out);
|
|
144
|
+
else
|
|
145
|
+
collectPatternNames([p.value], out);
|
|
146
|
+
}
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Recursively collect the names declared by `var` statements anywhere within a
|
|
153
|
+
* function body, WITHOUT descending into nested function scopes (which have
|
|
154
|
+
* their own `var` environment). JavaScript hoists `var` declarations to the
|
|
155
|
+
* top of the enclosing function, so a `var` declared in one block is visible
|
|
156
|
+
* in sibling blocks — e.g. two `for` loops sharing `var idx` (FP-library
|
|
157
|
+
* `object/sortBy.js`).
|
|
158
|
+
*/
|
|
159
|
+
function collectHoistedVarNames(node, out) {
|
|
160
|
+
if (!node || typeof node !== 'object' || typeof node.type !== 'string')
|
|
161
|
+
return;
|
|
162
|
+
if (node.type === 'FunctionDeclaration'
|
|
163
|
+
|| node.type === 'FunctionExpression'
|
|
164
|
+
|| node.type === 'ArrowFunctionExpression') {
|
|
165
|
+
return; // nested function: its `var`s belong to its own scope
|
|
166
|
+
}
|
|
167
|
+
if (node.type === 'VariableDeclaration'
|
|
168
|
+
&& node.kind === 'var') {
|
|
169
|
+
for (const d of node.declarations) {
|
|
170
|
+
collectPatternNames([d.id], out);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
for (const key of Object.keys(node)) {
|
|
174
|
+
if (key === 'type' || key === 'start' || key === 'end' || key === 'loc' || key === 'range')
|
|
175
|
+
continue;
|
|
176
|
+
const val = node[key];
|
|
177
|
+
if (Array.isArray(val)) {
|
|
178
|
+
for (const c of val)
|
|
179
|
+
collectHoistedVarNames(c, out);
|
|
180
|
+
}
|
|
181
|
+
else if (val && typeof val === 'object' && typeof val.type === 'string') {
|
|
182
|
+
collectHoistedVarNames(val, out);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
/** Origin descriptor (annotation name + comment range) for skolem
|
|
187
|
+
* registration — lets diagnostics point back at the declaring annotation
|
|
188
|
+
* when two same-letter skolems collide in one message. */
|
|
189
|
+
function annotationOrigin(annotation, node) {
|
|
190
|
+
return {
|
|
191
|
+
name: annotation.name,
|
|
192
|
+
start: annotation.commentStart ?? node.start,
|
|
193
|
+
end: annotation.commentEnd ?? node.end,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* When a method annotation's receiver (`Type#m :: Type e a ~> …`) names the
|
|
198
|
+
* SAME constructor (same arity) as the return type of an enclosing annotated
|
|
199
|
+
* function, the record under construction is the receiver itself. Returns a
|
|
200
|
+
* map from the receiver's type-variable ids to the enclosing return type's
|
|
201
|
+
* corresponding arguments, so `skolemSubstForScheme` pins them instead of
|
|
202
|
+
* minting fresh skolems.
|
|
203
|
+
*/
|
|
204
|
+
function enclosingReceiverBindings(engine, receiver) {
|
|
205
|
+
if (receiver.tag !== 'TCon')
|
|
206
|
+
return undefined;
|
|
207
|
+
for (let i = engine.enclosingAnnotatedReturns.length - 1; i >= 0; i--) {
|
|
208
|
+
const ret = engine.subst.apply(engine.enclosingAnnotatedReturns[i]);
|
|
209
|
+
if (ret.tag !== 'TCon' || ret.name !== receiver.name || ret.args.length !== receiver.args.length)
|
|
210
|
+
continue;
|
|
211
|
+
const bindings = new Map();
|
|
212
|
+
for (let j = 0; j < receiver.args.length; j++) {
|
|
213
|
+
const rv = receiver.args[j];
|
|
214
|
+
if (rv.tag === 'TVar')
|
|
215
|
+
bindings.set(rv.id, ret.args[j]);
|
|
216
|
+
}
|
|
217
|
+
if (bindings.size > 0)
|
|
218
|
+
return bindings;
|
|
219
|
+
}
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Lexically scoped type variables: a type variable in a NESTED annotation that
|
|
224
|
+
* also occurs in an enclosing (skolemized) annotation is the same variable —
|
|
225
|
+
* like a generic `T` inside an inner function in TypeScript. `engine.
|
|
226
|
+
* scopedTypeVars` maps those letters to the enclosing body's skolems; it is
|
|
227
|
+
* extended while a skolem-checked body is inferred and restored afterwards.
|
|
228
|
+
*/
|
|
229
|
+
/** `!x` or `!obj.prop` (any number of `!`, an odd count): a falsiness test. */
|
|
230
|
+
function isNegatedReference(test) {
|
|
231
|
+
let target = test;
|
|
232
|
+
let negations = 0;
|
|
233
|
+
while (target.type === 'UnaryExpression' && target.operator === '!') {
|
|
234
|
+
negations += 1;
|
|
235
|
+
target = target.argument;
|
|
236
|
+
}
|
|
237
|
+
if (negations % 2 === 0)
|
|
238
|
+
return false;
|
|
239
|
+
return target.type === 'Identifier'
|
|
240
|
+
|| (target.type === 'MemberExpression' && target.object.type === 'Identifier');
|
|
241
|
+
}
|
|
242
|
+
function inferFunctionExpression(engine, node, env, expectedType) {
|
|
243
|
+
const prevScoped = engine.scopedTypeVars;
|
|
244
|
+
const prevRigidRows = engine.rigidRowIds;
|
|
245
|
+
try {
|
|
246
|
+
return inferFunctionExpressionScoped(engine, node, env, expectedType);
|
|
247
|
+
}
|
|
248
|
+
finally {
|
|
249
|
+
engine.scopedTypeVars = prevScoped;
|
|
250
|
+
engine.rigidRowIds = prevRigidRows;
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/** Bind the annotation letters already in lexical scope to the enclosing
|
|
254
|
+
* skolems, then add this body's own skolems to the scope. Returns the
|
|
255
|
+
* mapping to apply to every type minted from the same annotation (the
|
|
256
|
+
* expected function type, and for a method also its `this` type). */
|
|
257
|
+
function scopeSkolems(engine, skolemToName) {
|
|
258
|
+
const outer = engine.scopedTypeVars;
|
|
259
|
+
const captured = new Map();
|
|
260
|
+
const next = new Map(outer);
|
|
261
|
+
for (const [sk, letter] of skolemToName) {
|
|
262
|
+
const outerSk = outer.get(letter);
|
|
263
|
+
if (outerSk)
|
|
264
|
+
captured.set(sk, outerSk);
|
|
265
|
+
else
|
|
266
|
+
next.set(letter, { tag: 'TCon', name: sk, args: [], skolemName: letter });
|
|
267
|
+
}
|
|
268
|
+
engine.scopedTypeVars = next;
|
|
269
|
+
if (captured.size === 0)
|
|
270
|
+
return t => t;
|
|
271
|
+
return t => (0, typeUtils_1.mapType)(t, n => (n.tag === 'TCon' && captured.has(n.name) ? captured.get(n.name) : undefined));
|
|
272
|
+
}
|
|
273
|
+
function inferFunctionExpressionScoped(engine, node, env, expectedType) {
|
|
274
|
+
let inlineAnnotation;
|
|
275
|
+
let inlineExpectedType;
|
|
276
|
+
let inlineMethodThisType;
|
|
277
|
+
// When the annotated body is checked against rigid skolem constants (so the
|
|
278
|
+
// body can never poison the annotation's parameter / `this` / return
|
|
279
|
+
// display), this holds the skolem→letter map for that signature. Its
|
|
280
|
+
// presence also marks that the annotation is authoritative for the returned
|
|
281
|
+
// function type (the body only *checks* against it).
|
|
282
|
+
let inlineSkolemNames;
|
|
283
|
+
// Inline HM annotation on anonymous function expressions:
|
|
284
|
+
// foo(
|
|
285
|
+
// // :: Number -> String
|
|
286
|
+
// x => x + "!"
|
|
287
|
+
// )
|
|
288
|
+
const annotation = engine.annotationByOffset.get(node.start);
|
|
289
|
+
if (annotation?.scheme && !annotation.receiver && !annotation.name?.includes('#')) {
|
|
290
|
+
inlineAnnotation = annotation;
|
|
291
|
+
const constrained = !!(annotation.scheme.constraints && annotation.scheme.constraints.length > 0);
|
|
292
|
+
// When the annotation references an unknown type constructor it already
|
|
293
|
+
// carries its own "unknown type constructor" diagnostic; rigid skolem
|
|
294
|
+
// checking of the body would only pile on spurious "Cannot unify" noise,
|
|
295
|
+
// so fall back to flexible instantiation (matching the existing
|
|
296
|
+
// suppression of mismatch checks for unknown-TCon schemes).
|
|
297
|
+
const useFlexible = constrained || (0, annotations_1.hasUnknownTConDiagForScheme)(engine.diagnostics, annotation.scheme);
|
|
298
|
+
if (useFlexible) {
|
|
299
|
+
// Constrained schemes (e.g. `Functor f =>`) keep the existing
|
|
300
|
+
// constraint-aware instantiation path; skolemizing them would defeat
|
|
301
|
+
// constraint resolution.
|
|
302
|
+
inlineExpectedType = engine.instantiateWithConstraints(annotation.scheme, node, annotation, false, undefined, true);
|
|
303
|
+
}
|
|
304
|
+
else {
|
|
305
|
+
const sk = (0, env_1.instantiateSkolem)(annotation.scheme);
|
|
306
|
+
engine.registerSkolemNames(sk.skolemToName, annotationOrigin(annotation, node));
|
|
307
|
+
inlineSkolemNames = sk.skolemToName;
|
|
308
|
+
inlineExpectedType = scopeSkolems(engine, sk.skolemToName)(sk.type);
|
|
309
|
+
}
|
|
310
|
+
expectedType = inlineExpectedType;
|
|
311
|
+
}
|
|
312
|
+
else if (annotation?.receiver && annotation?.methodType && annotation?.scheme && !expectedType) {
|
|
313
|
+
// Method annotation directly above a function expression (e.g. inside a
|
|
314
|
+
// factory function): // Either2#map :: Either2 e a ~> (a -> b) -> Either2 e b
|
|
315
|
+
// const map = fn => ...
|
|
316
|
+
// Share the receiver + method type variables (skolems when unconstrained)
|
|
317
|
+
// so the body can be checked without poisoning the displayed signature.
|
|
318
|
+
const constrained = !!(annotation.scheme.constraints && annotation.scheme.constraints.length > 0);
|
|
319
|
+
const useFlexible = constrained || (0, annotations_1.hasUnknownTConDiagForScheme)(engine.diagnostics, annotation.scheme);
|
|
320
|
+
if (useFlexible) {
|
|
321
|
+
const { thisType: methodThis, expectedType: methodExpected } = engine.coordinateInstantiate(annotation);
|
|
322
|
+
inlineMethodThisType = methodThis;
|
|
323
|
+
inlineExpectedType = methodExpected;
|
|
324
|
+
}
|
|
325
|
+
else {
|
|
326
|
+
// For a method annotation nested inside an annotated factory whose
|
|
327
|
+
// signature returns the SAME constructor (`// Either2#map :: Either2 e a ~> …`
|
|
328
|
+
// above `const map = fn => …` in a factory returning `Either2 e a`),
|
|
329
|
+
// the record under construction IS the receiver. Link the receiver's
|
|
330
|
+
// type variables to the enclosing return type's arguments so closure
|
|
331
|
+
// captures (`value :: e | a`) and the method's own signature agree,
|
|
332
|
+
// instead of minting unrelated same-letter rigid skolems that collide
|
|
333
|
+
// as "Cannot unify 'a' with 'a''".
|
|
334
|
+
const preBindings = enclosingReceiverBindings(engine, annotation.receiver);
|
|
335
|
+
const sk = engine.coordinateInstantiateSkolem(annotation, preBindings);
|
|
336
|
+
engine.registerSkolemNames(sk.skolemToName, annotationOrigin(annotation, node));
|
|
337
|
+
inlineSkolemNames = sk.skolemToName;
|
|
338
|
+
const scoped = scopeSkolems(engine, sk.skolemToName);
|
|
339
|
+
inlineMethodThisType = sk.thisType && scoped(sk.thisType);
|
|
340
|
+
inlineExpectedType = scoped(sk.expectedType);
|
|
341
|
+
}
|
|
342
|
+
const methodScheme = { vars: annotation.scheme.vars, type: inlineExpectedType };
|
|
343
|
+
inlineAnnotation = { ...annotation, scheme: methodScheme };
|
|
344
|
+
expectedType = inlineExpectedType;
|
|
345
|
+
}
|
|
346
|
+
// Method annotations with receivers (handled elsewhere) may still carry a
|
|
347
|
+
// name mismatch that should be reported at the implementation site.
|
|
348
|
+
if (annotation?.methodNameMismatch && annotation.name) {
|
|
349
|
+
// Point the diagnostic at the name identifier when location info is available,
|
|
350
|
+
// otherwise fall back to the whole function node.
|
|
351
|
+
const mismatchLoc = (annotation.mismatchNameStart != null && annotation.mismatchNameEnd != null)
|
|
352
|
+
? { start: annotation.mismatchNameStart, end: annotation.mismatchNameEnd }
|
|
353
|
+
: node;
|
|
354
|
+
engine.addDiag((0, annotations_1.methodNameMismatchMessage)(annotation.methodNameMismatch, annotation.name), mismatchLoc, [{ message: `Annotation '${annotation.name}' defined here`, start: annotation.commentStart, end: annotation.commentEnd }]);
|
|
355
|
+
}
|
|
356
|
+
// For explicit inline annotations on anonymous callbacks, do not allow
|
|
357
|
+
// auto-union to silently broaden mismatches (e.g. Number vs Boolean).
|
|
358
|
+
const prevSuppressAutoUnion = engine.suppressAutoUnion;
|
|
359
|
+
if (inlineAnnotation) {
|
|
360
|
+
engine.suppressAutoUnion = true;
|
|
361
|
+
}
|
|
362
|
+
let pushedEnclosingReturn = false;
|
|
363
|
+
try {
|
|
364
|
+
// Create fresh type variables for parameters
|
|
365
|
+
let fnEnv = env;
|
|
366
|
+
// Bind `this` for inline method annotations (e.g. Box#map :: Box a ~> ...)
|
|
367
|
+
// so that `this.value` etc. resolve correctly inside the method body.
|
|
368
|
+
if (inlineMethodThisType) {
|
|
369
|
+
fnEnv = fnEnv.extend('this', (0, types_1.mono)(inlineMethodThisType));
|
|
370
|
+
// Mark `this` as coming from a signature receiver so hover freezes it
|
|
371
|
+
// (renders with the signature's own letters — rule #1).
|
|
372
|
+
fnEnv = fnEnv.extend('__signatureThis', (0, types_1.mono)(types_1.tVoid));
|
|
373
|
+
}
|
|
374
|
+
// If we have an expected type from an annotation, decompose it to get
|
|
375
|
+
// parameter types so they are known *before* body inference.
|
|
376
|
+
let expectedParamTypes;
|
|
377
|
+
let expectedBodyType;
|
|
378
|
+
let extraExpectedParamTypes;
|
|
379
|
+
// Per-position DISPLAY unions for overloaded functions (union-of-TFun
|
|
380
|
+
// annotations). These are display-only — the body keeps fresh monomorphic
|
|
381
|
+
// parameter vars — but they drive hover and call-site polymorphism
|
|
382
|
+
// protection for every reference to the parameter.
|
|
383
|
+
let frozenParamDisplays;
|
|
384
|
+
if (expectedType) {
|
|
385
|
+
const resolved = engine.subst.apply(expectedType);
|
|
386
|
+
const decomposed = (0, types_1.decomposeFunParams)(resolved, node.params.length);
|
|
387
|
+
if (decomposed) {
|
|
388
|
+
expectedParamTypes = decomposed.paramTypes;
|
|
389
|
+
expectedBodyType = decomposed.restType;
|
|
390
|
+
extraExpectedParamTypes = decomposed.extraParamTypes;
|
|
391
|
+
}
|
|
392
|
+
else if (resolved.tag === 'TCon' && resolved.name === types_1.T_UNION) {
|
|
393
|
+
// Union expected type. Since this code only runs for function literals
|
|
394
|
+
// (arrow / function expressions), the argument can only inhabit a
|
|
395
|
+
// function-typed branch — the non-function members (e.g. the `Undefined`
|
|
396
|
+
// of an optional-callback slot `((String, String) -> Number) | Undefined`)
|
|
397
|
+
// are impossible for a literal function. Filter to the callable branches
|
|
398
|
+
// and NARROW the union to them.
|
|
399
|
+
const funBranches = resolved.args.filter(b => b.tag === 'TFun');
|
|
400
|
+
if (funBranches.length === 1) {
|
|
401
|
+
// Single callable branch (typically an optional-callback slot).
|
|
402
|
+
// Decompose it directly so the parameters get their contextual types
|
|
403
|
+
// BEFORE body inference. Without this the arrow's params stay fresh
|
|
404
|
+
// vars and only get back-propagated by a whole-function unify against
|
|
405
|
+
// the union — which fails atomically while the body is still being
|
|
406
|
+
// typed (e.g. `(a, b) => a` before the comparison is written), losing
|
|
407
|
+
// hover/completion inside the body.
|
|
408
|
+
const branchDecomposed = (0, types_1.decomposeFunParams)(funBranches[0], node.params.length);
|
|
409
|
+
if (branchDecomposed) {
|
|
410
|
+
expectedParamTypes = branchDecomposed.paramTypes;
|
|
411
|
+
expectedBodyType = branchDecomposed.restType;
|
|
412
|
+
extraExpectedParamTypes = branchDecomposed.extraParamTypes;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
else if (funBranches.length >= 2) {
|
|
416
|
+
// Overloaded annotation: compute the union of each parameter position
|
|
417
|
+
// across all callable branches for display. Decompose every branch by
|
|
418
|
+
// this arrow level's arity and collect per-position types.
|
|
419
|
+
const arity = node.params.length;
|
|
420
|
+
const perBranch = funBranches.map(b => (0, types_1.decomposeFunParams)(b, arity));
|
|
421
|
+
if (perBranch.every(d => d != null && d.paramTypes.length === arity)) {
|
|
422
|
+
frozenParamDisplays = [];
|
|
423
|
+
for (let i = 0; i < arity; i++) {
|
|
424
|
+
frozenParamDisplays.push((0, types_1.canonicalizeDisplayVarsByName)((0, types_1.tUnion)(perBranch.map(d => d.paramTypes[i]))));
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
// For async functions, the body's `return X` produces an `X` value but
|
|
431
|
+
// the function's caller-visible return type is `Promise X`. When an
|
|
432
|
+
// outer annotation pins the function as `... -> Promise T`, the body
|
|
433
|
+
// should be checked against `T` (not `Promise T`). Peel one Promise
|
|
434
|
+
// layer off the expected body type so unification of the inner return
|
|
435
|
+
// expression succeeds.
|
|
436
|
+
if (node.async && expectedBodyType) {
|
|
437
|
+
const resolvedExpected = engine.subst.apply(expectedBodyType);
|
|
438
|
+
if (resolvedExpected.tag === 'TCon' && resolvedExpected.name === 'Promise'
|
|
439
|
+
&& resolvedExpected.args.length === 2) {
|
|
440
|
+
expectedBodyType = resolvedExpected.args[1];
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
// A callback whose context expects `… -> ()` (an event handler, a
|
|
444
|
+
// `forEach` body): its result is ignored, as in TypeScript, where
|
|
445
|
+
// `() => void` accepts any result. `onClick={() => dispatch (action)}`
|
|
446
|
+
// is then fine. Only for a function literal without its own annotation
|
|
447
|
+
// (an annotated `f :: () -> ()` that returns a value stays an error).
|
|
448
|
+
let discardsResult = false;
|
|
449
|
+
const ownBinding = engine.annotationMethodNode;
|
|
450
|
+
const hasOwnAnnotation = !!inlineAnnotation || (ownBinding != null && ownBinding.init === node);
|
|
451
|
+
if (!hasOwnAnnotation && expectedBodyType && !node.generator && !node.async) {
|
|
452
|
+
const expectedResult = engine.subst.apply(expectedBodyType);
|
|
453
|
+
if (expectedResult.tag === 'TCon' && expectedResult.name === 'Void' && expectedResult.args.length === 0) {
|
|
454
|
+
discardsResult = true;
|
|
455
|
+
expectedBodyType = undefined;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
// Expose the annotated signature's RETURN type to nested method annotations
|
|
459
|
+
// while this body is inferred: a `Type#m :: Type e a ~> …` on a const inside
|
|
460
|
+
// this function describes a method of the record under construction, so its
|
|
461
|
+
// receiver vars should be THIS signature's vars (see the method-annotation
|
|
462
|
+
// branch above). Only for the rigid (skolemized) path — constrained
|
|
463
|
+
// annotations keep their flexible constraint-aware instantiation.
|
|
464
|
+
if (inlineAnnotation && inlineSkolemNames && expectedBodyType) {
|
|
465
|
+
engine.enclosingAnnotatedReturns.push((0, types_1.getReturnType)(expectedBodyType));
|
|
466
|
+
pushedEnclosingReturn = true;
|
|
467
|
+
}
|
|
468
|
+
// Checked against its own annotation: the parameters' rows are rigid in
|
|
469
|
+
// the body (`{ name :: String, ...r }` has no `title`).
|
|
470
|
+
const ownDeclaration = engine.annotationMethodNode;
|
|
471
|
+
if (expectedParamTypes && (hasOwnAnnotation || ownDeclaration === node)) {
|
|
472
|
+
const rows = new Set(engine.rigidRowIds);
|
|
473
|
+
for (const p of expectedParamTypes)
|
|
474
|
+
collectRowIds(engine.subst.apply(p), rows);
|
|
475
|
+
engine.rigidRowIds = rows;
|
|
476
|
+
}
|
|
477
|
+
const { fnEnv: fnEnvBound, paramTypes } = bindFunctionParams(engine, node.params, expectedParamTypes, fnEnv, frozenParamDisplays);
|
|
478
|
+
fnEnv = fnEnvBound;
|
|
479
|
+
// Named function expressions (e.g. `(function step(v) { … })(i)`) bind
|
|
480
|
+
// their own name inside the body scope so self-recursive calls resolve.
|
|
481
|
+
// Bind a fresh var now; it is unified with the assembled function type
|
|
482
|
+
// below, once the body has been inferred.
|
|
483
|
+
let selfRefVar;
|
|
484
|
+
const fnExprName = node.type === 'FunctionExpression' ? node.id?.name : undefined;
|
|
485
|
+
if (fnExprName) {
|
|
486
|
+
selfRefVar = (0, types_1.tVar)();
|
|
487
|
+
fnEnv = fnEnv.extend(fnExprName, (0, types_1.mono)(selfRefVar));
|
|
488
|
+
}
|
|
489
|
+
// Hoist function-scoped `var` declarations. JavaScript `var`s are visible
|
|
490
|
+
// throughout the whole function body regardless of the block they appear in,
|
|
491
|
+
// so pre-bind every `var` name (excluding those already bound as parameters)
|
|
492
|
+
// with a fresh type variable. Without this, a `var` declared in one block
|
|
493
|
+
// and reused in a sibling block (e.g. two `for` loops sharing `var idx`)
|
|
494
|
+
// reports a spurious "Unbound variable". Later `VariableDeclaration` /
|
|
495
|
+
// assignment inference refines these fresh vars.
|
|
496
|
+
if (node.body.type === 'BlockStatement') {
|
|
497
|
+
const paramNames = new Set();
|
|
498
|
+
collectPatternNames(node.params, paramNames);
|
|
499
|
+
const hoistedVarNames = new Set();
|
|
500
|
+
collectHoistedVarNames(node.body, hoistedVarNames);
|
|
501
|
+
for (const vname of hoistedVarNames) {
|
|
502
|
+
if (paramNames.has(vname))
|
|
503
|
+
continue;
|
|
504
|
+
fnEnv = fnEnv.extend(vname, (0, types_1.mono)((0, types_1.tVar)()));
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
// Infer body, passing remaining expected type for nested functions
|
|
508
|
+
// When the annotation has a spread tuple, the body may contain
|
|
509
|
+
// reduce/reduceRight calls whose internal typing can't fully express
|
|
510
|
+
// the polymorphic chain composition. Suppress diagnostics produced
|
|
511
|
+
// during body inference in that case — the annotation is the source
|
|
512
|
+
// of truth.
|
|
513
|
+
const hasSpreadParam = paramTypes.some(p => (0, typeUtils_1.isSpreadTupleOrArray)(p) ||
|
|
514
|
+
// Curry wrapper: param is a function with spread tuple
|
|
515
|
+
(p.tag === 'TFun' && (0, typeUtils_1.isSpreadTupleOrArray)(p.param)));
|
|
516
|
+
const diagsBefore = hasSpreadParam ? engine.diagnostics.length : -1;
|
|
517
|
+
// Generators: the declared return type is the YIELD (element) type, and the
|
|
518
|
+
// body's own `return`s produce the generator's *return value* (typically
|
|
519
|
+
// undefined). Capture the declared element type, stop checking `return`s
|
|
520
|
+
// against it, and start a yield frame so `yield`/`yield*` expressions
|
|
521
|
+
// contribute their element types (collected in expressions.ts YieldExpression).
|
|
522
|
+
let expectedYieldType;
|
|
523
|
+
if (node.generator) {
|
|
524
|
+
expectedYieldType = expectedBodyType;
|
|
525
|
+
expectedBodyType = undefined;
|
|
526
|
+
engine.generatorYieldStack.push([]);
|
|
527
|
+
}
|
|
528
|
+
let returnType;
|
|
529
|
+
if (node.body.type === 'BlockStatement') {
|
|
530
|
+
// Block body: look for return statements
|
|
531
|
+
returnType = inferBlockReturnType(engine, node.body, fnEnv, expectedBodyType);
|
|
532
|
+
}
|
|
533
|
+
else {
|
|
534
|
+
// Expression body (arrow function)
|
|
535
|
+
returnType = (0, expressions_1.inferExpressionWithExpected)(engine, node.body, fnEnv, expectedBodyType);
|
|
536
|
+
// Check: expression body returning a union where a concrete type is expected
|
|
537
|
+
if (expectedBodyType) {
|
|
538
|
+
checkUnionVsExpected(engine, returnType, expectedBodyType, node.body);
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
if (discardsResult)
|
|
542
|
+
returnType = types_1.tVoid;
|
|
543
|
+
// Drop body diagnostics for spread-annotated functions
|
|
544
|
+
if (diagsBefore >= 0) {
|
|
545
|
+
engine.diagnostics.length = diagsBefore;
|
|
546
|
+
}
|
|
547
|
+
// Generators: replace the inferred `return`-based result with the collected
|
|
548
|
+
// yield (element) type so the function type is `(params) -> <element>`. A
|
|
549
|
+
// call to the function wraps this element type in `Generator` at the call
|
|
550
|
+
// site (see calls.ts / engine.generatorFunctionNames).
|
|
551
|
+
if (node.generator) {
|
|
552
|
+
const frame = engine.generatorYieldStack.pop() ?? [];
|
|
553
|
+
const applied = frame.map((t) => engine.subst.apply(t));
|
|
554
|
+
let yieldType = applied.length === 0 ? (0, types_1.tVar)()
|
|
555
|
+
: applied.length === 1 ? applied[0]
|
|
556
|
+
: (0, types_1.tUnion)(applied);
|
|
557
|
+
if (expectedYieldType) {
|
|
558
|
+
engine.unifyWithDiagnostic(yieldType, engine.subst.apply(expectedYieldType), node);
|
|
559
|
+
yieldType = engine.subst.apply(expectedYieldType);
|
|
560
|
+
}
|
|
561
|
+
returnType = yieldType;
|
|
562
|
+
}
|
|
563
|
+
// Build function type:
|
|
564
|
+
// 1 param: a -> result
|
|
565
|
+
// 2+ params: (a, b, ...) -> result (Tuple-based)
|
|
566
|
+
// When a function expression has fewer params than the expected type
|
|
567
|
+
// (JS allows ignoring trailing callback params), pad the function type
|
|
568
|
+
// with the extra expected param types so it matches the caller's shape.
|
|
569
|
+
let allParams = paramTypes.map((p) => engine.subst.apply(p));
|
|
570
|
+
if (extraExpectedParamTypes && extraExpectedParamTypes.length > 0) {
|
|
571
|
+
allParams = [...allParams, ...extraExpectedParamTypes];
|
|
572
|
+
}
|
|
573
|
+
let funcType = (0, types_1.tMultiFun)(allParams, returnType);
|
|
574
|
+
// Zero-param function expressions: tMultiFun([], T) collapses to T, but the
|
|
575
|
+
// expression IS a function, so wrap as () -> T to preserve the function
|
|
576
|
+
// shape. This must happen EVEN when T is itself a function (e.g. a thunk
|
|
577
|
+
// `() => x => x` returning `a -> a`): without the wrapper the nullary level
|
|
578
|
+
// is lost and the value looks like a plain unary `a -> a`, which breaks
|
|
579
|
+
// immediately-invoked uses such as `(() => x => x)()`.
|
|
580
|
+
if (allParams.length === 0) {
|
|
581
|
+
funcType = (0, types_1.tFun)(types_1.tVoid, funcType);
|
|
582
|
+
}
|
|
583
|
+
// Async functions: wrap return type in Promise<T> if not already a Promise.
|
|
584
|
+
// Normally the wrap is skipped when an annotation provides a complete
|
|
585
|
+
// expectedType (because the annotation should already mention Promise).
|
|
586
|
+
// However when an outer annotation pins this function as `... -> Promise T`
|
|
587
|
+
// we peeled the Promise off expectedBodyType above so the body could
|
|
588
|
+
// unify with `T`; here we wrap the inferred return back into `Promise T`
|
|
589
|
+
// so the function type matches the annotation shape.
|
|
590
|
+
const expectedReturnIsPromise = !!expectedBodyType
|
|
591
|
+
&& (() => {
|
|
592
|
+
// expectedBodyType has been peeled if outer was Promise; check the
|
|
593
|
+
// *original* expected return type instead.
|
|
594
|
+
if (!expectedType)
|
|
595
|
+
return false;
|
|
596
|
+
const r = engine.subst.apply(expectedType);
|
|
597
|
+
const dec = (0, types_1.decomposeFunParams)(r, node.params.length);
|
|
598
|
+
const orig = dec?.restType ? engine.subst.apply(dec.restType) : null;
|
|
599
|
+
return !!orig && orig.tag === 'TCon' && orig.name === 'Promise';
|
|
600
|
+
})();
|
|
601
|
+
if (node.async && (!expectedType || expectedReturnIsPromise)) {
|
|
602
|
+
const resolvedReturn = engine.subst.apply(returnType);
|
|
603
|
+
if (!(resolvedReturn.tag === 'TCon' && resolvedReturn.name === 'Promise')) {
|
|
604
|
+
const wrappedReturn = (0, types_1.tCon)('Promise', [(0, types_1.tVar)(), resolvedReturn]);
|
|
605
|
+
funcType = (0, types_1.tMultiFun)(allParams, wrappedReturn);
|
|
606
|
+
if (allParams.length === 0) {
|
|
607
|
+
funcType = (0, types_1.tFun)(types_1.tVoid, funcType);
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
// Tie the self-reference var of a named function expression to the final
|
|
612
|
+
// function type so recursive calls in the body agree with the whole type.
|
|
613
|
+
if (selfRefVar) {
|
|
614
|
+
engine.unifyWithDiagnostic(engine.subst.apply(selfRefVar), funcType, node);
|
|
615
|
+
funcType = engine.subst.apply(funcType);
|
|
616
|
+
}
|
|
617
|
+
// For FunctionDeclaration nodes, inferFunctionDeclaration (statements.ts)
|
|
618
|
+
// already handles annotation checking — skip the validate call here to avoid
|
|
619
|
+
// duplicate diagnostics, and leave the body skolems on the returned type so
|
|
620
|
+
// statements.ts's own rigid check can still detect a genuinely wrong body
|
|
621
|
+
// (the central scrub in checkAnnotationRigid removes the false self-mismatch
|
|
622
|
+
// while preserving real shape differences). The declaration binds and
|
|
623
|
+
// displays the annotation scheme directly, so the skolems never surface.
|
|
624
|
+
if (inlineAnnotation?.scheme && inlineExpectedType && node.type !== 'FunctionDeclaration'
|
|
625
|
+
&& engine.annotationCheckedByBinding !== node) {
|
|
626
|
+
funcType = validateInlineAnnotation(engine, funcType, inlineAnnotation, inlineExpectedType, node);
|
|
627
|
+
// When the body was checked against rigid skolems, the annotation is the
|
|
628
|
+
// authoritative type — the body only *validates* against it and must not
|
|
629
|
+
// determine the displayed parameter / `this` / return types (a stub body
|
|
630
|
+
// that returned `()` would otherwise leak into the signature). Replace the
|
|
631
|
+
// returned function type with the annotation itself, scrubbing the skolems
|
|
632
|
+
// back to ordinary display variables so no downstream consumer (call sites,
|
|
633
|
+
// generalize(), or a second rigid check at the assignment / prototype site)
|
|
634
|
+
// ever sees `§N` constants.
|
|
635
|
+
if (inlineSkolemNames) {
|
|
636
|
+
funcType = (0, typeUtils_1.scrubSkolems)(engine.subst.apply(inlineExpectedType), inlineSkolemNames);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
// Detect literal equality guard patterns for conditional return narrowing.
|
|
640
|
+
if (node.body?.type === 'BlockStatement' && !inlineAnnotation && !expectedType) {
|
|
641
|
+
tryDetectConditionalReturn(engine, node, returnType);
|
|
642
|
+
}
|
|
643
|
+
return funcType;
|
|
644
|
+
}
|
|
645
|
+
finally {
|
|
646
|
+
engine.suppressAutoUnion = prevSuppressAutoUnion;
|
|
647
|
+
if (pushedEnclosingReturn)
|
|
648
|
+
engine.enclosingAnnotatedReturns.pop();
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* Bind the parameters of a function to fresh type variables (or the expected
|
|
653
|
+
* types provided by an outer annotation) and extend the function's local
|
|
654
|
+
* environment accordingly. Returns the extended environment and the ordered
|
|
655
|
+
* list of parameter types so the caller can build the function's TFun type.
|
|
656
|
+
*/
|
|
657
|
+
/** Ids of the row variables (`...r`) of every record inside a type. */
|
|
658
|
+
function collectRowIds(t, out) {
|
|
659
|
+
switch (t.tag) {
|
|
660
|
+
case 'TRecord':
|
|
661
|
+
if (t.rest && (t.rest.tag === 'TVar' || t.rest.tag === 'TRow'))
|
|
662
|
+
out.add(t.rest.id);
|
|
663
|
+
for (const f of Object.values(t.fields))
|
|
664
|
+
collectRowIds(f, out);
|
|
665
|
+
return;
|
|
666
|
+
case 'TFun':
|
|
667
|
+
collectRowIds(t.param, out);
|
|
668
|
+
collectRowIds(t.result, out);
|
|
669
|
+
return;
|
|
670
|
+
case 'TCon':
|
|
671
|
+
for (const a of t.args)
|
|
672
|
+
collectRowIds(a, out);
|
|
673
|
+
return;
|
|
674
|
+
default:
|
|
675
|
+
return;
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
function bindFunctionParams(engine, params, expectedParamTypes, env, frozenDisplays) {
|
|
679
|
+
let fnEnv = env;
|
|
680
|
+
const paramTypes = [];
|
|
681
|
+
// A variadic expected shape (`(a, b, ...) -> z`, e.g. `curryN (3) ((x, y,
|
|
682
|
+
// flag) => …)`) fixes only the positions BEFORE its `...`; the spread
|
|
683
|
+
// marker itself is never a parameter's type.
|
|
684
|
+
const spreadIdx = expectedParamTypes ? expectedParamTypes.findIndex(types_1.isSpread) : -1;
|
|
685
|
+
if (spreadIdx >= 0)
|
|
686
|
+
expectedParamTypes = expectedParamTypes.slice(0, spreadIdx);
|
|
687
|
+
for (let i = 0; i < params.length; i++) {
|
|
688
|
+
const param = params[i];
|
|
689
|
+
// When an expected param type is available (from an annotation or
|
|
690
|
+
// caller), use it directly instead of creating a fresh TVar.
|
|
691
|
+
// This preserves the original TVars so that auto-union can trace
|
|
692
|
+
// back to them through the substitution chain.
|
|
693
|
+
let paramType;
|
|
694
|
+
if (expectedParamTypes && i < expectedParamTypes.length) {
|
|
695
|
+
paramType = expectedParamTypes[i];
|
|
696
|
+
}
|
|
697
|
+
else if (param.type === 'RestElement') {
|
|
698
|
+
// Rest parameter without annotation: use wildcard type (*)
|
|
699
|
+
// so that (...args) => fn(...args) infers as (* -> a) -> * -> a
|
|
700
|
+
paramType = types_1.tAny;
|
|
701
|
+
}
|
|
702
|
+
else {
|
|
703
|
+
paramType = (0, types_1.tVar)();
|
|
704
|
+
}
|
|
705
|
+
paramTypes.push(paramType);
|
|
706
|
+
// A parameter's *declared* type is the annotation the user wrote. Body
|
|
707
|
+
// inference may later bind the annotation's row / value vars (e.g.
|
|
708
|
+
// `Object.keys(obj)` closing an open `{ a }` row to `{}`), which would
|
|
709
|
+
// poison the live-substituted hover type. Capture the annotated shape now
|
|
710
|
+
// so hover can always display the signature form the user wrote, for every
|
|
711
|
+
// object form (`{ a }`, `{ ...a }`, `{ [k] :: a }`, `{ x :: Number }`, …).
|
|
712
|
+
const isAnnotatedParam = !!(expectedParamTypes && i < expectedParamTypes.length);
|
|
713
|
+
// Overloaded functions expose a per-position UNION as the parameter's
|
|
714
|
+
// declared type (e.g. `foldable :: f a | String`). The body keeps a fresh
|
|
715
|
+
// monomorphic variable (so branch inference is unaffected), but the binding
|
|
716
|
+
// carries the union as its `frozenDisplay` — this drives hover at every
|
|
717
|
+
// reference AND lets call sites protect the polymorphic parameter from
|
|
718
|
+
// being pinned by unrelated helpers (see `shouldProtectPolymorphicParamArg`).
|
|
719
|
+
const frozenDisplay = !isAnnotatedParam ? frozenDisplays?.[i] : undefined;
|
|
720
|
+
if (param.type === 'Identifier') {
|
|
721
|
+
// Rank-N: a `forall`-annotated parameter binds POLYMORPHICALLY in the
|
|
722
|
+
// body. The binding is a genuine Scheme quantifying the forall's own
|
|
723
|
+
// vars, so EVERY use of the parameter instantiates fresh — `f(n)` and
|
|
724
|
+
// `f(s)` in one body each get their own copy of `a -> a`. The TForall
|
|
725
|
+
// itself is kept as `frozenDisplay` so hover renders the quantifier.
|
|
726
|
+
if (paramType.tag === 'TForall') {
|
|
727
|
+
const polyScheme = {
|
|
728
|
+
vars: paramType.vars,
|
|
729
|
+
type: paramType.body,
|
|
730
|
+
constraints: paramType.constraints,
|
|
731
|
+
frozenDisplay: paramType,
|
|
732
|
+
};
|
|
733
|
+
fnEnv = fnEnv.extend(param.name, polyScheme);
|
|
734
|
+
engine.recordNodeType(param, paramType);
|
|
735
|
+
engine.frozenParamType.set(param.start, paramType);
|
|
736
|
+
}
|
|
737
|
+
else if (paramType.tag === 'TCon' && paramType.name === types_1.T_SPREAD_ARRAY &&
|
|
738
|
+
paramType.args.some(a => (0, types_1.isSpread)(a))) {
|
|
739
|
+
// If the expected param type is a SpreadArray, bind as Array<elemType> in the body
|
|
740
|
+
const firstElem = paramType.args.find(a => !(0, types_1.isSpread)(a));
|
|
741
|
+
const elemType = firstElem ? (0, typeUtils_1.freshenType)(firstElem) : (0, types_1.tVar)();
|
|
742
|
+
const bound = (0, types_1.tArray)(elemType);
|
|
743
|
+
fnEnv = fnEnv.extend(param.name, isAnnotatedParam ? (0, types_1.monoFrozen)(bound) : (0, types_1.mono)(bound));
|
|
744
|
+
engine.recordNodeType(param, bound);
|
|
745
|
+
if (isAnnotatedParam)
|
|
746
|
+
engine.frozenParamType.set(param.start, bound);
|
|
747
|
+
}
|
|
748
|
+
else if (frozenDisplay) {
|
|
749
|
+
fnEnv = fnEnv.extend(param.name, (0, types_1.monoFrozen)(paramType, frozenDisplay));
|
|
750
|
+
engine.recordNodeType(param, frozenDisplay);
|
|
751
|
+
engine.frozenParamType.set(param.start, frozenDisplay);
|
|
752
|
+
}
|
|
753
|
+
else {
|
|
754
|
+
fnEnv = fnEnv.extend(param.name, isAnnotatedParam ? (0, types_1.monoFrozen)(paramType) : (0, types_1.mono)(paramType));
|
|
755
|
+
engine.recordNodeType(param, paramType);
|
|
756
|
+
if (isAnnotatedParam)
|
|
757
|
+
engine.frozenParamType.set(param.start, paramType);
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
else if (param.type === 'AssignmentPattern') {
|
|
761
|
+
// Default parameter: (x = defaultValue)
|
|
762
|
+
const ident = param.left;
|
|
763
|
+
if (ident?.type === 'Identifier') {
|
|
764
|
+
// Treat `(x = undefined)` purely as an optionality marker — do
|
|
765
|
+
// not unify the param type with `Undefined`. This keeps `x`
|
|
766
|
+
// polymorphic so annotations like `(a, b, c) -> r` remain valid
|
|
767
|
+
// while signaling to call-site arity checks that the slot may
|
|
768
|
+
// be omitted (see `optionalParamSlots`).
|
|
769
|
+
const isUndefinedDefault = param.right?.type === 'Identifier' &&
|
|
770
|
+
param.right.name === 'undefined';
|
|
771
|
+
if (!isUndefinedDefault) {
|
|
772
|
+
const defaultType = (0, expressions_1.inferExpression)(engine, param.right, fnEnv);
|
|
773
|
+
engine.unifyWithDiagnostic(paramType, defaultType, param.right);
|
|
774
|
+
}
|
|
775
|
+
let resolvedParamType = engine.subst.apply(paramType);
|
|
776
|
+
// A default value guarantees the parameter is never Undefined at runtime.
|
|
777
|
+
const narrowed = (0, narrowing_1.removeNullUndefined)(resolvedParamType);
|
|
778
|
+
// The *declared* type for display is the annotation (pre-narrow); the
|
|
779
|
+
// body binding stays `narrowed` so inference is unaffected.
|
|
780
|
+
fnEnv = fnEnv.extend(ident.name, isAnnotatedParam ? (0, types_1.monoFrozen)(narrowed, paramType) : (0, types_1.mono)(narrowed));
|
|
781
|
+
engine.recordNodeType(ident, narrowed);
|
|
782
|
+
if (isAnnotatedParam)
|
|
783
|
+
engine.frozenParamType.set(ident.start, paramType);
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
else if (param.type === 'RestElement') {
|
|
787
|
+
// Rest parameter: (...args) — type args as Array<elemType>
|
|
788
|
+
const ident = param.argument;
|
|
789
|
+
if (ident?.type === 'Identifier') {
|
|
790
|
+
let elemType;
|
|
791
|
+
if ((0, types_1.isTuple)(paramType) &&
|
|
792
|
+
paramType.args.some(a => (0, types_1.isSpread)(a))) {
|
|
793
|
+
const firstElem = paramType.args.find(a => !(0, types_1.isSpread)(a));
|
|
794
|
+
elemType = firstElem ? (0, typeUtils_1.freshenType)(firstElem) : (0, types_1.tVar)();
|
|
795
|
+
}
|
|
796
|
+
else {
|
|
797
|
+
elemType = (0, types_1.tVar)();
|
|
798
|
+
}
|
|
799
|
+
const bound = (0, types_1.tArray)(elemType);
|
|
800
|
+
fnEnv = fnEnv.extend(ident.name, isAnnotatedParam ? (0, types_1.monoFrozen)(bound) : (0, types_1.mono)(bound));
|
|
801
|
+
engine.recordNodeType(ident, bound);
|
|
802
|
+
if (isAnnotatedParam)
|
|
803
|
+
engine.frozenParamType.set(ident.start, bound);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
else if (param.type === 'ObjectPattern' || param.type === 'ArrayPattern') {
|
|
807
|
+
const { env: destructuredEnv } = engine.inferDestructuringPattern(param, paramType, fnEnv, 'const', isAnnotatedParam);
|
|
808
|
+
fnEnv = destructuredEnv;
|
|
809
|
+
// Record the pattern's type so completion/hover can resolve the
|
|
810
|
+
// destructured parameter to its full record/array type.
|
|
811
|
+
engine.recordNodeType(param, paramType);
|
|
812
|
+
if (isAnnotatedParam)
|
|
813
|
+
engine.frozenParamType.set(param.start, paramType);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
return { fnEnv, paramTypes };
|
|
817
|
+
}
|
|
818
|
+
/**
|
|
819
|
+
* When a function's inferred return type is a Union, check whether its body
|
|
820
|
+
* contains a literal equality guard pattern (e.g. `if (x === 'a') return T`).
|
|
821
|
+
* If so, record the guard info so that call sites passing a matching literal
|
|
822
|
+
* can narrow the union return type to just the branch's return type.
|
|
823
|
+
*/
|
|
824
|
+
function tryDetectConditionalReturn(engine, node, returnType) {
|
|
825
|
+
const resolvedReturn = engine.subst.apply(returnType);
|
|
826
|
+
if (!(0, types_1.isUnion)(resolvedReturn))
|
|
827
|
+
return;
|
|
828
|
+
const paramNames = [];
|
|
829
|
+
for (const param of node.params) {
|
|
830
|
+
if (param.type === 'Identifier') {
|
|
831
|
+
paramNames.push(param.name);
|
|
832
|
+
}
|
|
833
|
+
else if (param.type === 'AssignmentPattern' && param.left?.type === 'Identifier') {
|
|
834
|
+
paramNames.push(param.left.name);
|
|
835
|
+
}
|
|
836
|
+
else {
|
|
837
|
+
paramNames.push('');
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
if (paramNames.length >= 1) {
|
|
841
|
+
const guardInfo = (0, narrowing_1.extractLiteralGuardReturnInfo)(engine.subst, node.body, paramNames, (n) => collectAllReturnTypes(engine, n));
|
|
842
|
+
if (guardInfo)
|
|
843
|
+
engine.pendingConditionalReturn = guardInfo;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Check that a union return type is compatible with a concrete expected type.
|
|
848
|
+
* The standard unifier is too lenient here — it lets Union(A, B) unify with
|
|
849
|
+
* A because A is a member. This helper verifies each union member individually
|
|
850
|
+
* and emits a diagnostic at `reportNode` if any member fails to match.
|
|
851
|
+
*/
|
|
852
|
+
/** The members of a (nested) union, resolved and with aliases expanded. */
|
|
853
|
+
function flattenUnionMembers(engine, t) {
|
|
854
|
+
const out = [];
|
|
855
|
+
const collect = (u) => {
|
|
856
|
+
const r = engine.maybeExpandAlias(engine.subst.apply(u));
|
|
857
|
+
if ((0, types_1.isUnion)(r))
|
|
858
|
+
for (const m of r.args)
|
|
859
|
+
collect(m);
|
|
860
|
+
else
|
|
861
|
+
out.push(r);
|
|
862
|
+
};
|
|
863
|
+
collect(t);
|
|
864
|
+
return out;
|
|
865
|
+
}
|
|
866
|
+
function checkUnionVsExpected(engine, returnType, expectedType, reportNode) {
|
|
867
|
+
const resolvedReturn = engine.subst.apply(returnType);
|
|
868
|
+
const resolvedExpected = engine.subst.apply(expectedType);
|
|
869
|
+
// Both unions (`b ? "ja" : b ? 2 : null` against `String | Null`): every
|
|
870
|
+
// returned member must fit a member of the expected union. The symmetric
|
|
871
|
+
// unifier accepts two unions as soon as one contains the other, so the
|
|
872
|
+
// returned `Null | Number | String` passed for `String | Null`.
|
|
873
|
+
if ((0, types_1.isUnion)(resolvedReturn) && (0, types_1.isUnion)(resolvedExpected)) {
|
|
874
|
+
const expectedMembers = flattenUnionMembers(engine, resolvedExpected);
|
|
875
|
+
if (expectedMembers.some(m => m.tag === 'TVar' || (0, types_1.isAnyType)(m)))
|
|
876
|
+
return;
|
|
877
|
+
const stray = flattenUnionMembers(engine, resolvedReturn).find(member => member.tag !== 'TVar' && !(0, types_1.isAnyType)(member)
|
|
878
|
+
&& !expectedMembers.some(expected => {
|
|
879
|
+
try {
|
|
880
|
+
(0, unify_1.unify)(member, expected);
|
|
881
|
+
return true;
|
|
882
|
+
}
|
|
883
|
+
catch {
|
|
884
|
+
return false;
|
|
885
|
+
}
|
|
886
|
+
}));
|
|
887
|
+
if (!stray)
|
|
888
|
+
return;
|
|
889
|
+
// Only where the symmetric unifier would accept the pair; otherwise the
|
|
890
|
+
// annotation check reports the mismatch already.
|
|
891
|
+
try {
|
|
892
|
+
(0, unify_1.unify)(resolvedReturn, resolvedExpected);
|
|
893
|
+
}
|
|
894
|
+
catch {
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
const anchor = engine.annotationMethodNode ?? reportNode;
|
|
898
|
+
const name = (0, annotations_1.bindingNameFromNode)(anchor);
|
|
899
|
+
const ann = name ? engine.lookupAnnotation(name, anchor.start ?? 0) : undefined;
|
|
900
|
+
const expectedFull = ann?.scheme ? (0, env_1.instantiate)(ann.scheme) : resolvedExpected;
|
|
901
|
+
const inferredFull = expectedFull.tag === 'TFun' ? (0, types_1.tFun)(expectedFull.param, resolvedReturn) : resolvedReturn;
|
|
902
|
+
if ((0, types_1.containsErrorType)(inferredFull) || (0, types_1.containsErrorType)(expectedFull))
|
|
903
|
+
return;
|
|
904
|
+
engine.addDiag((0, annotations_1.annotationMismatchMessage)(name, inferredFull, expectedFull), (0, annotations_1.narrowToIdentifier)(anchor));
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
if ((0, types_1.isUnion)(resolvedReturn) &&
|
|
908
|
+
!(0, types_1.isUnion)(resolvedExpected) &&
|
|
909
|
+
resolvedExpected.tag !== 'TVar') {
|
|
910
|
+
// Flatten nested unions so (Boolean | (Number | Boolean)) becomes [Boolean, Number, Boolean]
|
|
911
|
+
const flatMembers = [];
|
|
912
|
+
const collect = (t) => {
|
|
913
|
+
if ((0, types_1.isUnion)(t)) {
|
|
914
|
+
for (const m of t.args)
|
|
915
|
+
collect(m);
|
|
916
|
+
}
|
|
917
|
+
else {
|
|
918
|
+
flatMembers.push(t);
|
|
919
|
+
}
|
|
920
|
+
};
|
|
921
|
+
collect(resolvedReturn);
|
|
922
|
+
// Deduplicate for diagnostic message
|
|
923
|
+
const seen = new Set();
|
|
924
|
+
const uniqueMembers = [];
|
|
925
|
+
for (const m of flatMembers) {
|
|
926
|
+
const s = (0, types_1.typeToString)(m);
|
|
927
|
+
if (!seen.has(s)) {
|
|
928
|
+
seen.add(s);
|
|
929
|
+
uniqueMembers.push(m);
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
// When inside an annotated method, report on the method name
|
|
933
|
+
// rather than on an inner expression deep in the body.
|
|
934
|
+
const anchor = engine.annotationMethodNode ?? reportNode;
|
|
935
|
+
for (const member of uniqueMembers) {
|
|
936
|
+
try {
|
|
937
|
+
(0, unify_1.unify)(member, resolvedExpected);
|
|
938
|
+
}
|
|
939
|
+
catch (e) {
|
|
940
|
+
if (e instanceof unify_1.UnificationError) {
|
|
941
|
+
// Build an inferred function type that matches the annotation's
|
|
942
|
+
// shape so the unified mismatch message shows full types when
|
|
943
|
+
// possible (falling back to bare return types otherwise).
|
|
944
|
+
const name = (0, annotations_1.bindingNameFromNode)(anchor);
|
|
945
|
+
const ann = name
|
|
946
|
+
? engine.lookupAnnotation(name, anchor.start ?? 0)
|
|
947
|
+
: undefined;
|
|
948
|
+
const expectedFull = ann?.scheme ? (0, env_1.instantiate)(ann.scheme) : resolvedExpected;
|
|
949
|
+
const inferredReturn = uniqueMembers.length === 1
|
|
950
|
+
? uniqueMembers[0]
|
|
951
|
+
: (0, types_1.tUnion)(uniqueMembers);
|
|
952
|
+
const inferredFull = expectedFull.tag === 'TFun'
|
|
953
|
+
? (0, types_1.tFun)(expectedFull.param, inferredReturn)
|
|
954
|
+
: inferredReturn;
|
|
955
|
+
if ((0, types_1.containsErrorType)(inferredFull) || (0, types_1.containsErrorType)(expectedFull)) {
|
|
956
|
+
break;
|
|
957
|
+
}
|
|
958
|
+
engine.addDiag((0, annotations_1.annotationMismatchMessage)(name, inferredFull, expectedFull), (0, annotations_1.narrowToIdentifier)(anchor));
|
|
959
|
+
break;
|
|
960
|
+
}
|
|
961
|
+
else {
|
|
962
|
+
throw e;
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
/** `obj.field == null` / `=== undefined` (a positive null check on a
|
|
969
|
+
* member of an identifier). */
|
|
970
|
+
function isMemberNullCheck(test) {
|
|
971
|
+
const b = test;
|
|
972
|
+
if (!['==', '==='].includes(b.operator))
|
|
973
|
+
return false;
|
|
974
|
+
const isNullish = (n) => (n.type === 'Literal' && n.value === null)
|
|
975
|
+
|| (n.type === 'Identifier' && n.name === 'undefined');
|
|
976
|
+
const isMember = (n) => n.type === 'MemberExpression'
|
|
977
|
+
&& !n.computed
|
|
978
|
+
&& n.object.type === 'Identifier';
|
|
979
|
+
return (isMember(b.left) && isNullish(b.right))
|
|
980
|
+
|| (isMember(b.right) && isNullish(b.left));
|
|
981
|
+
}
|
|
982
|
+
/** The value of an unconditional `name = value` at the top level of a
|
|
983
|
+
* branch (`x = make ();` or `{ …; x = make (); }`), or null. */
|
|
984
|
+
function assignedValueIn(branch, name) {
|
|
985
|
+
const statements = branch.type === 'BlockStatement'
|
|
986
|
+
? branch.body
|
|
987
|
+
: [branch];
|
|
988
|
+
for (const st of statements) {
|
|
989
|
+
if (st.type !== 'ExpressionStatement')
|
|
990
|
+
continue;
|
|
991
|
+
const e = st.expression;
|
|
992
|
+
if (e.type !== 'AssignmentExpression')
|
|
993
|
+
continue;
|
|
994
|
+
const a = e;
|
|
995
|
+
if (a.operator === '=' && a.left.type === 'Identifier' && a.left.name === name) {
|
|
996
|
+
return a.right;
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
return null;
|
|
1000
|
+
}
|
|
1001
|
+
function inferBlockReturnType(engine, block, env, expectedReturnType) {
|
|
1002
|
+
let currentEnv = (0, statements_1.hoistFunctionDeclarations)(engine, block.body, env);
|
|
1003
|
+
let returnType = null;
|
|
1004
|
+
for (const stmt of block.body) {
|
|
1005
|
+
if (stmt.type === 'ReturnStatement') {
|
|
1006
|
+
if (stmt.argument) {
|
|
1007
|
+
returnType = (0, expressions_1.inferExpressionWithExpected)(engine, stmt.argument, currentEnv, expectedReturnType);
|
|
1008
|
+
// Record it, like a nested return (statements.ts): the return
|
|
1009
|
+
// collection below must not guess it from source offsets, where
|
|
1010
|
+
// `a === 3` ends with its operand `3` and would read as Number.
|
|
1011
|
+
engine.returnTypeOverrides.set(stmt, returnType);
|
|
1012
|
+
}
|
|
1013
|
+
break;
|
|
1014
|
+
}
|
|
1015
|
+
// `if (!m.has (k)) m.set (k, …);` / `if (!m.has (k)) return …;`: after
|
|
1016
|
+
// it `m.get (k)` cannot miss (see `keyPresentAfter`).
|
|
1017
|
+
{
|
|
1018
|
+
const present = (0, narrowing_1.keyPresentAfter)(stmt);
|
|
1019
|
+
if (present) {
|
|
1020
|
+
const [newEnv] = engine.inferStatement(stmt, currentEnv);
|
|
1021
|
+
currentEnv = newEnv.extend(present, (0, types_1.mono)(types_1.tBool));
|
|
1022
|
+
continue;
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
// Loop exit: after `while (test) { … }` the test is false, unless the
|
|
1026
|
+
// body can `break` out early — continue with the false-branch narrowing
|
|
1027
|
+
// (`while (isNext (acc)) { … } return acc.value;` reads a `Done`).
|
|
1028
|
+
if (stmt.type === 'WhileStatement' && !containsBreak(stmt.body)) {
|
|
1029
|
+
const [newEnv] = engine.inferStatement(stmt, currentEnv);
|
|
1030
|
+
currentEnv = (0, narrowing_1.computeNarrowedEnvs)(engine.subst, stmt.test, newEnv, engine.annotationMap).altEnv;
|
|
1031
|
+
continue;
|
|
1032
|
+
}
|
|
1033
|
+
// Guard with an assignment: `if (x == null) x = make ();` (or `!x`) —
|
|
1034
|
+
// after it `x` holds either its old non-null value or the new one, so
|
|
1035
|
+
// it is not null when the assigned value cannot be. Only an
|
|
1036
|
+
// unconditional `x = …` at the top level of the branch counts.
|
|
1037
|
+
if (stmt.type === 'IfStatement' && !stmt.alternate && !(0, narrowing_1.blockAlwaysReturns)(stmt.consequent)) {
|
|
1038
|
+
// The guarded variable: `x == null`, `!x`, or one of those as a
|
|
1039
|
+
// disjunct of `A || x == null` (the branch runs whenever x is null).
|
|
1040
|
+
const guardedBy = (test) => {
|
|
1041
|
+
const nullCheck = (0, narrowing_1.extractNullCheck)(test);
|
|
1042
|
+
if (nullCheck && nullCheck.isNullCheckPositive)
|
|
1043
|
+
return nullCheck.varName;
|
|
1044
|
+
if (isNegatedReference(test))
|
|
1045
|
+
return test.argument.name;
|
|
1046
|
+
if (test.type === 'LogicalExpression' && test.operator === '||') {
|
|
1047
|
+
const l = test;
|
|
1048
|
+
return guardedBy(l.right) ?? guardedBy(l.left);
|
|
1049
|
+
}
|
|
1050
|
+
return null;
|
|
1051
|
+
};
|
|
1052
|
+
const guarded = guardedBy(stmt.test);
|
|
1053
|
+
const assigned = guarded ? assignedValueIn(stmt.consequent, guarded) : null;
|
|
1054
|
+
if (guarded && assigned) {
|
|
1055
|
+
const [newEnv] = engine.inferStatement(stmt, currentEnv);
|
|
1056
|
+
currentEnv = newEnv;
|
|
1057
|
+
const valueType = engine.getNodeType(assigned);
|
|
1058
|
+
const varScheme = currentEnv.lookup(guarded);
|
|
1059
|
+
if (valueType && varScheme) {
|
|
1060
|
+
const value = engine.subst.apply(valueType);
|
|
1061
|
+
if ((0, typeUtils_1.structuralEquals)((0, narrowing_1.removeNullUndefined)(value), value)) {
|
|
1062
|
+
currentEnv = currentEnv.extend(guarded, (0, types_1.mono)((0, narrowing_1.removeNullUndefined)(engine.subst.apply(varScheme.type))));
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
continue;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
// Guard clause on a member: `if (input.localTime == null) return …;` —
|
|
1069
|
+
// after it the member is not null (the else-side narrowing of the test,
|
|
1070
|
+
// as in a ternary).
|
|
1071
|
+
if (stmt.type === 'IfStatement' && !stmt.alternate && (0, narrowing_1.blockAlwaysReturns)(stmt.consequent)
|
|
1072
|
+
&& stmt.test.type === 'BinaryExpression' && isMemberNullCheck(stmt.test)) {
|
|
1073
|
+
const [newEnv] = engine.inferStatement(stmt, currentEnv);
|
|
1074
|
+
currentEnv = (0, narrowing_1.computeNarrowedEnvs)(engine.subst, stmt.test, newEnv, engine.annotationMap).altEnv;
|
|
1075
|
+
continue;
|
|
1076
|
+
}
|
|
1077
|
+
// Guard clause narrowing: if (x == null) return ...; → narrow x after
|
|
1078
|
+
if (stmt.type === 'IfStatement' && !stmt.alternate && (0, narrowing_1.blockAlwaysReturns)(stmt.consequent)) {
|
|
1079
|
+
const narrowing = (0, narrowing_1.extractNullCheck)(stmt.test);
|
|
1080
|
+
if (narrowing) {
|
|
1081
|
+
// The if body returns, so code after this point has the opposite narrowing
|
|
1082
|
+
const [newEnv] = engine.inferStatement(stmt, currentEnv);
|
|
1083
|
+
currentEnv = newEnv;
|
|
1084
|
+
const varScheme = currentEnv.lookup(narrowing.varName);
|
|
1085
|
+
if (varScheme) {
|
|
1086
|
+
const resolvedType = engine.subst.apply(varScheme.type);
|
|
1087
|
+
const narrowed = (0, narrowing_1.removeNullUndefined)(resolvedType);
|
|
1088
|
+
if (narrowing.isNullCheckPositive) {
|
|
1089
|
+
// Guard was "if (x == null) return" → after guard, x is NOT null
|
|
1090
|
+
currentEnv = currentEnv.extend(narrowing.varName, (0, types_1.mono)(narrowed));
|
|
1091
|
+
}
|
|
1092
|
+
// For "if (x != null) return" → after guard, x IS null (uncommon, don't narrow)
|
|
1093
|
+
}
|
|
1094
|
+
continue;
|
|
1095
|
+
}
|
|
1096
|
+
// Guard clause with type predicate: if (isString(x)) return ...; → narrow x after
|
|
1097
|
+
const predicateNarrowing = (0, narrowing_1.extractTypePredicateNarrowing)(engine.subst, stmt.test, currentEnv);
|
|
1098
|
+
if (predicateNarrowing) {
|
|
1099
|
+
const [newEnv] = engine.inferStatement(stmt, currentEnv);
|
|
1100
|
+
// The guard returned when the predicate was true, so after it the
|
|
1101
|
+
// predicate is false: the false-branch narrowing (union remainder,
|
|
1102
|
+
// or the other variant of a sumtype for a `::narrow <Variant>` guard).
|
|
1103
|
+
currentEnv = (0, narrowing_1.computeNarrowedEnvs)(engine.subst, stmt.test, newEnv, engine.annotationMap).altEnv;
|
|
1104
|
+
continue;
|
|
1105
|
+
}
|
|
1106
|
+
// Guard clause on falsiness: if (!x) return ...; → after it `x` is
|
|
1107
|
+
// truthy, so not Null/Undefined (`if (!evidence) return "–";`).
|
|
1108
|
+
// computeNarrowedEnvs already narrows the else-side of `!x`.
|
|
1109
|
+
if (isNegatedReference(stmt.test)) {
|
|
1110
|
+
const [newEnv] = engine.inferStatement(stmt, currentEnv);
|
|
1111
|
+
currentEnv = (0, narrowing_1.computeNarrowedEnvs)(engine.subst, stmt.test, newEnv, engine.annotationMap).altEnv;
|
|
1112
|
+
continue;
|
|
1113
|
+
}
|
|
1114
|
+
// Guard clause with typeof: if (typeof x === "string") return ...; → narrow x after
|
|
1115
|
+
const typeofNarrowing = (0, narrowing_1.extractTypeofCheck)(stmt.test);
|
|
1116
|
+
if (typeofNarrowing) {
|
|
1117
|
+
const [newEnv] = engine.inferStatement(stmt, currentEnv);
|
|
1118
|
+
currentEnv = newEnv;
|
|
1119
|
+
const varScheme = currentEnv.lookup(typeofNarrowing.varName);
|
|
1120
|
+
if (varScheme) {
|
|
1121
|
+
const resolvedType = engine.subst.apply(varScheme.type);
|
|
1122
|
+
if (typeofNarrowing.isPositive) {
|
|
1123
|
+
// Guard was "if (typeof x === 'string') return ..." → after guard, x is NOT string
|
|
1124
|
+
const remainder = (0, narrowing_1.filterUnion)(resolvedType, (t) => !(0, narrowing_1.typeofCategoryMatches)(t, typeofNarrowing.narrowedType));
|
|
1125
|
+
if (!(0, typeUtils_1.structuralEquals)(remainder, resolvedType)) {
|
|
1126
|
+
currentEnv = currentEnv.extend(typeofNarrowing.varName, (0, types_1.mono)(remainder));
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
// For "if (typeof x !== 'string') return" → after guard, x IS string
|
|
1130
|
+
else {
|
|
1131
|
+
currentEnv = currentEnv.extend(typeofNarrowing.varName, (0, types_1.mono)(typeofNarrowing.narrowedType));
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
// Guard clause with ::narrow member expression or method call:
|
|
1137
|
+
// if (f.isLeft) return ...; or if (f.isLeft()) return ...;
|
|
1138
|
+
// → narrow f after the guard
|
|
1139
|
+
if ((stmt.test.type === 'MemberExpression'
|
|
1140
|
+
&& stmt.test.object.type === 'Identifier'
|
|
1141
|
+
&& stmt.test.property.type === 'Identifier')
|
|
1142
|
+
|| (stmt.test.type === 'CallExpression'
|
|
1143
|
+
&& stmt.test.callee?.type === 'MemberExpression'
|
|
1144
|
+
&& stmt.test.callee.object?.type === 'Identifier'
|
|
1145
|
+
&& stmt.test.callee.property?.type === 'Identifier')) {
|
|
1146
|
+
const { altEnv } = (0, narrowing_1.computeNarrowedEnvs)(engine.subst, stmt.test, currentEnv, engine.annotationMap);
|
|
1147
|
+
if (altEnv !== currentEnv) {
|
|
1148
|
+
const [newEnv] = engine.inferStatement(stmt, currentEnv);
|
|
1149
|
+
currentEnv = newEnv;
|
|
1150
|
+
// Apply the altEnv bindings (the guard returned when predicate was true,
|
|
1151
|
+
// so after the guard the opposite variant applies)
|
|
1152
|
+
currentEnv = altEnv;
|
|
1153
|
+
continue;
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
// Guard clause with a compound test: `if (A || B) return …;` — after
|
|
1157
|
+
// the guard both A and B are false (`computeNarrowedEnvs` step 3a), so
|
|
1158
|
+
// `if (names.length < 2 || link == null) return;` leaves `link` non-null.
|
|
1159
|
+
if (stmt.test.type === 'LogicalExpression' && stmt.test.operator === '||') {
|
|
1160
|
+
const [newEnv] = engine.inferStatement(stmt, currentEnv);
|
|
1161
|
+
currentEnv = (0, narrowing_1.computeNarrowedEnvs)(engine.subst, stmt.test, newEnv, engine.annotationMap).altEnv;
|
|
1162
|
+
continue;
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
const [newEnv] = engine.inferStatement(stmt, currentEnv);
|
|
1166
|
+
currentEnv = newEnv;
|
|
1167
|
+
}
|
|
1168
|
+
// Collect ALL return types from nested branches and merge with the
|
|
1169
|
+
// top-level return type (if any). This handles patterns like:
|
|
1170
|
+
// if (cond) { return "a" }
|
|
1171
|
+
// return 1
|
|
1172
|
+
// → the function return type should be String | Number.
|
|
1173
|
+
// Nested returns (inside `if` / loops / `switch`) are inferred WITHOUT the
|
|
1174
|
+
// expected return type — only the final top-level `return` gets it. Merging
|
|
1175
|
+
// them into a union afterwards is unsound against an annotation: `[Number]`
|
|
1176
|
+
// and `[a]` merge to `[Number | a]`, whose element "matches" `a`. Check each
|
|
1177
|
+
// nested return against the annotated return type as well, exactly like the
|
|
1178
|
+
// branches of a ternary (which unify): a rigid variable then reports the
|
|
1179
|
+
// mismatch, and a flexible one is pinned so the binding's final check sees it.
|
|
1180
|
+
if (expectedReturnType && engine.subst.apply(expectedReturnType).tag !== 'TVar') {
|
|
1181
|
+
for (const { node: retNode, type: rt } of collectNestedReturns(engine, block)) {
|
|
1182
|
+
// A narrower union (`loading ? <Spinner /> : null`) fits a wider
|
|
1183
|
+
// declared union result.
|
|
1184
|
+
const widened = (0, unify_1.unifyWidening)(engine.subst.apply(rt), engine.subst.apply(expectedReturnType));
|
|
1185
|
+
if (widened)
|
|
1186
|
+
engine.subst.mergeFrom(widened);
|
|
1187
|
+
else
|
|
1188
|
+
engine.unifyWithDiagnostic(rt, expectedReturnType, retNode);
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
const allReturnTypes = collectAllReturnTypes(engine, block);
|
|
1192
|
+
if (allReturnTypes.length > 0) {
|
|
1193
|
+
if (returnType === null) {
|
|
1194
|
+
returnType = allReturnTypes[0];
|
|
1195
|
+
}
|
|
1196
|
+
// Merge all return types: resolve and deduplicate
|
|
1197
|
+
const resolvedTypes = [];
|
|
1198
|
+
const seen = new Set();
|
|
1199
|
+
for (const rt of allReturnTypes) {
|
|
1200
|
+
const resolved = engine.subst.apply(rt);
|
|
1201
|
+
const key = (0, types_1.typeToString)(resolved);
|
|
1202
|
+
if (!seen.has(key)) {
|
|
1203
|
+
seen.add(key);
|
|
1204
|
+
resolvedTypes.push(resolved);
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
// Only override returnType when there are multiple distinct types
|
|
1208
|
+
if (resolvedTypes.length > 1) {
|
|
1209
|
+
returnType = (0, types_1.mergeReturnTypes)(resolvedTypes);
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
// Constructor function detection: if the block has `this.x = ...`
|
|
1213
|
+
// assignments and no (or only guard) return, the function implicitly
|
|
1214
|
+
// returns `this`. Use the bound `this` type from the environment.
|
|
1215
|
+
if (returnType === null && (0, narrowing_1.blockHasThisAssignment)(block)) {
|
|
1216
|
+
const thisScheme = env.lookup('this');
|
|
1217
|
+
if (thisScheme) {
|
|
1218
|
+
returnType = (0, env_1.instantiate)(thisScheme);
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1221
|
+
if (returnType === null) {
|
|
1222
|
+
// A body that can only exit by throwing never produces a value, so its
|
|
1223
|
+
// return type is unconstrained (bottom) — a fresh var lets a throw-only
|
|
1224
|
+
// thunk like `() => { throw "boom"; }` satisfy any `() -> a` slot
|
|
1225
|
+
// (FP-library: `RTask.try (() => { throw "boom"; })`).
|
|
1226
|
+
returnType = blockAlwaysThrows(block) ? (0, types_1.tVar)() : types_1.tVoid;
|
|
1227
|
+
}
|
|
1228
|
+
// Check: if the resolved return type is a union but the expected return
|
|
1229
|
+
// type is a concrete (non-union, non-TVar) type, verify that ALL members
|
|
1230
|
+
// of the union match the expected type. The normal unifier is too lenient
|
|
1231
|
+
// here — it allows Union(Number, Null) to match Number because Number is
|
|
1232
|
+
// a member. But returning a Union where a concrete type is expected is a
|
|
1233
|
+
// real type error (the value could be any member of the union).
|
|
1234
|
+
if (expectedReturnType) {
|
|
1235
|
+
checkUnionVsExpected(engine, returnType, expectedReturnType, block);
|
|
1236
|
+
}
|
|
1237
|
+
return returnType;
|
|
1238
|
+
}
|
|
1239
|
+
/** True when the block's execution unavoidably ends in a `throw` (last
|
|
1240
|
+
* statement is a throw, or an if/else where both branches always throw). */
|
|
1241
|
+
function blockAlwaysThrows(node) {
|
|
1242
|
+
if (node.type === 'ThrowStatement')
|
|
1243
|
+
return true;
|
|
1244
|
+
if (node.type === 'BlockStatement') {
|
|
1245
|
+
const body = node.body ?? [];
|
|
1246
|
+
const last = body[body.length - 1];
|
|
1247
|
+
return !!last && blockAlwaysThrows(last);
|
|
1248
|
+
}
|
|
1249
|
+
if (node.type === 'IfStatement') {
|
|
1250
|
+
return !!node.alternate && blockAlwaysThrows(node.consequent) && blockAlwaysThrows(node.alternate);
|
|
1251
|
+
}
|
|
1252
|
+
return false;
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Collect ALL return-statement types from nested branches.
|
|
1256
|
+
* Uses acorn-walk to traverse blocks, if/else, switch cases, and try/catch
|
|
1257
|
+
* without descending into nested function bodies.
|
|
1258
|
+
*/
|
|
1259
|
+
/** The type recorded for exactly `node` (same start AND end), preferred over
|
|
1260
|
+
* a lookup by end offset alone, which is ambiguous: `(await x) === "PONG"` and its operand
|
|
1261
|
+
* `"PONG"` end at the same position, and the operand's type would be taken
|
|
1262
|
+
* for the whole expression. */
|
|
1263
|
+
function recordedTypeOf(engine, node) {
|
|
1264
|
+
const byEnd = engine.nodeTypesByEnd.get(node.end);
|
|
1265
|
+
if (byEnd && byEnd.start === node.start)
|
|
1266
|
+
return byEnd.type;
|
|
1267
|
+
const byStart = engine.nodeTypes.get(node.start);
|
|
1268
|
+
if (byStart && byStart.end === node.end)
|
|
1269
|
+
return byStart.type;
|
|
1270
|
+
// Not recorded under exactly this node: the end-offset entry is the best
|
|
1271
|
+
// remaining guess (returns inferred through the statement path are
|
|
1272
|
+
// recorded explicitly and never reach this point).
|
|
1273
|
+
return byEnd?.type;
|
|
1274
|
+
}
|
|
1275
|
+
/** Returns with an argument that are NOT direct statements of `block`
|
|
1276
|
+
* (those are inferred against the expected type already), outside nested
|
|
1277
|
+
* functions — with their recorded (or local-kind-lifted) types. */
|
|
1278
|
+
function collectNestedReturns(engine, block) {
|
|
1279
|
+
const out = [];
|
|
1280
|
+
const direct = new Set((block.body ?? []));
|
|
1281
|
+
walk.ancestor(block, {
|
|
1282
|
+
ReturnStatement(ret, _state, ancestors) {
|
|
1283
|
+
if (direct.has(ret) || !ret.argument)
|
|
1284
|
+
return;
|
|
1285
|
+
for (let i = 1; i < ancestors.length - 1; i++) {
|
|
1286
|
+
const t = ancestors[i].type;
|
|
1287
|
+
if (t === 'FunctionDeclaration' || t === 'FunctionExpression' || t === 'ArrowFunctionExpression')
|
|
1288
|
+
return;
|
|
1289
|
+
}
|
|
1290
|
+
const t = engine.returnTypeOverrides.get(ret) ?? recordedTypeOf(engine, ret.argument);
|
|
1291
|
+
if (t)
|
|
1292
|
+
out.push({ node: ret.argument, type: t });
|
|
1293
|
+
},
|
|
1294
|
+
});
|
|
1295
|
+
return out;
|
|
1296
|
+
}
|
|
1297
|
+
function collectAllReturnTypes(engine, node) {
|
|
1298
|
+
if (!node)
|
|
1299
|
+
return [];
|
|
1300
|
+
const types = [];
|
|
1301
|
+
walk.ancestor(node, {
|
|
1302
|
+
ReturnStatement(ret, _state, ancestors) {
|
|
1303
|
+
// Skip returns inside nested function bodies
|
|
1304
|
+
for (let i = 1; i < ancestors.length - 1; i++) {
|
|
1305
|
+
const t = ancestors[i].type;
|
|
1306
|
+
if (t === 'FunctionDeclaration' || t === 'FunctionExpression' || t === 'ArrowFunctionExpression') {
|
|
1307
|
+
return;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
if (ret.argument) {
|
|
1311
|
+
// A return under a local kind equality (`isArray` guard on `f a`)
|
|
1312
|
+
// contributes its re-expressed type (`f x`, not `[x]`).
|
|
1313
|
+
const t = engine.returnTypeOverrides.get(ret) ?? recordedTypeOf(engine, ret.argument);
|
|
1314
|
+
if (t)
|
|
1315
|
+
types.push(t);
|
|
1316
|
+
}
|
|
1317
|
+
else {
|
|
1318
|
+
// Bare return (no argument) — skip if inside a guard clause
|
|
1319
|
+
// (IfStatement without alternate). These are early-exit control
|
|
1320
|
+
// flow and should not introduce () into the function return type.
|
|
1321
|
+
for (let i = ancestors.length - 2; i >= 1; i--) {
|
|
1322
|
+
const a = ancestors[i];
|
|
1323
|
+
if (a.type === 'IfStatement' && !a.alternate) {
|
|
1324
|
+
return;
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
types.push(types_1.tVoid);
|
|
1328
|
+
}
|
|
1329
|
+
},
|
|
1330
|
+
});
|
|
1331
|
+
return types;
|
|
1332
|
+
}
|
|
1333
|
+
/** Conservative: any `break` in a loop body (outside nested functions) may
|
|
1334
|
+
* leave the loop while its test is still true. */
|
|
1335
|
+
function containsBreak(node) {
|
|
1336
|
+
let found = false;
|
|
1337
|
+
const visit = (n) => {
|
|
1338
|
+
if (found || !n || typeof n !== 'object')
|
|
1339
|
+
return;
|
|
1340
|
+
const t = n.type;
|
|
1341
|
+
if (t === 'BreakStatement') {
|
|
1342
|
+
found = true;
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
if (t === 'FunctionExpression' || t === 'ArrowFunctionExpression' || t === 'FunctionDeclaration')
|
|
1346
|
+
return;
|
|
1347
|
+
for (const [k, v] of Object.entries(n)) {
|
|
1348
|
+
if (k === 'loc' || k === 'range')
|
|
1349
|
+
continue;
|
|
1350
|
+
if (Array.isArray(v))
|
|
1351
|
+
v.forEach(visit);
|
|
1352
|
+
else if (v && typeof v === 'object')
|
|
1353
|
+
visit(v);
|
|
1354
|
+
}
|
|
1355
|
+
};
|
|
1356
|
+
visit(node);
|
|
1357
|
+
return found;
|
|
1358
|
+
}
|
|
1359
|
+
//# sourceMappingURL=expr-functions.js.map
|