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,1468 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ============================================================================
|
|
3
|
+
// Call-expression inference — extracted from InferenceEngine
|
|
4
|
+
//
|
|
5
|
+
// Plain language: this file answers "what does `f(a, b)` produce?" — the
|
|
6
|
+
// hardest question in the engine, because JavaScript call styles vary so
|
|
7
|
+
// much. The general recipe: infer the type of `f`, infer each argument,
|
|
8
|
+
// unify the arguments against `f`'s parameters, and read off the result
|
|
9
|
+
// type. Around that core live many specialised paths: curried calls
|
|
10
|
+
// (`f(a)(b)`), variadic functions, overloaded signatures (call-overloads.ts),
|
|
11
|
+
// method calls on containers, `new` constructor calls, and library-style
|
|
12
|
+
// record projections (call-rows.ts).
|
|
13
|
+
// ============================================================================
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.inferCallExpression = inferCallExpression;
|
|
16
|
+
exports.inferRankNArgument = inferRankNArgument;
|
|
17
|
+
const types_1 = require("../hm/types");
|
|
18
|
+
const types_2 = require("../hm/types");
|
|
19
|
+
const methodRegistry_1 = require("../registries/methodRegistry");
|
|
20
|
+
const env_1 = require("../hm/env");
|
|
21
|
+
const unify_1 = require("../hm/unify");
|
|
22
|
+
const typeUtils_1 = require("../hm/typeUtils");
|
|
23
|
+
const narrowing_1 = require("./narrowing");
|
|
24
|
+
const helpers_1 = require("./helpers");
|
|
25
|
+
const annotations_1 = require("./annotations");
|
|
26
|
+
const functionPatterns_1 = require("./functionPatterns");
|
|
27
|
+
const methodRegistry_2 = require("../registries/methodRegistry");
|
|
28
|
+
const constraintRegistry_1 = require("../registries/constraintRegistry");
|
|
29
|
+
const parsing_1 = require("../parsing");
|
|
30
|
+
const call_rows_1 = require("./call-rows");
|
|
31
|
+
const call_overloads_1 = require("./call-overloads");
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
// Numeric literal refinement helpers
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
/** Extract a numeric literal value from an AST node, handling unary minus and NaN/Infinity. */
|
|
36
|
+
function getNumericLiteralValue(node) {
|
|
37
|
+
if (node.type === 'Literal' && typeof node.value === 'number') {
|
|
38
|
+
return node.value;
|
|
39
|
+
}
|
|
40
|
+
if (node.type === 'UnaryExpression') {
|
|
41
|
+
const unary = node;
|
|
42
|
+
if (unary.operator === '-' &&
|
|
43
|
+
unary.argument.type === 'Literal' &&
|
|
44
|
+
typeof unary.argument.value === 'number') {
|
|
45
|
+
return -unary.argument.value;
|
|
46
|
+
}
|
|
47
|
+
if (unary.operator === '-' && unary.argument.type === 'Identifier') {
|
|
48
|
+
const name = unary.argument.name;
|
|
49
|
+
if (name === 'Infinity')
|
|
50
|
+
return -Infinity;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (node.type === 'Identifier') {
|
|
54
|
+
const name = node.name;
|
|
55
|
+
if (name === 'NaN')
|
|
56
|
+
return NaN;
|
|
57
|
+
if (name === 'Infinity')
|
|
58
|
+
return Infinity;
|
|
59
|
+
}
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
/** Validate a numeric literal against a refined numeric type annotation.
|
|
63
|
+
* Returns an error message if the literal violates the refinement, or null. */
|
|
64
|
+
function checkNumericRefinement(typeName, value) {
|
|
65
|
+
const checks = NUMERIC_REFINEMENT_CHECKS[typeName];
|
|
66
|
+
if (!checks)
|
|
67
|
+
return null; // Float/Double/Number/etc. — any number is fine
|
|
68
|
+
for (const [predicate, fail] of checks) {
|
|
69
|
+
if (!predicate(value))
|
|
70
|
+
return `'${value}' ${fail}`;
|
|
71
|
+
}
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
const isInt = [Number.isInteger, 'is not an integer'];
|
|
75
|
+
const isFinite = [Number.isFinite, 'is not finite'];
|
|
76
|
+
const notNaN = [(n) => !Number.isNaN(n), 'is NaN'];
|
|
77
|
+
const positive = [(n) => n > 0, 'is not positive'];
|
|
78
|
+
const negative = [(n) => n < 0, 'is not negative'];
|
|
79
|
+
const nonNegative = [(n) => n >= 0, 'is negative'];
|
|
80
|
+
const nonZero = [(n) => n !== 0, 'must not be zero'];
|
|
81
|
+
const NUMERIC_REFINEMENT_CHECKS = {
|
|
82
|
+
Integer: [isInt],
|
|
83
|
+
NonNegativeInteger: [isInt, nonNegative],
|
|
84
|
+
NegativeInteger: [isInt, negative],
|
|
85
|
+
PositiveInteger: [isInt, positive],
|
|
86
|
+
NonZeroInteger: [isInt, nonZero],
|
|
87
|
+
PositiveNumber: [positive],
|
|
88
|
+
NegativeNumber: [negative],
|
|
89
|
+
ValidNumber: [notNaN],
|
|
90
|
+
NonZeroValidNumber: [notNaN, nonZero],
|
|
91
|
+
FiniteNumber: [isFinite],
|
|
92
|
+
NonZeroFiniteNumber: [isFinite, nonZero],
|
|
93
|
+
PositiveFiniteNumber: [isFinite, positive],
|
|
94
|
+
NegativeFiniteNumber: [isFinite, negative],
|
|
95
|
+
};
|
|
96
|
+
/**
|
|
97
|
+
* Whether a tuple parameter slot accepts an implicit `Undefined` argument.
|
|
98
|
+
*
|
|
99
|
+
* Used by {@link checkAndPadArity} to relax the strict tuple arity check
|
|
100
|
+
* when the trailing parameters are typed as a constraint variable whose
|
|
101
|
+
* structural body explicitly admits `Undefined` (e.g.
|
|
102
|
+
* `::constraint Source s { s :: String | SQLTag a b | Undefined }`).
|
|
103
|
+
*
|
|
104
|
+
* Returns `true` when:
|
|
105
|
+
* - the slot resolves to `Undefined` directly, OR
|
|
106
|
+
* - the slot resolves to a `Union` containing `Undefined`, OR
|
|
107
|
+
* - the slot resolves to a `TVar` whose registered constraint(s) define
|
|
108
|
+
* a self-clause (`s :: …`) with a `Union` body containing `Undefined`.
|
|
109
|
+
*/
|
|
110
|
+
function tupleSlotAcceptsUndefined(engine, slot) {
|
|
111
|
+
const resolved = engine.subst.apply(slot);
|
|
112
|
+
if ((0, narrowing_1.typeAcceptsUndefined)(engine.subst, resolved))
|
|
113
|
+
return true;
|
|
114
|
+
if (resolved.tag !== 'TVar')
|
|
115
|
+
return false;
|
|
116
|
+
// Structural constraints (`::constraint Source s { s :: String | Undefined }`)
|
|
117
|
+
// are tracked as pendingUnionConstraints — each entry lists the union
|
|
118
|
+
// alternatives the use-site var must satisfy. When ANY pending union
|
|
119
|
+
// constraint on this var lists Undefined as an alternative, the slot is
|
|
120
|
+
// optional.
|
|
121
|
+
for (const pu of engine.pendingUnionConstraints) {
|
|
122
|
+
if (pu.varId !== resolved.id)
|
|
123
|
+
continue;
|
|
124
|
+
if (pu.alternatives.some(a => {
|
|
125
|
+
const r = engine.subst.apply(a);
|
|
126
|
+
return r.tag === 'TCon' && r.name === 'Undefined';
|
|
127
|
+
})) {
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
// Nominal constraints stored as kvConstraints (e.g. `Functor f`) — keep
|
|
132
|
+
// a fallback lookup via the constraint registry's selfClauses for
|
|
133
|
+
// forward-compatibility with future structural variants registered there.
|
|
134
|
+
const cs = engine.kvConstraints.get(resolved.id);
|
|
135
|
+
if (!cs || cs.length === 0)
|
|
136
|
+
return false;
|
|
137
|
+
for (const cname of cs) {
|
|
138
|
+
const def = (0, constraintRegistry_1.lookupConstraint)(cname);
|
|
139
|
+
if (!def?.selfClauses)
|
|
140
|
+
continue;
|
|
141
|
+
for (const clause of def.selfClauses) {
|
|
142
|
+
if (clause.selfParam !== def.typeVar)
|
|
143
|
+
continue;
|
|
144
|
+
if ((0, narrowing_1.typeAcceptsUndefined)(engine.subst, clause.body))
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Resolve the optionalParamSlots metadata for a callee node. Supports
|
|
152
|
+
* plain identifier callees (env scheme lookup) and member-access callees
|
|
153
|
+
* (`Param.Path(...)`) via the object's `fieldSchemes` row.
|
|
154
|
+
*/
|
|
155
|
+
function resolveCalleeOptionalSlots(engine, env, callee) {
|
|
156
|
+
if (callee.type === 'Identifier') {
|
|
157
|
+
const sch = env.lookup(callee.name);
|
|
158
|
+
return sch?.optionalParamSlots;
|
|
159
|
+
}
|
|
160
|
+
if (callee.type === 'MemberExpression' && !callee.computed) {
|
|
161
|
+
const me = callee;
|
|
162
|
+
if (me.object?.type === 'Identifier' && me.property?.type === 'Identifier') {
|
|
163
|
+
const dotted = `${me.object.name}.${me.property.name}`;
|
|
164
|
+
const direct = engine.optionalParamSlotsByDottedName.get(dotted);
|
|
165
|
+
if (direct)
|
|
166
|
+
return direct;
|
|
167
|
+
return memberCalleeScheme(engine, env, callee)?.optionalParamSlots;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return undefined;
|
|
171
|
+
}
|
|
172
|
+
/** The stored scheme of `obj.f` when `obj` is a record that keeps one per
|
|
173
|
+
* field (`fieldSchemes`: a namespace import, `Param.Path = …`). */
|
|
174
|
+
function memberCalleeScheme(engine, env, callee) {
|
|
175
|
+
if (callee.type !== 'MemberExpression')
|
|
176
|
+
return undefined;
|
|
177
|
+
const me = callee;
|
|
178
|
+
if (me.computed || me.object?.type !== 'Identifier' || me.property?.type !== 'Identifier')
|
|
179
|
+
return undefined;
|
|
180
|
+
const objScheme = env.lookup(me.object.name);
|
|
181
|
+
if (!objScheme)
|
|
182
|
+
return undefined;
|
|
183
|
+
const objType = engine.subst.apply(objScheme.type);
|
|
184
|
+
if (objType.tag !== 'TRecord' || !objType.fieldSchemes)
|
|
185
|
+
return undefined;
|
|
186
|
+
const name = me.property.name;
|
|
187
|
+
return Object.prototype.hasOwnProperty.call(objType.fieldSchemes, name) ? objType.fieldSchemes[name] : undefined;
|
|
188
|
+
}
|
|
189
|
+
/**
|
|
190
|
+
* For tuple-parameter functions, emit a clear arity diagnostic and pad
|
|
191
|
+
* `numArgs` up to the expected count so unification still decomposes the
|
|
192
|
+
* callee. Returns `{ numArgs, arityMismatch }`.
|
|
193
|
+
*
|
|
194
|
+
* Constraint-aware relaxation: when fewer arguments than expected are
|
|
195
|
+
* provided, but every missing trailing slot is "undefined-friendly" via
|
|
196
|
+
* {@link tupleSlotAcceptsUndefined}, the diagnostic is suppressed and
|
|
197
|
+
* `arityMismatch` is reported as `false` so the caller's normal
|
|
198
|
+
* "pad with Undefined" path fills in the gaps.
|
|
199
|
+
*/
|
|
200
|
+
function checkAndPadArity(engine, resolvedCallee, numArgs, calleeNode, optionalParamSlots, hasSpreadArg = false) {
|
|
201
|
+
if (resolvedCallee.tag !== 'TFun' || resolvedCallee.param.tag !== 'TCon'
|
|
202
|
+
|| resolvedCallee.param.name !== types_1.T_TUPLE || numArgs === 0
|
|
203
|
+
|| numArgs === resolvedCallee.param.args.length
|
|
204
|
+
|| resolvedCallee.param.args.some(a => (0, types_1.isSpread)(a))) {
|
|
205
|
+
return { numArgs, arityMismatch: false };
|
|
206
|
+
}
|
|
207
|
+
const expected = resolvedCallee.param.args.length;
|
|
208
|
+
// A spread argument (`fn (a, ...rest)`) supplies an unknown number of
|
|
209
|
+
// values at runtime, so it may fill every remaining parameter — e.g. the
|
|
210
|
+
// surplus-argument pass-through in an FP library's `curry`. Never report "too few
|
|
211
|
+
// arguments" for such a call; pad so the missing slots stay unconstrained.
|
|
212
|
+
if (hasSpreadArg && numArgs < expected) {
|
|
213
|
+
return { numArgs: expected, arityMismatch: false };
|
|
214
|
+
}
|
|
215
|
+
// Constraint-aware optional trailing slots: if every missing trailing
|
|
216
|
+
// parameter accepts Undefined (via its constraint body), accept the
|
|
217
|
+
// shorter call without diagnostic and let the caller pad with Undefined.
|
|
218
|
+
if (numArgs < expected) {
|
|
219
|
+
const trailing = resolvedCallee.param.args.slice(numArgs);
|
|
220
|
+
if (trailing.every(s => tupleSlotAcceptsUndefined(engine, s))) {
|
|
221
|
+
return { numArgs: expected, arityMismatch: false };
|
|
222
|
+
}
|
|
223
|
+
// JS-body-default optional slots: if every missing trailing slot index
|
|
224
|
+
// is registered as optional via the callee's binding (i.e. the
|
|
225
|
+
// implementation declares `(…, x = …)`), accept the shorter call.
|
|
226
|
+
if (optionalParamSlots && optionalParamSlots.length > 0) {
|
|
227
|
+
const missingIndices = [];
|
|
228
|
+
for (let i = numArgs; i < expected; i++)
|
|
229
|
+
missingIndices.push(i);
|
|
230
|
+
if (missingIndices.every(i => optionalParamSlots.includes(i))) {
|
|
231
|
+
return { numArgs: expected, arityMismatch: false };
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
engine.addDiag(`Expected ${expected} argument${expected === 1 ? '' : 's'} but got ${numArgs}`, calleeNode);
|
|
236
|
+
return {
|
|
237
|
+
numArgs: numArgs < expected ? expected : numArgs,
|
|
238
|
+
arityMismatch: true,
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* After unification has resolved the callee type, detect attempts to call a
|
|
243
|
+
* non-function value and emit a "not callable" diagnostic. Two paths:
|
|
244
|
+
* 1. Zero-arg call where unification trivially succeeded against a TVar.
|
|
245
|
+
* 2. Failing unification: rewrite the "Cannot unify" message.
|
|
246
|
+
*/
|
|
247
|
+
function reportNonCallableCallee(engine, node, env, calleeType, numArgs, diagsBefore, prettyBefore) {
|
|
248
|
+
const resolved = engine.subst.apply(calleeType);
|
|
249
|
+
// Both paths short-circuit when the resolved type is callable (TFun) or
|
|
250
|
+
// still a free TVar (no information yet).
|
|
251
|
+
if (isCallableType(resolved))
|
|
252
|
+
return;
|
|
253
|
+
// Prefer the pre-unification pretty-string when supplied: after a failed
|
|
254
|
+
// unification, free TVars in `resolved` may be poisoned to `$error`
|
|
255
|
+
// (see poisonFreeVars), which would leak into the diagnostic. Fallback
|
|
256
|
+
// strips `$error` to `_` for the rare callers that don't pass a snapshot.
|
|
257
|
+
const pretty = prettyBefore ?? (0, types_1.prettyTypeToString)(resolved).replace(/\$error/g, '_');
|
|
258
|
+
// Case 1: zero-arg call where unification didn't error.
|
|
259
|
+
if (numArgs === 0 && engine.diagnostics.length === diagsBefore &&
|
|
260
|
+
node.type !== 'NewExpression') {
|
|
261
|
+
if (node.callee.type !== 'MemberExpression' || isGetterPropertyCall(engine, env, node.callee)) {
|
|
262
|
+
engine.addDiag(`Type '${pretty}' is not callable`, node.callee);
|
|
263
|
+
}
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
// Case 2: rewrite "Cannot unify" emitted by the callee unification.
|
|
267
|
+
if (engine.diagnostics.length > diagsBefore) {
|
|
268
|
+
const lastDiag = engine.diagnostics[engine.diagnostics.length - 1];
|
|
269
|
+
if (lastDiag.message.startsWith('Cannot unify') || lastDiag.message.startsWith('Type mismatch: Cannot unify')) {
|
|
270
|
+
lastDiag.message = `Type '${pretty}' is not callable`;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/** A type is callable if it can stand in for a function: TFun, the opaque
|
|
275
|
+
* `Function` constructor (produced e.g. by `typeof x === "function"`
|
|
276
|
+
* narrowing), an unresolved TVar, or a wildcard/`Any` (both match anything
|
|
277
|
+
* by definition — e.g. a cancel handle from `fork :: (…) -> *`). */
|
|
278
|
+
function isCallableType(t) {
|
|
279
|
+
if (t.tag === 'TFun' || t.tag === 'TVar')
|
|
280
|
+
return true;
|
|
281
|
+
if (t.tag === 'TCon' && t.name === 'Function' && (t.args.length === 0 || t.args.length === 2))
|
|
282
|
+
return true;
|
|
283
|
+
if ((0, types_1.isWildcard)(t) || (0, types_1.isAnyType)(t))
|
|
284
|
+
return true;
|
|
285
|
+
return false;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Detect "calling" what is actually a getter — a member access annotated
|
|
289
|
+
* with a non-function methodType, e.g. `Box#size :: Number`. Treating these
|
|
290
|
+
* as callable yields better diagnostics than silently returning the type.
|
|
291
|
+
*/
|
|
292
|
+
function isGetterPropertyCall(engine, env, callee) {
|
|
293
|
+
if (callee.object?.type !== 'Identifier' || callee.property?.type !== 'Identifier') {
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
const objScheme = env.lookup(callee.object.name);
|
|
297
|
+
if (!objScheme)
|
|
298
|
+
return false;
|
|
299
|
+
const objType = engine.subst.apply(objScheme.type);
|
|
300
|
+
if (objType.tag !== 'TCon')
|
|
301
|
+
return false;
|
|
302
|
+
const ann = engine.annotationMap.get(`${objType.name}#${callee.property.name}`);
|
|
303
|
+
return !!ann && ann.methodType?.tag !== 'TFun';
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Emit a warning when `new` usage doesn't match the callee's constructor
|
|
307
|
+
* provenance:
|
|
308
|
+
* - `new` on an arrow-factory: the runtime returns a fresh `Object`, NOT
|
|
309
|
+
* a "Name" instance — almost certainly a mistake.
|
|
310
|
+
* - missing `new` on a `class` or `function-this` constructor: invoking
|
|
311
|
+
* such a function without `new` either throws (class) or pollutes the
|
|
312
|
+
* global object (function-this).
|
|
313
|
+
*
|
|
314
|
+
* Sum-type variants (`'sumtype-variant'`) are intentionally exempt: it
|
|
315
|
+
* is idiomatic in this codebase to write `Just(5)` without `new`.
|
|
316
|
+
*/
|
|
317
|
+
function checkNewStrictness(engine, node) {
|
|
318
|
+
if (node.callee.type !== 'Identifier')
|
|
319
|
+
return;
|
|
320
|
+
const name = node.callee.name;
|
|
321
|
+
const prov = engine.constructorProvenance.get(name);
|
|
322
|
+
if (!prov || prov === 'sumtype-variant' || prov === 'sumtype')
|
|
323
|
+
return;
|
|
324
|
+
const isNew = node.type === 'NewExpression';
|
|
325
|
+
if (isNew && prov === 'arrow-factory') {
|
|
326
|
+
engine.addDiag(`Cannot use 'new' with arrow-function factory '${name}'; it returns Object, not a new instance`, node.callee);
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
if (!isNew && (prov === 'class' || prov === 'function-this')) {
|
|
330
|
+
engine.addDiag(`Constructor '${name}' must be called with 'new'`, node.callee);
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Look up the built-in constructor kind (`'Array'`, `'Function'`, …) for
|
|
335
|
+
* the callee of a CallExpression. Returns the kind when the callee is a
|
|
336
|
+
* direct `.constructor` member access or an identifier that was bound to
|
|
337
|
+
* such an access.
|
|
338
|
+
*/
|
|
339
|
+
function lookupBuiltinCtorKindForCallee(engine, callee, env) {
|
|
340
|
+
if (callee.type === 'MemberExpression'
|
|
341
|
+
&& !callee.computed
|
|
342
|
+
&& callee.property?.name === 'constructor') {
|
|
343
|
+
const propStart = callee.property.start;
|
|
344
|
+
let k = engine.builtinCtorKind.get(propStart);
|
|
345
|
+
if (k)
|
|
346
|
+
return k;
|
|
347
|
+
// Direct form like `[].constructor(...)` — callee hasn't been inferred
|
|
348
|
+
// yet, so populate the map by inferring it on demand.
|
|
349
|
+
try {
|
|
350
|
+
engine.inferExpression(callee, env);
|
|
351
|
+
}
|
|
352
|
+
catch { /* ignore */ }
|
|
353
|
+
k = engine.builtinCtorKind.get(propStart);
|
|
354
|
+
return k;
|
|
355
|
+
}
|
|
356
|
+
if (callee.type === 'Identifier') {
|
|
357
|
+
const n = callee.name;
|
|
358
|
+
const mapped = engine.builtinCtorByVarName.get(n);
|
|
359
|
+
if (mapped)
|
|
360
|
+
return mapped;
|
|
361
|
+
// Bare global `Function` identifier used as `new Function(...)` /
|
|
362
|
+
// `Function(...)` — enables Phase D smart-infer of the body string.
|
|
363
|
+
if (n === 'Function')
|
|
364
|
+
return n;
|
|
365
|
+
}
|
|
366
|
+
return undefined;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Dedupe a list of types by their pretty-printed form (preserves order).
|
|
370
|
+
*/
|
|
371
|
+
function dedupTypes(types) {
|
|
372
|
+
const seen = new Set();
|
|
373
|
+
const out = [];
|
|
374
|
+
for (const t of types) {
|
|
375
|
+
const k = (0, types_1.prettyTypeToString)(t);
|
|
376
|
+
if (!seen.has(k)) {
|
|
377
|
+
seen.add(k);
|
|
378
|
+
out.push(t);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
return out;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Specialise calls to built-in constructors (currently only `Array`).
|
|
385
|
+
* Returns the specialised result type, or `null` if no specialisation
|
|
386
|
+
* applies. Phase D (smart-infer for `Function`) plugs in here too.
|
|
387
|
+
*/
|
|
388
|
+
function tryInferBuiltinCtorCall(engine, node, env) {
|
|
389
|
+
const kind = lookupBuiltinCtorKindForCallee(engine, node.callee, env);
|
|
390
|
+
if (!kind)
|
|
391
|
+
return null;
|
|
392
|
+
if (kind === 'Array') {
|
|
393
|
+
// Infer the callee for side effects / hover, then synthesise the
|
|
394
|
+
// result as `[union of arg types]` (deduped). Bypasses the spread
|
|
395
|
+
// unification path entirely.
|
|
396
|
+
engine.inferExpression(node.callee, env);
|
|
397
|
+
const argTypes = [];
|
|
398
|
+
for (const arg of node.arguments) {
|
|
399
|
+
if (arg.type === 'SpreadElement')
|
|
400
|
+
return null; // fall through to generic
|
|
401
|
+
const t = engine.subst.apply(engine.inferExpression(arg, env));
|
|
402
|
+
argTypes.push(t);
|
|
403
|
+
}
|
|
404
|
+
if (argTypes.length === 0)
|
|
405
|
+
return (0, types_1.tArray)((0, types_1.tVar)());
|
|
406
|
+
const elems = dedupTypes(argTypes);
|
|
407
|
+
const elem = elems.length === 1 ? elems[0] : (0, types_1.tUnion)(elems);
|
|
408
|
+
const result = (0, types_1.tArray)(elem);
|
|
409
|
+
engine.recordNodeType(node, result);
|
|
410
|
+
return result;
|
|
411
|
+
}
|
|
412
|
+
if (kind === 'Function') {
|
|
413
|
+
const result = tryInferFunctionCtorSmart(engine, node, env);
|
|
414
|
+
if (result)
|
|
415
|
+
return result;
|
|
416
|
+
// Fall through — let generic call inference produce a `Function` result.
|
|
417
|
+
return null;
|
|
418
|
+
}
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Smart-infer `new Function('a', 'b', 'return a + b')`.
|
|
423
|
+
* When every argument is a string literal, the last is treated as the
|
|
424
|
+
* body and the prior strings as parameter names. We synthesise a
|
|
425
|
+
* `function (a, b) { return a + b }` source, parse it, and infer
|
|
426
|
+
* it with an isolated env so call-site bindings don't leak in. Returns
|
|
427
|
+
* the inferred function type, or `null` on any parse/infer failure.
|
|
428
|
+
*/
|
|
429
|
+
function tryInferFunctionCtorSmart(engine, node, env) {
|
|
430
|
+
const args = node.arguments;
|
|
431
|
+
if (args.length === 0)
|
|
432
|
+
return null;
|
|
433
|
+
// All arguments must be string literals.
|
|
434
|
+
const strs = [];
|
|
435
|
+
for (const a of args) {
|
|
436
|
+
if (a.type !== 'Literal')
|
|
437
|
+
return null;
|
|
438
|
+
const v = a.value;
|
|
439
|
+
if (typeof v !== 'string')
|
|
440
|
+
return null;
|
|
441
|
+
strs.push(v);
|
|
442
|
+
}
|
|
443
|
+
const paramNames = strs.slice(0, -1);
|
|
444
|
+
const body = strs[strs.length - 1];
|
|
445
|
+
// Reject param lists that aren't simple identifiers — the parser would also
|
|
446
|
+
// reject, but failing fast keeps error noise out of the diagnostic log.
|
|
447
|
+
if (!paramNames.every(p => /^[A-Za-z_$][\w$]*$/.test(p.trim())))
|
|
448
|
+
return null;
|
|
449
|
+
const synth = `(function(${paramNames.join(',')}) { ${body} })`;
|
|
450
|
+
let parsed;
|
|
451
|
+
try {
|
|
452
|
+
parsed = (0, parsing_1.parseExpression)(synth);
|
|
453
|
+
}
|
|
454
|
+
catch {
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
// Infer with an empty env — Function() bodies don't see outer scope.
|
|
458
|
+
let inferred;
|
|
459
|
+
try {
|
|
460
|
+
inferred = engine.inferExpression(parsed, new env_1.TypeEnv());
|
|
461
|
+
}
|
|
462
|
+
catch {
|
|
463
|
+
return null;
|
|
464
|
+
}
|
|
465
|
+
// Record the callee identifier (`Function`) type as the synthesised
|
|
466
|
+
// function type so hover shows something useful and the "Unbound
|
|
467
|
+
// variable: 'Function'" diagnostic is not produced by a downstream
|
|
468
|
+
// inferExpression call on the callee.
|
|
469
|
+
if (node.callee.type === 'Identifier'
|
|
470
|
+
&& node.callee.name === 'Function') {
|
|
471
|
+
engine.recordNodeType(node.callee, inferred);
|
|
472
|
+
}
|
|
473
|
+
// Infer the literal string arguments for hover / recording — these are
|
|
474
|
+
// safe and don't trigger unbound diagnostics.
|
|
475
|
+
for (const a of args)
|
|
476
|
+
engine.inferExpression(a, env);
|
|
477
|
+
engine.recordNodeType(node, inferred);
|
|
478
|
+
return inferred;
|
|
479
|
+
}
|
|
480
|
+
/** Is a callee's first parameter variadic: a tuple / spread array with a
|
|
481
|
+
* `...` member, or a container (`f (…)`) of one? */
|
|
482
|
+
function firstParamIsVariadic(engine, param) {
|
|
483
|
+
const p = engine.subst.apply(param);
|
|
484
|
+
if (p.tag !== 'TCon')
|
|
485
|
+
return false;
|
|
486
|
+
if ((p.name === types_1.T_TUPLE || p.name === types_1.T_SPREAD_ARRAY) && p.args.some(a => (0, types_1.isSpread)(a)))
|
|
487
|
+
return true;
|
|
488
|
+
if (p.args.length === 1) {
|
|
489
|
+
const inner = engine.subst.apply(p.args[0]);
|
|
490
|
+
return inner.tag === 'TCon' && (inner.name === types_1.T_TUPLE || inner.name === types_1.T_SPREAD_ARRAY)
|
|
491
|
+
&& inner.args.some(a => (0, types_1.isSpread)(a));
|
|
492
|
+
}
|
|
493
|
+
return false;
|
|
494
|
+
}
|
|
495
|
+
/** True when the callee's result (any overload branch) carries a `Picked`
|
|
496
|
+
* marker, i.e. the call's type is only known after the projection. */
|
|
497
|
+
function resultHasPicked(engine, calleeType) {
|
|
498
|
+
const resolved = engine.subst.apply(calleeType);
|
|
499
|
+
const results = [];
|
|
500
|
+
const collect = (t) => {
|
|
501
|
+
if (t.tag === 'TFun')
|
|
502
|
+
results.push(t.result);
|
|
503
|
+
else if (t.tag === 'TCon' && t.name === types_1.T_UNION)
|
|
504
|
+
t.args.forEach(collect);
|
|
505
|
+
};
|
|
506
|
+
collect(resolved);
|
|
507
|
+
return results.some(r => (0, typeUtils_1.someType)(r, n => n.tag === 'TCon' && n.name === types_1.T_PICKED));
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Check a projected result against its annotation. Unification alone is too
|
|
511
|
+
* lenient here (closed records with different fields unify): a projected
|
|
512
|
+
* query is checked EXACTLY — at each position the annotation and the
|
|
513
|
+
* projection must name the same fields (fields the annotation types
|
|
514
|
+
* `X | Undefined` may be absent). `// q :: QueryTag RangeParams Row` then
|
|
515
|
+
* reports a query that reads a parameter `RangeParams` lacks, or a `Row`
|
|
516
|
+
* field the query does not select.
|
|
517
|
+
*/
|
|
518
|
+
function checkProjectedAgainstExpected(engine, actual, expected, node) {
|
|
519
|
+
const before = engine.diagnostics.length;
|
|
520
|
+
engine.unifyWithDiagnostic(actual, expected, node);
|
|
521
|
+
if (engine.diagnostics.length > before)
|
|
522
|
+
return;
|
|
523
|
+
const problems = [];
|
|
524
|
+
const walk = (a, e) => {
|
|
525
|
+
const ra = engine.maybeExpandAlias(engine.subst.apply(a));
|
|
526
|
+
const re = engine.maybeExpandAlias(engine.subst.apply(e));
|
|
527
|
+
if (ra.tag === 'TRecord' && re.tag === 'TRecord') {
|
|
528
|
+
if (ra.rest || re.rest || (ra.labelFields?.length ?? 0) > 0 || (re.labelFields?.length ?? 0) > 0)
|
|
529
|
+
return;
|
|
530
|
+
const extra = Object.keys(ra.fields).filter(k => !(k in re.fields));
|
|
531
|
+
const missing = Object.keys(re.fields).filter(k => !(k in ra.fields) && !typeAcceptsUndefinedLoose(engine, re.fields[k]));
|
|
532
|
+
if (extra.length > 0)
|
|
533
|
+
problems.push(`${extra.map(k => `'${k}'`).join(', ')} not in '${(0, types_1.typeToString)(re)}'`);
|
|
534
|
+
if (missing.length > 0)
|
|
535
|
+
problems.push(`${missing.map(k => `'${k}'`).join(', ')} missing from '${(0, types_1.typeToString)(ra)}'`);
|
|
536
|
+
for (const k of Object.keys(ra.fields))
|
|
537
|
+
if (k in re.fields)
|
|
538
|
+
walk(ra.fields[k], re.fields[k]);
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
if (ra.tag === 'TCon' && re.tag === 'TCon' && ra.name === re.name && ra.args.length === re.args.length) {
|
|
542
|
+
for (let i = 0; i < ra.args.length; i++)
|
|
543
|
+
walk(ra.args[i], re.args[i]);
|
|
544
|
+
}
|
|
545
|
+
};
|
|
546
|
+
walk(actual, expected);
|
|
547
|
+
if (problems.length > 0) {
|
|
548
|
+
engine.addDiag(`Type mismatch: the query does not match its annotation: ${problems.join('; ')}`, node);
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
/** `T | Undefined` (or `Undefined`). */
|
|
552
|
+
function typeAcceptsUndefinedLoose(engine, t) {
|
|
553
|
+
const r = engine.subst.apply(t);
|
|
554
|
+
if (r.tag === 'TCon' && r.name === 'Undefined')
|
|
555
|
+
return true;
|
|
556
|
+
return r.tag === 'TCon' && r.name === types_1.T_UNION && r.args.some(x => x.tag === 'TCon' && x.name === 'Undefined');
|
|
557
|
+
}
|
|
558
|
+
function inferCallExpression(engine, node, env, expectedResultType) {
|
|
559
|
+
// --- `new` strictness: warn on constructor/`new` mismatches ---
|
|
560
|
+
// Skipped for sumtype variants (idiomatic `Just(5)` allowed) and for
|
|
561
|
+
// anything we have no provenance for.
|
|
562
|
+
checkNewStrictness(engine, node);
|
|
563
|
+
// --- Built-in constructor call specialisation ---
|
|
564
|
+
// `Array(...)` / `[].constructor(...)` / `const ac = [].constructor; ac(...)`
|
|
565
|
+
// should widen the element type to a union of the literal arg types.
|
|
566
|
+
{
|
|
567
|
+
const specialised = tryInferBuiltinCtorCall(engine, node, env);
|
|
568
|
+
if (specialised)
|
|
569
|
+
return specialised;
|
|
570
|
+
}
|
|
571
|
+
// --- curry wrapper call: curry(fn) ---
|
|
572
|
+
if ((node.callee.type === 'Identifier' && engine.curryFunctionNames.has(node.callee.name))
|
|
573
|
+
|| memberCalleeScheme(engine, env, node.callee)?.isCurryWrapper) {
|
|
574
|
+
return (0, functionPatterns_1.inferCurryWrapperCall)(engine, node, env, expectedResultType);
|
|
575
|
+
}
|
|
576
|
+
// curryN-style wrapper: `curryN (3) (fn)` — the leading call(s) supply
|
|
577
|
+
// the non-function arguments, this call supplies the function.
|
|
578
|
+
{
|
|
579
|
+
let root = node.callee;
|
|
580
|
+
let depth = 0;
|
|
581
|
+
while (root.type === 'CallExpression') {
|
|
582
|
+
depth++;
|
|
583
|
+
root = root.callee;
|
|
584
|
+
}
|
|
585
|
+
if (depth > 0 && root.type === 'Identifier'
|
|
586
|
+
&& engine.curryNFunctionNames.get(root.name) === depth) {
|
|
587
|
+
return (0, functionPatterns_1.inferCurryWrapperCall)(engine, node, env, expectedResultType);
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
let calleeType = engine.inferExpression(node.callee, env);
|
|
591
|
+
// --- Calling a type representative: `TypeRep (T x…)` is the constructor
|
|
592
|
+
// of T (see `T.@@new` in annotations.ts), with its leading type
|
|
593
|
+
// arguments fixed to the representative's. Without this the call fell
|
|
594
|
+
// into the TypeRep coercion and returned the partial `T x…` itself.
|
|
595
|
+
{
|
|
596
|
+
const rc = engine.subst.apply(calleeType);
|
|
597
|
+
if (rc.tag === 'TCon' && rc.name === types_2.T_TYPEREP && rc.args.length === 1) {
|
|
598
|
+
const inner = engine.subst.apply(rc.args[0]);
|
|
599
|
+
if (inner.tag === 'TCon' && !(0, types_2.parseKvName)(inner.name)) {
|
|
600
|
+
const ctor = (0, methodRegistry_1.lookupStaticMethod)(inner.name, '@@new');
|
|
601
|
+
if (ctor) {
|
|
602
|
+
const ctorType = ctor.scheme?.constraints?.length
|
|
603
|
+
? engine.instantiateWithConstraints(ctor.scheme, node)
|
|
604
|
+
: ctor.factory([]);
|
|
605
|
+
const ret = engine.subst.apply((0, types_2.getReturnType)(ctorType));
|
|
606
|
+
if (ret.tag === 'TCon' && ret.name === inner.name && ret.args.length >= inner.args.length) {
|
|
607
|
+
for (let i = 0; i < inner.args.length; i++) {
|
|
608
|
+
engine.unifyWithDiagnostic(ret.args[i], inner.args[i], node.callee);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
calleeType = ctorType;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
// --- Overloaded callee: Union of TFun branches (from repeated `Name :: ...`) ---
|
|
617
|
+
// Resolve which branch matches by inferring args first, then trying each.
|
|
618
|
+
// A result with a `Picked` marker only has its real shape after the
|
|
619
|
+
// projection below: an annotation (`// q :: QueryTag Params Row`) is then
|
|
620
|
+
// checked against the projected type, not against the raw marker.
|
|
621
|
+
const deferExpected = !!expectedResultType && resultHasPicked(engine, calleeType);
|
|
622
|
+
{
|
|
623
|
+
const overloadResult = (0, call_overloads_1.tryInferOverloadedCall)(engine, node, env, calleeType, deferExpected ? undefined : expectedResultType);
|
|
624
|
+
if (overloadResult !== null) {
|
|
625
|
+
// The overload path returns before the main path's post-processing
|
|
626
|
+
// hooks run, so apply the `Picked` projection (and a follow-up
|
|
627
|
+
// Merge reduction) here too. Without this, a call through an
|
|
628
|
+
// overloaded constructor union (e.g. query-builder's
|
|
629
|
+
// `({props} | Table R | ([RSelector p] -> QueryTag p (Picked R RSelector)))`
|
|
630
|
+
// from a generated Tables record) keeps its raw `Picked R Sel`
|
|
631
|
+
// marker: direct property access then only works via the
|
|
632
|
+
// permissive unknown-TCon fallback, and combinators typed with
|
|
633
|
+
// `Merge r1 r2` (e.g. `QueryTag#concat`) produce an unusable union
|
|
634
|
+
// of two unprojected Picked markers.
|
|
635
|
+
let projected = (0, call_rows_1.applyPickedProjection)(engine, node, env, overloadResult);
|
|
636
|
+
projected = (0, call_rows_1.applyMergeReduction)(engine, projected, node);
|
|
637
|
+
projected = (0, call_rows_1.applyAwaitedReduction)(engine, projected);
|
|
638
|
+
if (deferExpected && expectedResultType)
|
|
639
|
+
checkProjectedAgainstExpected(engine, projected, expectedResultType, node);
|
|
640
|
+
return projected;
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
// --- Spread argument call: fn(...args) ---
|
|
644
|
+
// When all arguments are spread elements, the callee accepts variadic args.
|
|
645
|
+
// Type the callee's param as wildcard (*) so that wrapper patterns like
|
|
646
|
+
// const wrap = (fn) => (...args) => fn(...args)
|
|
647
|
+
// infer as (* -> a) -> * -> a.
|
|
648
|
+
if (node.arguments.length > 0 &&
|
|
649
|
+
node.arguments.every((a) => a.type === 'SpreadElement')) {
|
|
650
|
+
const resultType = (0, types_1.tVar)();
|
|
651
|
+
const calleeFunType = (0, types_1.tFun)(types_1.tAny, resultType);
|
|
652
|
+
engine.unifyWithDiagnostic(calleeType, calleeFunType, node.callee);
|
|
653
|
+
// Infer the spread argument expressions for side effects / recording
|
|
654
|
+
for (const arg of node.arguments) {
|
|
655
|
+
engine.inferExpression(arg.argument, env);
|
|
656
|
+
}
|
|
657
|
+
if (expectedResultType) {
|
|
658
|
+
engine.unifyWithDiagnostic(resultType, expectedResultType, node);
|
|
659
|
+
}
|
|
660
|
+
return engine.subst.apply(resultType);
|
|
661
|
+
}
|
|
662
|
+
// --- Spread-function wrapper call: fn whose param is a function with spread tuple ---
|
|
663
|
+
// e.g. memoize :: ((a, b, ...) -> z) -> (a, b, ...) -> z
|
|
664
|
+
// This must be checked BEFORE the curried function call path.
|
|
665
|
+
{
|
|
666
|
+
const resolvedCalleeEarly = engine.subst.apply(calleeType);
|
|
667
|
+
if (resolvedCalleeEarly.tag === 'TFun' &&
|
|
668
|
+
resolvedCalleeEarly.param.tag === 'TFun' &&
|
|
669
|
+
(0, typeUtils_1.isSpreadTupleOrArray)(resolvedCalleeEarly.param.param) &&
|
|
670
|
+
!(0, typeUtils_1.hasSpreadInArrowChain)(resolvedCalleeEarly.result) &&
|
|
671
|
+
node.arguments.length === 1) {
|
|
672
|
+
return (0, functionPatterns_1.inferVariadicWrapperCall)(engine, node, env, calleeType, resolvedCalleeEarly, expectedResultType);
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
// --- Curried function call (result of curry wrapper) ---
|
|
676
|
+
// Check if the callee was produced by a curry wrapper (chained: curry(fn)(a, b))
|
|
677
|
+
// or if the callee is a variable with isCurriedResult in its scheme.
|
|
678
|
+
let isCurried = engine.pendingIsCurriedResult;
|
|
679
|
+
engine.pendingIsCurriedResult = false;
|
|
680
|
+
if (!isCurried && node.callee.type === 'Identifier') {
|
|
681
|
+
const calleeScheme = env.lookup(node.callee.name);
|
|
682
|
+
if (calleeScheme?.isCurriedResult) {
|
|
683
|
+
isCurried = true;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
// `ns.f (…)` on a namespace import of a curried library (`R.map (f, xs)`).
|
|
687
|
+
if (!isCurried && memberCalleeScheme(engine, env, node.callee)?.isCurriedResult) {
|
|
688
|
+
isCurried = true;
|
|
689
|
+
}
|
|
690
|
+
// A combinator whose first parameter is variadic — a spread tuple / spread
|
|
691
|
+
// array (`(a -> b, ..., y -> z)`), or a container of one
|
|
692
|
+
// (`f (a -> b, ..., y -> z)`) — needs the specialised routing below
|
|
693
|
+
// (fan-out, variadic items, spread-chain machinery) even when the
|
|
694
|
+
// combinator itself is a `curry (…)` result (an FP library's `pipe`, `compose`,
|
|
695
|
+
// `converge`). The generic curried path would unify an array literal as a
|
|
696
|
+
// plain `Array (f | g | h)` and lose the link-by-link chain typing.
|
|
697
|
+
if (isCurried) {
|
|
698
|
+
const rc = engine.subst.apply(calleeType);
|
|
699
|
+
if (rc.tag === 'TFun' && firstParamIsVariadic(engine, rc.param))
|
|
700
|
+
isCurried = false;
|
|
701
|
+
}
|
|
702
|
+
if (isCurried) {
|
|
703
|
+
const resolvedCalleeForCurry = engine.subst.apply(calleeType);
|
|
704
|
+
if (resolvedCalleeForCurry.tag === 'TFun') {
|
|
705
|
+
const { params, result } = (0, types_1.flattenCurriedType)(resolvedCalleeForCurry);
|
|
706
|
+
if (params.length > 0) {
|
|
707
|
+
let callResult = (0, functionPatterns_1.inferCurriedFunctionCall)(engine, node, env, calleeType, { params, result }, expectedResultType);
|
|
708
|
+
callResult = (0, narrowing_1.applyConditionalReturnNarrowing)(engine.subst, node, env, callResult);
|
|
709
|
+
return callResult;
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
// --- Container-wrapped spread chain called with an array literal ---
|
|
714
|
+
// `f (a -> b, b -> c, ..., y -> z)` behaves exactly like the bare
|
|
715
|
+
// spread-array form `[a -> b, ..., y -> z]`. Routed by the chain-combinator
|
|
716
|
+
// subsystem (functionPatterns.ts); returns null when it doesn't apply.
|
|
717
|
+
{
|
|
718
|
+
const containerChainResult = (0, functionPatterns_1.tryContainerSpreadChainCall)(engine, node, env, calleeType, expectedResultType);
|
|
719
|
+
if (containerChainResult !== null)
|
|
720
|
+
return containerChainResult;
|
|
721
|
+
}
|
|
722
|
+
let numArgs = node.arguments.length;
|
|
723
|
+
const resultType = (0, types_1.tVar)();
|
|
724
|
+
// Check if the callee expects more params than provided, and trailing
|
|
725
|
+
// params accept Undefined (i.e. they are optional). If so, pad with
|
|
726
|
+
// tUndefined so the call type-checks without requiring explicit undefined.
|
|
727
|
+
let resolvedCallee = engine.subst.apply(calleeType);
|
|
728
|
+
// Constructor-as-callable bridge for the case where unification alone
|
|
729
|
+
// wouldn't catch the mismatch — i.e. zero-arg calls. When the callee
|
|
730
|
+
// resolves to an uppercase TCon (e.g. `QueryTag b` returned from
|
|
731
|
+
// `Organisation([...])`) and the local annotation map or an imported
|
|
732
|
+
// sidecar declares a callable scheme for that name (typically a
|
|
733
|
+
// `QueryTag :: a -> RTask r e [b]` overload supplied by the consumer's
|
|
734
|
+
// project-level override), instantiate that callable form and use it
|
|
735
|
+
// as the effective callee. This lets `const rest = readRandomOrganisations()`
|
|
736
|
+
// pick up the overridden return type instead of silently producing an
|
|
737
|
+
// unbound TVar. The non-zero-arg case is already handled by
|
|
738
|
+
// `tryConstructorCallable` invoked from `unifyWithDiagnostic` below.
|
|
739
|
+
if (numArgs === 0 && resolvedCallee.tag === 'TCon'
|
|
740
|
+
&& /^[A-Z]/.test(resolvedCallee.name)) {
|
|
741
|
+
const tconName = resolvedCallee.name;
|
|
742
|
+
const localScheme = engine.annotationMap.get(tconName)?.scheme;
|
|
743
|
+
const importedScheme = engine.importedConstructors.get(tconName);
|
|
744
|
+
const scheme = localScheme ?? importedScheme;
|
|
745
|
+
if (scheme) {
|
|
746
|
+
const inst = (0, env_1.instantiate)(scheme);
|
|
747
|
+
const candidates = inst.tag === 'TCon' && inst.name === 'Union'
|
|
748
|
+
? inst.args.filter(a => a.tag === 'TFun')
|
|
749
|
+
: inst.tag === 'TFun' ? [inst] : [];
|
|
750
|
+
if (candidates.length > 0) {
|
|
751
|
+
// Use the callable form locally for THIS call site. We
|
|
752
|
+
// intentionally do NOT bind the callee's TVar to the callable
|
|
753
|
+
// form — that would mutate the value's type at every other
|
|
754
|
+
// reference (turning `tagged :: Tag Number` into the union
|
|
755
|
+
// `Tag Number | (a -> a)` next time it's read). The local
|
|
756
|
+
// rebinding is enough to drive the rest of `inferCallExpression`
|
|
757
|
+
// along the TFun path.
|
|
758
|
+
calleeType = candidates[0];
|
|
759
|
+
resolvedCallee = candidates[0];
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
// Handle variadic/spread function calls: (a, ..., z) -> r. These patterns
|
|
764
|
+
// all key off a `TFun` whose param is a `TCon` container; the structural
|
|
765
|
+
// shapes they match are catalogued by `classifyCallPattern`
|
|
766
|
+
// (functionPatterns.ts), which documents the load-bearing priority order.
|
|
767
|
+
// Partial application of a top-level spread-chain callee peels the
|
|
768
|
+
// remainder (`p1 -> p2 -> ... -> z` applied to one arg → `p2 -> ... -> z`)
|
|
769
|
+
// — see `trySpreadChainCalleePeel` for why this is call-site-only.
|
|
770
|
+
{
|
|
771
|
+
const peeled = (0, functionPatterns_1.trySpreadChainCalleePeel)(engine, node, env, resolvedCallee, expectedResultType);
|
|
772
|
+
if (peeled)
|
|
773
|
+
return peeled;
|
|
774
|
+
}
|
|
775
|
+
if (resolvedCallee.tag === 'TFun' && resolvedCallee.param.tag === 'TCon') {
|
|
776
|
+
// Fan-out combinator (converge/combine): the container is a Foldable-
|
|
777
|
+
// applied heterogeneous tuple `(combiner, a -> x1, a -> x2, ...)`. A
|
|
778
|
+
// plain unification would melt the array literal into a union and fail
|
|
779
|
+
// against the tuple; instead link each branch to its combiner parameter
|
|
780
|
+
// positionally. Only fires for a single array-literal argument.
|
|
781
|
+
if (numArgs === 1 &&
|
|
782
|
+
node.arguments[0].type === 'ArrayExpression') {
|
|
783
|
+
const fanOut = (0, functionPatterns_1.matchFanOutCallee)(resolvedCallee);
|
|
784
|
+
if (fanOut) {
|
|
785
|
+
return (0, functionPatterns_1.inferFanOutCall)(engine, node, env, fanOut, node.arguments[0]);
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
if (resolvedCallee.param.name === types_1.T_TUPLE &&
|
|
789
|
+
resolvedCallee.param.args.some(a => (0, types_1.isSpread)(a))) {
|
|
790
|
+
return (0, functionPatterns_1.inferVariadicItems)(engine, node, env, resolvedCallee, node.arguments, expectedResultType);
|
|
791
|
+
}
|
|
792
|
+
// Handle spread-array function calls: [a, ..., z] -> r
|
|
793
|
+
if (resolvedCallee.param.name === types_1.T_SPREAD_ARRAY &&
|
|
794
|
+
resolvedCallee.param.args.some(a => (0, types_1.isSpread)(a)) &&
|
|
795
|
+
node.arguments.length === 1 && node.arguments[0].type === 'ArrayExpression') {
|
|
796
|
+
return (0, functionPatterns_1.inferSpreadArrayCall)(engine, node, env, resolvedCallee, node.arguments[0], expectedResultType);
|
|
797
|
+
}
|
|
798
|
+
if (resolvedCallee.param.name === types_1.T_TUPLE && numArgs < resolvedCallee.param.args.length) {
|
|
799
|
+
const expectedParams = resolvedCallee.param.args;
|
|
800
|
+
const missingParams = expectedParams.slice(numArgs);
|
|
801
|
+
const allMissingAcceptUndefined = missingParams.every(p => (0, narrowing_1.typeAcceptsUndefined)(engine.subst, p));
|
|
802
|
+
if (allMissingAcceptUndefined) {
|
|
803
|
+
numArgs = expectedParams.length;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
// Detect argument count mismatch for tuple-parameter functions early,
|
|
808
|
+
// before unification, to produce a clear arity diagnostic.
|
|
809
|
+
// Instead of bailing out, pad numArgs to the expected count so that
|
|
810
|
+
// unification still decomposes the callee and provided arguments get
|
|
811
|
+
// their correct types. This avoids cascading errors while the user
|
|
812
|
+
// is still typing additional arguments.
|
|
813
|
+
const calleeOptionalSlots = resolveCalleeOptionalSlots(engine, env, node.callee);
|
|
814
|
+
const hasSpreadArg = node.arguments.some((a) => a.type === 'SpreadElement');
|
|
815
|
+
const padded = checkAndPadArity(engine, resolvedCallee, numArgs, node.callee, calleeOptionalSlots, hasSpreadArg);
|
|
816
|
+
numArgs = padded.numArgs;
|
|
817
|
+
const arityMismatch = padded.arityMismatch;
|
|
818
|
+
// When a function is called with zero arguments, treat it as passing
|
|
819
|
+
// `undefined` for every parameter (JS implicit undefined semantics).
|
|
820
|
+
if (numArgs === 0 && resolvedCallee.tag === 'TFun') {
|
|
821
|
+
const calleeParam = resolvedCallee.param;
|
|
822
|
+
if (calleeParam.tag === 'TCon'
|
|
823
|
+
&& (calleeParam.name === 'Void' || calleeParam.name === 'Undefined')) {
|
|
824
|
+
// Genuine nullary function `() -> R` (param is the Void marker a
|
|
825
|
+
// zero-param arrow is built with). A zero-arg call consumes only that
|
|
826
|
+
// single Void parameter and yields `R` — do NOT walk the result chain.
|
|
827
|
+
// Otherwise an IIFE whose thunk returns a curried function — e.g.
|
|
828
|
+
// `(() => value1 => value2 => …)()` typed `Void -> (a -> b -> Boolean)`
|
|
829
|
+
// — would miscount the returned arrows as the thunk's own parameters.
|
|
830
|
+
numArgs = 1;
|
|
831
|
+
}
|
|
832
|
+
else if ((0, types_1.isTuple)(calleeParam)) {
|
|
833
|
+
numArgs = calleeParam.args.length;
|
|
834
|
+
}
|
|
835
|
+
else {
|
|
836
|
+
let count = 1;
|
|
837
|
+
let cur = resolvedCallee.result;
|
|
838
|
+
while (cur.tag === 'TFun') {
|
|
839
|
+
count++;
|
|
840
|
+
cur = cur.result;
|
|
841
|
+
}
|
|
842
|
+
numArgs = count;
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
// Extract parameter TVars from the raw callee type (before substitution
|
|
846
|
+
// flattens the chain). These are the original TVars that need to be
|
|
847
|
+
// updated when an auto-union is created for the corresponding argSlot.
|
|
848
|
+
const calleeParamTVarIds = (0, typeUtils_1.extractParamTVarIds)(calleeType, numArgs);
|
|
849
|
+
// Static key-set removal: when a parameter typed `Array String` receives
|
|
850
|
+
// an inline array literal of string keys (the `omit`/`pick`-by-array
|
|
851
|
+
// pattern), expand the matching `{ [k] :: a, ...r }` group into one
|
|
852
|
+
// concrete field per key so ALL listed keys are removed, not just one.
|
|
853
|
+
calleeType = (0, call_rows_1.tryExpandKeySetFromArrayArg)(engine, calleeType, node.arguments);
|
|
854
|
+
// Row-map fan-out: when the callee has a label-field `{ [k] :: T }`
|
|
855
|
+
// whose label var k is closed over by the label-field group only,
|
|
856
|
+
// expand it into concrete fields based on the keys of the
|
|
857
|
+
// corresponding object-literal argument. This makes
|
|
858
|
+
// `unwrap :: { [k] :: Pair a b } -> { [k] :: b }` work uniformly
|
|
859
|
+
// over every key of the argument record.
|
|
860
|
+
calleeType = (0, call_rows_1.tryExpandRowMap)(engine, calleeType, node.arguments);
|
|
861
|
+
// Plan v6.3 Phase D — structural row-opening at the call site.
|
|
862
|
+
// When the callee's (curried) type has a polymorphic TVar at 2+
|
|
863
|
+
// top-level positions AND at least one argument supplied at one of
|
|
864
|
+
// those positions is an object literal (i.e. structurally a record),
|
|
865
|
+
// rewrite the scheme so each input position gets a fresh row-var and
|
|
866
|
+
// any top-level result position collects them into a `Merge`. This
|
|
867
|
+
// lets `f :: a -> a -> a` accept records of *different* shapes at
|
|
868
|
+
// different positions without forcing them through a single rigid
|
|
869
|
+
// unification — pure structural mechanism, no class hardcoding.
|
|
870
|
+
calleeType = (0, call_rows_1.maybeApplyRowOpening)(engine, calleeType, node.arguments);
|
|
871
|
+
// Endomorphic spread-arrow-chain wrapper detection. An annotation shaped
|
|
872
|
+
// like `(a -> b -> ... -> z) -> a -> b -> ... -> z` (memoize / once /
|
|
873
|
+
// identity-preserving combinators) returns a function of the SAME type as
|
|
874
|
+
// the one it receives. Because the `...` marker in the RESULT chain is a
|
|
875
|
+
// structural constant with no binding, unifying only the PARAM chain against
|
|
876
|
+
// a concrete argument leaves the result chain's `...` (and any surplus
|
|
877
|
+
// fixed params) in place — e.g. `memoizeCurried(greet2)` would display
|
|
878
|
+
// `a -> b -> ... -> String` instead of greet2's real `a -> b -> String`.
|
|
879
|
+
// When the callee is endomorphic (param chain structurally identical to the
|
|
880
|
+
// result chain and carries a spread), the correct result is simply the
|
|
881
|
+
// concrete argument's own type, so we record the flag here and rebind the
|
|
882
|
+
// result below once the argument has been inferred.
|
|
883
|
+
let endoSpreadWrapper = false;
|
|
884
|
+
{
|
|
885
|
+
const resolvedForEndo = engine.subst.apply(calleeType);
|
|
886
|
+
if (numArgs === 1 &&
|
|
887
|
+
resolvedForEndo.tag === 'TFun' &&
|
|
888
|
+
(0, typeUtils_1.hasSpreadInArrowChain)(resolvedForEndo.param) &&
|
|
889
|
+
(0, types_1.typeToString)(resolvedForEndo.param) === (0, types_1.typeToString)(resolvedForEndo.result)) {
|
|
890
|
+
endoSpreadWrapper = true;
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
// Create placeholder type vars for each argument up front, build the
|
|
894
|
+
// expected callee shape, and unify with the actual callee type.
|
|
895
|
+
// This decomposes the callee and connects each argSlot to the callee's
|
|
896
|
+
// corresponding parameter type.
|
|
897
|
+
const argSlots = (0, helpers_1.freshVars)(numArgs);
|
|
898
|
+
// Zero-arg call on a still-unresolved callee: constrain it to a thunk
|
|
899
|
+
// `() -> r` instead of the bare TVar `tMultiFun([], r)` would produce.
|
|
900
|
+
// Without this, `thunk ()` on an unannotated parameter leaves the
|
|
901
|
+
// parameter unconstrained (an FP library's `try :: (() -> a) -> RTask r Error a`
|
|
902
|
+
// in a chained static assignment inferred `a -> ...`). Known TFun
|
|
903
|
+
// callees were already arity-padded above, so this only fires for
|
|
904
|
+
// genuinely unknown callees.
|
|
905
|
+
const calleeFunType = numArgs === 0 && engine.subst.apply(calleeType).tag === 'TVar'
|
|
906
|
+
? (0, types_1.tFun)(types_1.tVoid, resultType)
|
|
907
|
+
: (0, types_1.tMultiFun)(argSlots, resultType);
|
|
908
|
+
// Unify callee with the expected function type. If unification fails
|
|
909
|
+
// because the callee is a concrete non-function type, replace the
|
|
910
|
+
// confusing "Cannot unify" message with a clearer "not callable" error.
|
|
911
|
+
const diagsBefore = engine.diagnostics.length;
|
|
912
|
+
// Capture a pretty-printed snapshot of the callee BEFORE unification.
|
|
913
|
+
// After a failed unification, free TVars in the callee may be poisoned
|
|
914
|
+
// to `$error` (see poisonFreeVars) which would leak into the
|
|
915
|
+
// "not callable" diagnostic (e.g. `Just $error | Nothing`). The
|
|
916
|
+
// snapshot preserves the natural variable names (`Just a | Nothing`).
|
|
917
|
+
const calleePrettyBefore = (0, types_1.prettyTypeToString)(engine.subst.apply(calleeType));
|
|
918
|
+
engine.unifyWithDiagnostic(calleeType, calleeFunType, node.callee);
|
|
919
|
+
// When called with zero arguments, tMultiFun([], result) returns a bare
|
|
920
|
+
// TVar that unifies with anything — so non-function callees (String,
|
|
921
|
+
// Number, etc.) silently succeed instead of producing a diagnostic.
|
|
922
|
+
// Detect this after unification, and rewrite confusing "Cannot unify"
|
|
923
|
+
// messages into clearer "not callable" errors.
|
|
924
|
+
reportNonCallableCallee(engine, node, env, calleeType, numArgs, diagsBefore, calleePrettyBefore);
|
|
925
|
+
// When an expected type is known (from an annotation), unify it with the
|
|
926
|
+
// result type BEFORE inferring arguments. Because the callee has already
|
|
927
|
+
// been decomposed above, this propagates annotation constraints into the
|
|
928
|
+
// argSlots. E.g. for `RTask String a Boolean`, this makes `res`'s slot
|
|
929
|
+
// `Boolean -> ()` so that `res("foemp")` correctly errors.
|
|
930
|
+
// An `Awaited x` marker (Promise#then) only means something once the
|
|
931
|
+
// arguments are inferred and it is reduced; the reduced result meets the
|
|
932
|
+
// expected type afterwards, at the use site.
|
|
933
|
+
if (expectedResultType && !deferExpected && !promiseWithAwaited(engine.subst.apply(resultType))) {
|
|
934
|
+
engine.unifyWithDiagnostic(resultType, expectedResultType, node);
|
|
935
|
+
}
|
|
936
|
+
// Now infer actual argument expressions — pass the constrained argSlot
|
|
937
|
+
// as expectedType so function expression arguments get their parameter
|
|
938
|
+
// types pre-constrained by the annotation.
|
|
939
|
+
const actualArgCount = node.arguments.length;
|
|
940
|
+
// When the callee has an explicit type annotation, suppress auto-union
|
|
941
|
+
// during argument inference. The annotation's parameter types are rigid
|
|
942
|
+
// constraints — a mismatch should produce a diagnostic, not silently
|
|
943
|
+
// create a union type. E.g. `f :: Integer -> Integer` called with
|
|
944
|
+
// `f("hello")` should error, not infer `Integer | String`.
|
|
945
|
+
// Curried applications count too: in `f(g)(true, "x")` the outer call's
|
|
946
|
+
// callee is a CallExpression, but its type still comes from `f`'s
|
|
947
|
+
// annotation — walk the chain to the base identifier so the later arrows
|
|
948
|
+
// of the annotation stay just as rigid as the first.
|
|
949
|
+
let baseCallee = node.callee;
|
|
950
|
+
while (baseCallee.type === 'CallExpression') {
|
|
951
|
+
baseCallee = baseCallee.callee;
|
|
952
|
+
}
|
|
953
|
+
const calleeIsAnnotated = baseCallee.type === 'Identifier' &&
|
|
954
|
+
engine.annotationMap.has(baseCallee.name);
|
|
955
|
+
const prevSuppressAutoUnion = engine.suppressAutoUnion;
|
|
956
|
+
if (calleeIsAnnotated) {
|
|
957
|
+
engine.suppressAutoUnion = true;
|
|
958
|
+
}
|
|
959
|
+
// Pin the callee-result's free vars for the duration of argument
|
|
960
|
+
// inference: per-element freshening of expanded union element types
|
|
961
|
+
// (array literals) must not sever vars that thread into the result
|
|
962
|
+
// (e.g. `p` in `[Selector p] -> Tag p o`).
|
|
963
|
+
const prevPinned = engine.pinnedElementVarIds;
|
|
964
|
+
{
|
|
965
|
+
const resultVarNames = new Map();
|
|
966
|
+
(0, types_1.collectVarNames)(engine.subst.apply(resultType), resultVarNames);
|
|
967
|
+
engine.pinnedElementVarIds = new Set(resultVarNames.keys());
|
|
968
|
+
}
|
|
969
|
+
const resolvedParamTypes = [];
|
|
970
|
+
const actualArgTypes = [];
|
|
971
|
+
// Skolems minted for rank-N (`forall`) parameter slots during this call —
|
|
972
|
+
// used by the post-loop escape check below. Lazily allocated so the
|
|
973
|
+
// rank-1 hot path pays nothing.
|
|
974
|
+
let rankNSkolems = null;
|
|
975
|
+
try {
|
|
976
|
+
// Capture resolved param types BEFORE arg inference for union narrowing
|
|
977
|
+
for (let i = 0; i < numArgs && i < actualArgCount; i++) {
|
|
978
|
+
resolvedParamTypes.push(engine.subst.apply(argSlots[i]));
|
|
979
|
+
}
|
|
980
|
+
for (let i = 0; i < numArgs; i++) {
|
|
981
|
+
if (i >= actualArgCount) {
|
|
982
|
+
// Arity mismatch: leave padded slots as fresh vars — the diagnostic
|
|
983
|
+
// was already emitted, no need to unify with Undefined.
|
|
984
|
+
if (arityMismatch)
|
|
985
|
+
continue;
|
|
986
|
+
// Spread argument (`fn (a, ...rest)`): the remaining slots are filled
|
|
987
|
+
// by the spread at runtime — leave them unconstrained.
|
|
988
|
+
if (hasSpreadArg)
|
|
989
|
+
continue;
|
|
990
|
+
// Nullary function: () -> m — the slot resolved to Void after callee
|
|
991
|
+
// decomposition; do not pad with Undefined.
|
|
992
|
+
const resolvedSlot = engine.subst.apply(argSlots[i]);
|
|
993
|
+
if (resolvedSlot.tag === 'TCon' && resolvedSlot.name === 'Void') {
|
|
994
|
+
continue;
|
|
995
|
+
}
|
|
996
|
+
// JS-default slot (`(x, y = 0) => …`): the default supplies the
|
|
997
|
+
// value, so the missing argument puts no constraint on the slot.
|
|
998
|
+
if (calleeOptionalSlots && calleeOptionalSlots.includes(i))
|
|
999
|
+
continue;
|
|
1000
|
+
// Padded optional parameter — fill with Undefined
|
|
1001
|
+
engine.unifyWithDiagnostic(types_1.tUndefined, argSlots[i], node);
|
|
1002
|
+
continue;
|
|
1003
|
+
}
|
|
1004
|
+
const expectedArgType = engine.subst.apply(argSlots[i]);
|
|
1005
|
+
// --- Rank-N parameter slot: the annotation demands a POLYMORPHIC
|
|
1006
|
+
// argument (`forall a. ...`). Skolemize the bound variables and check
|
|
1007
|
+
// the argument against the rigid body — only a genuinely polymorphic
|
|
1008
|
+
// argument passes (subsumption). Handled fully by the helper; the
|
|
1009
|
+
// regular leniency paths below (callback adaptation, auto-union
|
|
1010
|
+
// propagation) must not see the quantifier.
|
|
1011
|
+
if (expectedArgType.tag === 'TForall') {
|
|
1012
|
+
if (!rankNSkolems)
|
|
1013
|
+
rankNSkolems = new Set();
|
|
1014
|
+
const rankNArgType = inferRankNArgument(engine, node.arguments[i], env, expectedArgType, rankNSkolems);
|
|
1015
|
+
actualArgTypes.push(rankNArgType);
|
|
1016
|
+
continue;
|
|
1017
|
+
}
|
|
1018
|
+
// JS callback-arity tolerance: when the expected slot is a multi-arg
|
|
1019
|
+
// callback `(a, Number, [a]) -> b` but the argument is an *expression*
|
|
1020
|
+
// that evaluates to a function (e.g. a point-free `dumpKey(this)` call,
|
|
1021
|
+
// not an inline arrow), passing the multi-arg slot as the eager expected
|
|
1022
|
+
// type would force the nested expression to unify its (fewer-param)
|
|
1023
|
+
// function result against the tuple param and spuriously fail. Defer to
|
|
1024
|
+
// `adaptCallbackArity` below by inferring without the eager expected
|
|
1025
|
+
// type. Inline function literals keep the expected type so their
|
|
1026
|
+
// parameters get pre-constrained.
|
|
1027
|
+
let argExpected = expectedArgType;
|
|
1028
|
+
const argNodeType = node.arguments[i].type;
|
|
1029
|
+
const argIsFunctionLiteral = argNodeType === 'ArrowFunctionExpression' || argNodeType === 'FunctionExpression';
|
|
1030
|
+
if (!argIsFunctionLiteral
|
|
1031
|
+
&& expectedArgType.tag === 'TFun'
|
|
1032
|
+
&& (0, types_1.isTuple)(expectedArgType.param)) {
|
|
1033
|
+
argExpected = undefined;
|
|
1034
|
+
}
|
|
1035
|
+
// Auto-union may widen the ARGUMENT side, never the callee's parameter:
|
|
1036
|
+
// when the slot was already concrete after decomposing the callee
|
|
1037
|
+
// (`String` from `toUpper :: String -> String`, whether the callee is
|
|
1038
|
+
// annotated here, imported, or an alias such as `const top = toUpper`),
|
|
1039
|
+
// a mismatching argument is an error — not a silent `String | Number`.
|
|
1040
|
+
// Function literals keep their own (gradual) body inference.
|
|
1041
|
+
const slotBefore = resolvedParamTypes[i];
|
|
1042
|
+
const slotIsConcrete = slotBefore !== undefined && slotBefore.tag !== 'TVar'
|
|
1043
|
+
&& !(slotBefore.tag === 'TCon' && slotBefore.name === types_1.T_UNION);
|
|
1044
|
+
const suppressHere = slotIsConcrete && !argIsFunctionLiteral && !engine.suppressAutoUnion;
|
|
1045
|
+
if (suppressHere)
|
|
1046
|
+
engine.suppressAutoUnion = true;
|
|
1047
|
+
// (Restored after `adaptCallbackArity` below, which performs the
|
|
1048
|
+
// argument-vs-slot unification for non-literal arguments.)
|
|
1049
|
+
const argType = engine.inferExpressionWithExpected(node.arguments[i], env, argExpected);
|
|
1050
|
+
actualArgTypes.push(engine.subst.apply(argType));
|
|
1051
|
+
// Protect an annotated, still-polymorphic parameter from being PINNED
|
|
1052
|
+
// globally by an unrelated call. When the argument is a reference to a
|
|
1053
|
+
// parameter whose declared (frozen) type is polymorphic — e.g. a
|
|
1054
|
+
// `Foldable f => f a | String` overload parameter passed to
|
|
1055
|
+
// `hasProp :: String -> Object k a -> Boolean` — unifying the param's
|
|
1056
|
+
// own type variable with the callee's concrete parameter would mutate
|
|
1057
|
+
// the parameter's type everywhere (inside AND outside any guarding
|
|
1058
|
+
// `if`), producing spurious narrowings such as `foldable :: Object k a`.
|
|
1059
|
+
// Instead, satisfy the callee slot with a FRESH instantiation of the
|
|
1060
|
+
// argument type so the parameter's variable stays free (let-style
|
|
1061
|
+
// polymorphism at the call boundary). This only applies when the slot
|
|
1062
|
+
// would otherwise specialise the parameter (the slot is more concrete
|
|
1063
|
+
// than a bare variable).
|
|
1064
|
+
let effectiveArgType = argType;
|
|
1065
|
+
if ((0, functionPatterns_1.shouldProtectPolymorphicParamArg)(engine, node.arguments[i], env, argSlots[i])) {
|
|
1066
|
+
effectiveArgType = (0, typeUtils_1.freshenType)(engine.subst.apply(argType));
|
|
1067
|
+
}
|
|
1068
|
+
// JS callback adaptation: pad arity when actual function has fewer params
|
|
1069
|
+
// than the expected multi-arg callback slot (e.g. [1,2].map(String)).
|
|
1070
|
+
try {
|
|
1071
|
+
(0, functionPatterns_1.adaptCallbackArity)(engine, effectiveArgType, argSlots[i], node.arguments[i]);
|
|
1072
|
+
}
|
|
1073
|
+
finally {
|
|
1074
|
+
if (suppressHere)
|
|
1075
|
+
engine.suppressAutoUnion = false;
|
|
1076
|
+
}
|
|
1077
|
+
// Numeric literal refinement: when the callee has an annotation with a
|
|
1078
|
+
// refined numeric type (Integer, NonNegativeInteger, NegativeInteger),
|
|
1079
|
+
// check whether the literal value satisfies the refinement.
|
|
1080
|
+
if (calleeIsAnnotated) {
|
|
1081
|
+
const paramType = engine.subst.apply(argSlots[i]);
|
|
1082
|
+
if (paramType.tag === 'TCon' && types_1.NUMERIC_SUBTYPES.has(paramType.name)) {
|
|
1083
|
+
const litValue = getNumericLiteralValue(node.arguments[i]);
|
|
1084
|
+
if (litValue !== null) {
|
|
1085
|
+
const err = checkNumericRefinement(paramType.name, litValue);
|
|
1086
|
+
if (err) {
|
|
1087
|
+
engine.addDiag(`Type '${paramType.name}' — ${err}`, node.arguments[i]);
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
// If auto-union was created for this argSlot, propagate the union to
|
|
1093
|
+
// the callee's original parameter TVar so it flows into the result type.
|
|
1094
|
+
const resolvedSlot = engine.subst.apply(argSlots[i]);
|
|
1095
|
+
if (resolvedSlot.tag === 'TCon' &&
|
|
1096
|
+
resolvedSlot.name === types_1.T_UNION &&
|
|
1097
|
+
calleeParamTVarIds[i] !== undefined) {
|
|
1098
|
+
engine.subst.set(calleeParamTVarIds[i], resolvedSlot);
|
|
1099
|
+
}
|
|
1100
|
+
// Default unfilled record-field type variables to Undefined. When an
|
|
1101
|
+
// object-literal argument lacks a field that the callee's open-record
|
|
1102
|
+
// parameter expects (e.g. `getTwo("name", "age", {})` against
|
|
1103
|
+
// `(k, i, { [k] :: a, [i] :: b, ...r }) -> { [k] :: a, [i] :: b }`),
|
|
1104
|
+
// the value-type variables `a`, `b` would otherwise stay unbound and
|
|
1105
|
+
// surface as polymorphic in the result. At runtime those reads yield
|
|
1106
|
+
// `undefined`, so binding the unfilled vars matches JS semantics and
|
|
1107
|
+
// gives a more useful inferred type for the call result.
|
|
1108
|
+
defaultUnfilledFieldsToUndefined(engine, node.arguments[i], expectedArgType);
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
finally {
|
|
1112
|
+
// Restore auto-union suppression state after argument inference.
|
|
1113
|
+
engine.suppressAutoUnion = prevSuppressAutoUnion;
|
|
1114
|
+
engine.pinnedElementVarIds = prevPinned;
|
|
1115
|
+
}
|
|
1116
|
+
let result = engine.subst.apply(resultType);
|
|
1117
|
+
// Rank-N escape check: a skolem minted for a `forall` parameter slot may
|
|
1118
|
+
// not survive into the call's result type — that would let the callee's
|
|
1119
|
+
// locally-quantified variable leak into the caller's scope.
|
|
1120
|
+
if (rankNSkolems !== null && rankNSkolems.size > 0 &&
|
|
1121
|
+
(0, typeUtils_1.someType)(result, t => t.tag === 'TCon' && rankNSkolems.has(t.name))) {
|
|
1122
|
+
engine.addDiag('Polymorphic value escapes its scope: a type bound by \'forall\' appears in the call result', (0, annotations_1.narrowToIdentifier)(node));
|
|
1123
|
+
}
|
|
1124
|
+
// Endomorphic spread-arrow-chain wrapper: the result is definitionally the
|
|
1125
|
+
// same type as the concrete argument (see the flag computed above). Adopt
|
|
1126
|
+
// the argument's actual (fully arity-resolved) type so the result chain's
|
|
1127
|
+
// spread `...` collapses to the argument's real arity instead of lingering.
|
|
1128
|
+
if (endoSpreadWrapper && actualArgTypes.length === 1) {
|
|
1129
|
+
const resolvedArg = engine.subst.apply(actualArgTypes[0]);
|
|
1130
|
+
if (resolvedArg.tag === 'TFun' && !(0, typeUtils_1.hasSpreadInArrowChain)(resolvedArg)) {
|
|
1131
|
+
result = resolvedArg;
|
|
1132
|
+
}
|
|
1133
|
+
}
|
|
1134
|
+
// applyArgs-style peeling capture — recorded by the chain-combinator
|
|
1135
|
+
// subsystem (functionPatterns.ts) so the follow-up array application can
|
|
1136
|
+
// peel partial results and flag over-application.
|
|
1137
|
+
(0, functionPatterns_1.captureSpreadChainPeel)(engine, node, numArgs, actualArgTypes, resolvedCallee, result);
|
|
1138
|
+
// Narrow union return types based on actual argument types.
|
|
1139
|
+
// E.g. if callee is (Number | null) -> Number | null and arg is Number,
|
|
1140
|
+
// the result narrows to Number (since we know the argument is not null).
|
|
1141
|
+
result = (0, typeUtils_1.narrowCallResultByArgs)(result, resolvedParamTypes, actualArgTypes);
|
|
1142
|
+
// Literal guard conditional return narrowing
|
|
1143
|
+
result = (0, narrowing_1.applyConditionalReturnNarrowing)(engine.subst, node, env, result);
|
|
1144
|
+
// Inline call-site record projection: when the result type contains a
|
|
1145
|
+
// `Picked R a` marker (a generic primitive used by libraries that emit
|
|
1146
|
+
// signatures like `[Selector] -> QueryTag (Picked Row Selector)`), inspect
|
|
1147
|
+
// the call's literal-array argument and replace the marker with a
|
|
1148
|
+
// record built from the elements. Pure post-processing — does not
|
|
1149
|
+
// change unification semantics elsewhere.
|
|
1150
|
+
validateSelectorRelations(engine, node, result);
|
|
1151
|
+
result = (0, call_rows_1.applyPickedProjection)(engine, node, env, result);
|
|
1152
|
+
// Reduce any `Merge a b` markers in the result to a single structural
|
|
1153
|
+
// union record (alias-stripped, conflicting field types unified).
|
|
1154
|
+
// Runs AFTER picked projection so that combinators like
|
|
1155
|
+
// `QueryTag#concat` operate on already-projected rows.
|
|
1156
|
+
result = (0, call_rows_1.applyMergeReduction)(engine, result, node);
|
|
1157
|
+
result = (0, call_rows_1.applyAwaitedReduction)(engine, result);
|
|
1158
|
+
if (deferExpected && expectedResultType)
|
|
1159
|
+
checkProjectedAgainstExpected(engine, result, expectedResultType, node);
|
|
1160
|
+
// Generic paramHint capture: when the call's result is a TCon and one
|
|
1161
|
+
// of its arguments is (after substitution) a callback `({...record...}) -> _`,
|
|
1162
|
+
// attach the record as `paramHint` on the result TCon. This lets
|
|
1163
|
+
// helper bindings like `const limit = Limit(p => p.limit)` carry the
|
|
1164
|
+
// captured callback record across the binding so downstream consumers
|
|
1165
|
+
// (e.g. `gatherParamRecord` in another call's selector list) can
|
|
1166
|
+
// reconstruct the structural parameter shape even after generalisation
|
|
1167
|
+
// would otherwise erase it.
|
|
1168
|
+
if (result.tag === 'TCon' && !result.paramHint) {
|
|
1169
|
+
for (const arg of node.arguments) {
|
|
1170
|
+
const argType = engine.maybeExpandAlias(engine.subst.apply(engine.getNodeType(arg) ?? (0, types_1.tVar)()));
|
|
1171
|
+
if (argType.tag === 'TFun') {
|
|
1172
|
+
const paramT = engine.maybeExpandAlias(engine.subst.apply(argType.param));
|
|
1173
|
+
if (paramT.tag === 'TRecord' && Object.keys(paramT.fields).length > 0) {
|
|
1174
|
+
result.paramHint = paramT;
|
|
1175
|
+
break;
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
// Re-resolve the result so any TCon eventually surfaced through the
|
|
1181
|
+
// substitution can still receive a `paramHint` (helper calls like
|
|
1182
|
+
// `Limit(p => p.x)` typically have a TVar result here that only
|
|
1183
|
+
// becomes `Limit (callback)` after unification at the use-site).
|
|
1184
|
+
const resolved = engine.subst.apply(result);
|
|
1185
|
+
if (resolved !== result && resolved.tag === 'TCon' && !resolved.paramHint) {
|
|
1186
|
+
for (const arg of node.arguments) {
|
|
1187
|
+
const argType = engine.maybeExpandAlias(engine.subst.apply(engine.getNodeType(arg) ?? (0, types_1.tVar)()));
|
|
1188
|
+
if (argType.tag === 'TFun') {
|
|
1189
|
+
const paramT = engine.maybeExpandAlias(engine.subst.apply(argType.param));
|
|
1190
|
+
if (paramT.tag === 'TRecord' && Object.keys(paramT.fields).length > 0) {
|
|
1191
|
+
resolved.paramHint = paramT;
|
|
1192
|
+
break;
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
result = resolved;
|
|
1197
|
+
}
|
|
1198
|
+
return result;
|
|
1199
|
+
}
|
|
1200
|
+
// ---------------------------------------------------------------------------
|
|
1201
|
+
// Rank-N argument subsumption
|
|
1202
|
+
// ---------------------------------------------------------------------------
|
|
1203
|
+
/**
|
|
1204
|
+
* Check a call argument against a `forall` parameter slot (rank-N
|
|
1205
|
+
* subsumption). The quantified variables are skolemized to fresh rigid
|
|
1206
|
+
* constants; the argument is then inferred/checked against the skolemized
|
|
1207
|
+
* body. A monomorphic argument (e.g. `Number -> Number` against
|
|
1208
|
+
* `forall a. a -> a`) fails to unify with the skolems and produces ONE
|
|
1209
|
+
* targeted "not polymorphic enough" diagnostic — the raw skolem-mismatch
|
|
1210
|
+
* diagnostics raised during inference are scrubbed. Poisoning and
|
|
1211
|
+
* auto-union are suppressed for the duration so a failed subsumption
|
|
1212
|
+
* neither cascades nor melts into a union.
|
|
1213
|
+
*/
|
|
1214
|
+
function inferRankNArgument(engine, argNode, env, expected, rankNSkolems) {
|
|
1215
|
+
const { body: skolemBody, skolems, skolemToName, varToSkolem } = (0, env_1.skolemizeForall)(expected);
|
|
1216
|
+
for (const s of skolems)
|
|
1217
|
+
rankNSkolems.add(s);
|
|
1218
|
+
engine.registerSkolemNames(skolemToName);
|
|
1219
|
+
// Constraint promises: `forall f. Functor f => …` guarantees the Functor
|
|
1220
|
+
// methods on the skolemized binder — record the promised classes (plus
|
|
1221
|
+
// superclasses) so pending-constraint validation accepts them on the skolem.
|
|
1222
|
+
if (expected.constraints) {
|
|
1223
|
+
for (const c of expected.constraints) {
|
|
1224
|
+
const sk = c.varId !== undefined ? varToSkolem.get(c.varId) : undefined;
|
|
1225
|
+
if (!sk)
|
|
1226
|
+
continue;
|
|
1227
|
+
let promised = engine.rankNSkolemPromises.get(sk);
|
|
1228
|
+
if (!promised) {
|
|
1229
|
+
promised = new Set();
|
|
1230
|
+
engine.rankNSkolemPromises.set(sk, promised);
|
|
1231
|
+
}
|
|
1232
|
+
promised.add(c.className);
|
|
1233
|
+
for (const sup of (0, constraintRegistry_1.constraintSuperclassClosure)(c.className))
|
|
1234
|
+
promised.add(sup);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1237
|
+
const diagsBefore = engine.diagnostics.length;
|
|
1238
|
+
const prevSuppressUnion = engine.suppressAutoUnion;
|
|
1239
|
+
engine.suppressAutoUnion = true;
|
|
1240
|
+
engine.suppressPoisonDepth++;
|
|
1241
|
+
let argType = skolemBody;
|
|
1242
|
+
let failed = false;
|
|
1243
|
+
try {
|
|
1244
|
+
argType = engine.inferExpressionWithExpected(argNode, env, skolemBody);
|
|
1245
|
+
const s = (0, unify_1.unify)(engine.resolve(skolemBody), engine.resolve(argType));
|
|
1246
|
+
engine.subst.mergeFrom(s);
|
|
1247
|
+
}
|
|
1248
|
+
catch (e) {
|
|
1249
|
+
if (!(e instanceof unify_1.UnificationError))
|
|
1250
|
+
throw e;
|
|
1251
|
+
failed = true;
|
|
1252
|
+
}
|
|
1253
|
+
finally {
|
|
1254
|
+
engine.suppressPoisonDepth--;
|
|
1255
|
+
engine.suppressAutoUnion = prevSuppressUnion;
|
|
1256
|
+
}
|
|
1257
|
+
// Any diagnostic raised against one of OUR skolems means the same thing:
|
|
1258
|
+
// the argument is not polymorphic enough. Collapse them into one targeted
|
|
1259
|
+
// message; keep unrelated diagnostics (genuine errors inside a lambda body).
|
|
1260
|
+
// Note: pretty-printing may already have mapped the skolem back to its
|
|
1261
|
+
// display letter, so once subsumption is known to have failed we also drop
|
|
1262
|
+
// new diagnostics located INSIDE the argument span (they are all symptoms
|
|
1263
|
+
// of the same root cause).
|
|
1264
|
+
const skolemRes = Array.from(skolems).map(n => new RegExp(`${n.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![0-9])`));
|
|
1265
|
+
const mentionsSkolem = (msg) => skolemRes.some(re => re.test(msg));
|
|
1266
|
+
let sawSkolemDiag = false;
|
|
1267
|
+
for (let d = diagsBefore; d < engine.diagnostics.length; d++) {
|
|
1268
|
+
if (mentionsSkolem(engine.diagnostics[d].message)) {
|
|
1269
|
+
sawSkolemDiag = true;
|
|
1270
|
+
break;
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
if (failed || sawSkolemDiag) {
|
|
1274
|
+
const argSpan = argNode;
|
|
1275
|
+
const kept = [];
|
|
1276
|
+
for (let d = diagsBefore; d < engine.diagnostics.length; d++) {
|
|
1277
|
+
const diag = engine.diagnostics[d];
|
|
1278
|
+
const insideArg = typeof argSpan.start === 'number' && typeof argSpan.end === 'number'
|
|
1279
|
+
&& diag.start >= argSpan.start && diag.end <= argSpan.end;
|
|
1280
|
+
if (!insideArg && !mentionsSkolem(diag.message))
|
|
1281
|
+
kept.push(diag);
|
|
1282
|
+
}
|
|
1283
|
+
engine.diagnostics.length = diagsBefore;
|
|
1284
|
+
engine.diagnostics.push(...kept);
|
|
1285
|
+
const gotPretty = (0, types_1.prettyTypeToString)((0, typeUtils_1.scrubSkolems)(engine.resolve(argType), skolemToName));
|
|
1286
|
+
engine.addDiag(`Argument is not polymorphic enough: expected '${(0, types_1.prettyTypeToString)(expected)}' but got '${gotPretty}'`, (0, annotations_1.narrowToIdentifier)(argNode));
|
|
1287
|
+
}
|
|
1288
|
+
return engine.resolve(argType);
|
|
1289
|
+
}
|
|
1290
|
+
// ---------------------------------------------------------------------------
|
|
1291
|
+
// Picked projection — inline record build from a call-site array argument
|
|
1292
|
+
// ---------------------------------------------------------------------------
|
|
1293
|
+
/**
|
|
1294
|
+
* Constructor-aware "no relation" diagnostic.
|
|
1295
|
+
*
|
|
1296
|
+
* When a call-site has the shape `Parent([Child(...), ...])` (or
|
|
1297
|
+
* `Parent([Child, ...])` — bare identifier form) and the result type
|
|
1298
|
+
* carries a `Picked R _` marker for a row `R` that has at least one
|
|
1299
|
+
* registered method-shadow (i.e. the schema declares relations on that
|
|
1300
|
+
* row), each array element whose extracted child-row name is NOT a
|
|
1301
|
+
* known relation of `R` produces a friendly diagnostic:
|
|
1302
|
+
*
|
|
1303
|
+
* `'Child' has no relation with 'Parent'`
|
|
1304
|
+
*
|
|
1305
|
+
* Located on the offending element node. Replaces (and pre-empts) the
|
|
1306
|
+
* coarser "is not a valid relation here. Valid relations: …" message
|
|
1307
|
+
* that `unifyWithUnion` may also emit at the same span — we strip any
|
|
1308
|
+
* such pre-existing diagnostic at the same span when we fire.
|
|
1309
|
+
*
|
|
1310
|
+
* Generic across libraries — relies only on the `Picked R _` primitive
|
|
1311
|
+
* plus method-shadow registry.
|
|
1312
|
+
*/
|
|
1313
|
+
function validateSelectorRelations(engine, node, result) {
|
|
1314
|
+
if (node.callee.type !== 'Identifier')
|
|
1315
|
+
return;
|
|
1316
|
+
const parentCalleeName = node.callee.name;
|
|
1317
|
+
const arrayArg = node.arguments.find(a => a.type === 'ArrayExpression');
|
|
1318
|
+
if (!arrayArg)
|
|
1319
|
+
return;
|
|
1320
|
+
// Collect parent row aliases from `Picked R _` markers in the result.
|
|
1321
|
+
const parentRows = new Set();
|
|
1322
|
+
const collect = (t, depth = 0) => {
|
|
1323
|
+
if (depth > 20)
|
|
1324
|
+
return;
|
|
1325
|
+
if (t.tag === 'TCon') {
|
|
1326
|
+
if (t.name === types_1.T_PICKED && t.args.length >= 1) {
|
|
1327
|
+
const r = engine.subst.apply(t.args[0]);
|
|
1328
|
+
if (r.tag === 'TCon')
|
|
1329
|
+
parentRows.add(r.name);
|
|
1330
|
+
else if (r.tag === 'TRecord' && r.alias)
|
|
1331
|
+
parentRows.add(r.alias);
|
|
1332
|
+
}
|
|
1333
|
+
for (const a of t.args)
|
|
1334
|
+
collect(a, depth + 1);
|
|
1335
|
+
}
|
|
1336
|
+
else if (t.tag === 'TFun') {
|
|
1337
|
+
collect(t.param, depth + 1);
|
|
1338
|
+
collect(t.result, depth + 1);
|
|
1339
|
+
}
|
|
1340
|
+
else if (t.tag === 'TRecord') {
|
|
1341
|
+
for (const k in t.fields)
|
|
1342
|
+
collect(t.fields[k], depth + 1);
|
|
1343
|
+
if (t.rest)
|
|
1344
|
+
collect(t.rest, depth + 1);
|
|
1345
|
+
}
|
|
1346
|
+
};
|
|
1347
|
+
collect(result);
|
|
1348
|
+
if (parentRows.size === 0)
|
|
1349
|
+
return;
|
|
1350
|
+
// Only check parent rows that actually declare some relations. Without
|
|
1351
|
+
// this gate, fully generic demos (e.g. one with no `R#x :: ChildRow`
|
|
1352
|
+
// shadows at all) would wrongly reject every nested call.
|
|
1353
|
+
const relevantParents = Array.from(parentRows).filter(r => (0, methodRegistry_2.getMethodNames)(r).length > 0);
|
|
1354
|
+
if (relevantParents.length === 0)
|
|
1355
|
+
return;
|
|
1356
|
+
for (const elem of arrayArg.elements) {
|
|
1357
|
+
if (!elem)
|
|
1358
|
+
continue;
|
|
1359
|
+
const elemNode = elem;
|
|
1360
|
+
if (elemNode.type !== 'CallExpression' && elemNode.type !== 'Identifier')
|
|
1361
|
+
continue;
|
|
1362
|
+
// Skip identifiers that resolve to a column or `Prop T` (handled by
|
|
1363
|
+
// projection's own positive cases) — only flag ones that look like
|
|
1364
|
+
// a row-constructor reference.
|
|
1365
|
+
const elemType = engine.subst.apply(engine.getNodeType(elemNode) ?? (0, types_1.tVar)());
|
|
1366
|
+
const childRow = extractChildRowForRelationCheck(engine, elemNode, elemType);
|
|
1367
|
+
if (!childRow)
|
|
1368
|
+
continue;
|
|
1369
|
+
// Determine the child constructor name for the message.
|
|
1370
|
+
let childCalleeName;
|
|
1371
|
+
if (elemNode.type === 'CallExpression') {
|
|
1372
|
+
const callee = elemNode.callee;
|
|
1373
|
+
if (callee.type === 'Identifier')
|
|
1374
|
+
childCalleeName = callee.name;
|
|
1375
|
+
}
|
|
1376
|
+
else {
|
|
1377
|
+
childCalleeName = elemNode.name;
|
|
1378
|
+
}
|
|
1379
|
+
if (!childCalleeName)
|
|
1380
|
+
continue;
|
|
1381
|
+
// If ANY relevant parent accepts this child as a relation, allow.
|
|
1382
|
+
let accepted = false;
|
|
1383
|
+
for (const parentRow of relevantParents) {
|
|
1384
|
+
if ((0, call_rows_1.findShadowKeyForChildRow)(parentRow, childRow, null)) {
|
|
1385
|
+
accepted = true;
|
|
1386
|
+
break;
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
if (accepted)
|
|
1390
|
+
continue;
|
|
1391
|
+
// Strip any pre-existing redundant union-mismatch diagnostic at the
|
|
1392
|
+
// same span before emitting the friendlier one.
|
|
1393
|
+
const loc = (0, annotations_1.narrowToIdentifier)(elemNode);
|
|
1394
|
+
engine.diagnostics = engine.diagnostics.filter(d => !(d.start === loc.start && d.end === loc.end &&
|
|
1395
|
+
/ is not a valid relation here\b/.test(d.message)));
|
|
1396
|
+
engine.addDiag(`'${childCalleeName}' has no relation with '${parentCalleeName}'`, loc);
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
/**
|
|
1400
|
+
* Like `extractChildRowName` but specifically for the relation-check pass.
|
|
1401
|
+
*
|
|
1402
|
+
* For CallExpression elements: prefer the call's already-resolved result
|
|
1403
|
+
* type, which after `applyPickedProjection` carries a `pickedFrom` tag on
|
|
1404
|
+
* its inner TRecord — the most reliable source of "what row this call
|
|
1405
|
+
* returns". Only when that's unavailable, fall back to scanning the
|
|
1406
|
+
* callee's TFun signature (result side only, to avoid selector-union
|
|
1407
|
+
* cross-pollution from the parent call's unification).
|
|
1408
|
+
*
|
|
1409
|
+
* For Identifier elements (bare row reference): scan the resolved type's
|
|
1410
|
+
* TFun result side for a `Picked R _` marker.
|
|
1411
|
+
*/
|
|
1412
|
+
function extractChildRowForRelationCheck(engine, elemNode, elemType) {
|
|
1413
|
+
if (elemNode.type === 'CallExpression') {
|
|
1414
|
+
const callee = elemNode.callee;
|
|
1415
|
+
const calleeType = engine.subst.apply(engine.getNodeType(callee) ?? (0, types_1.tVar)());
|
|
1416
|
+
return (0, call_rows_1.findPickedInResultSides)(engine, calleeType);
|
|
1417
|
+
}
|
|
1418
|
+
if (elemNode.type === 'Identifier') {
|
|
1419
|
+
// Bare identifier: same caveat — param sides may carry parent's
|
|
1420
|
+
// selector-union rows after unification.
|
|
1421
|
+
return (0, call_rows_1.findPickedInResultSides)(engine, elemType);
|
|
1422
|
+
}
|
|
1423
|
+
return null;
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
* For an object-literal argument, bind any field-value type variables in the
|
|
1427
|
+
* expected (callee) parameter that the literal didn't supply to `Undefined`.
|
|
1428
|
+
* This matches JS runtime semantics (missing keys read as `undefined`) and
|
|
1429
|
+
* avoids leaving free type vars in the call's result type.
|
|
1430
|
+
*/
|
|
1431
|
+
function defaultUnfilledFieldsToUndefined(engine, argNode, expectedArgType) {
|
|
1432
|
+
if (!argNode || argNode.type !== 'ObjectExpression')
|
|
1433
|
+
return;
|
|
1434
|
+
const expected = engine.subst.apply(expectedArgType);
|
|
1435
|
+
if (expected.tag !== 'TRecord')
|
|
1436
|
+
return;
|
|
1437
|
+
// Collect string keys actually present in the literal.
|
|
1438
|
+
const provided = new Set();
|
|
1439
|
+
const props = argNode.properties || [];
|
|
1440
|
+
for (const p of props) {
|
|
1441
|
+
if (p.type !== 'Property' || !p.key)
|
|
1442
|
+
continue;
|
|
1443
|
+
if (p.computed)
|
|
1444
|
+
continue;
|
|
1445
|
+
if (p.key.type === 'Identifier' && typeof p.key.name === 'string') {
|
|
1446
|
+
provided.add(p.key.name);
|
|
1447
|
+
}
|
|
1448
|
+
else if (p.key.type === 'Literal' && typeof p.key.value === 'string') {
|
|
1449
|
+
provided.add(p.key.value);
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
for (const [k, vt] of Object.entries(expected.fields)) {
|
|
1453
|
+
if (provided.has(k))
|
|
1454
|
+
continue;
|
|
1455
|
+
const resolved = engine.subst.apply(vt);
|
|
1456
|
+
if (resolved.tag === 'TVar') {
|
|
1457
|
+
engine.subst.set(resolved.id, types_1.tUndefined);
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
function isAwaitedMarker(t) {
|
|
1462
|
+
return t.tag === 'TCon' && t.name === 'Awaited';
|
|
1463
|
+
}
|
|
1464
|
+
/** A `Promise e (Awaited b)` result of `Promise#then` (see applyAwaitedReduction). */
|
|
1465
|
+
function promiseWithAwaited(t) {
|
|
1466
|
+
return t.tag === 'TCon' && t.name === 'Promise' && t.args.some(isAwaitedMarker);
|
|
1467
|
+
}
|
|
1468
|
+
//# sourceMappingURL=calls.js.map
|