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,1497 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ============================================================================
|
|
3
|
+
// Expression-level inference functions extracted from InferenceEngine
|
|
4
|
+
//
|
|
5
|
+
// Plain language: an *expression* is any piece of code that produces a value
|
|
6
|
+
// (`1 + 2`, `"hi"`, `obj.field`, `x => x * 2`, `f(3)`, …). This file is the
|
|
7
|
+
// switchboard that, given one expression from the syntax tree, works out its
|
|
8
|
+
// type. It handles the simple kinds directly (literals, arrays, objects,
|
|
9
|
+
// operators, template strings) and hands the complicated kinds to specialist
|
|
10
|
+
// modules: function expressions → expr-functions.ts, property access →
|
|
11
|
+
// expr-member.ts, assignments → expr-assignment.ts, calls → calls.ts.
|
|
12
|
+
// ============================================================================
|
|
13
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
+
exports.objectPrototypeMethodType = exports.OBJECT_PROTOTYPE_METHOD_NAMES = exports.builtinConstructorType = exports.inferMemberExpression = exports.trackModuleExports = exports.inferAssignmentExpression = exports.collectAllReturnTypes = exports.inferBlockReturnType = exports.checkUnionVsExpected = exports.tryDetectConditionalReturn = exports.bindFunctionParams = exports.inferFunctionExpression = exports.tryInferPrototypeMethodAssignment = exports.lookupConstraintMethod = exports.collectAllKvConstraintNames = exports.resolveKvConstraintNames = void 0;
|
|
15
|
+
exports.inferExpression = inferExpression;
|
|
16
|
+
exports.inferExpressionWithExpected = inferExpressionWithExpected;
|
|
17
|
+
exports.inferExpressionInner = inferExpressionInner;
|
|
18
|
+
exports.inferLiteral = inferLiteral;
|
|
19
|
+
exports.inferIdentifier = inferIdentifier;
|
|
20
|
+
exports.requireNumericOperands = requireNumericOperands;
|
|
21
|
+
exports.relateComparableOperands = relateComparableOperands;
|
|
22
|
+
exports.iterableElementType = iterableElementType;
|
|
23
|
+
exports.inferBinaryExpression = inferBinaryExpression;
|
|
24
|
+
exports.inferUnaryExpression = inferUnaryExpression;
|
|
25
|
+
exports.inferLogicalExpression = inferLogicalExpression;
|
|
26
|
+
exports.inferConditionalExpression = inferConditionalExpression;
|
|
27
|
+
exports.inferArrayExpression = inferArrayExpression;
|
|
28
|
+
exports.inferObjectExpression = inferObjectExpression;
|
|
29
|
+
const types_1 = require("../hm/types");
|
|
30
|
+
const env_1 = require("../hm/env");
|
|
31
|
+
const unify_1 = require("../hm/unify");
|
|
32
|
+
const methodRegistry_1 = require("../registries/methodRegistry");
|
|
33
|
+
const dataTypeRegistry_1 = require("../registries/dataTypeRegistry");
|
|
34
|
+
const constraintRegistry_1 = require("../registries/constraintRegistry");
|
|
35
|
+
const types_2 = require("../hm/types");
|
|
36
|
+
const typeUtils_1 = require("../hm/typeUtils");
|
|
37
|
+
const annotations_1 = require("./annotations");
|
|
38
|
+
const call_rows_1 = require("./call-rows");
|
|
39
|
+
const unifyDiag_1 = require("./unifyDiag");
|
|
40
|
+
const narrowing_1 = require("./narrowing");
|
|
41
|
+
const helpers_1 = require("./helpers");
|
|
42
|
+
const types_3 = require("./types");
|
|
43
|
+
const narrowing_2 = require("./narrowing");
|
|
44
|
+
const expr_functions_1 = require("./expr-functions");
|
|
45
|
+
const expr_assignment_1 = require("./expr-assignment");
|
|
46
|
+
const expr_member_1 = require("./expr-member");
|
|
47
|
+
const expr_jsx_1 = require("./expr-jsx");
|
|
48
|
+
// -----------------------------------------------------------------------
|
|
49
|
+
// Expressions
|
|
50
|
+
// -----------------------------------------------------------------------
|
|
51
|
+
function inferExpression(engine, node, env) {
|
|
52
|
+
return inferExpressionWithExpected(engine, node, env, undefined);
|
|
53
|
+
}
|
|
54
|
+
function inferExpressionWithExpected(engine, node, env, expectedType) {
|
|
55
|
+
const type = inferExpressionInner(engine, node, env, expectedType);
|
|
56
|
+
engine.recordNodeType(node, type);
|
|
57
|
+
return type;
|
|
58
|
+
}
|
|
59
|
+
function inferExpressionInner(engine, node, env, expectedType) {
|
|
60
|
+
switch (node.type) {
|
|
61
|
+
// --- Literals ---
|
|
62
|
+
case 'Literal':
|
|
63
|
+
return inferLiteral(engine, node, expectedType);
|
|
64
|
+
// --- Identifiers ---
|
|
65
|
+
case 'Identifier':
|
|
66
|
+
return inferIdentifier(engine, node, env, expectedType);
|
|
67
|
+
// --- Binary expressions ---
|
|
68
|
+
case 'BinaryExpression':
|
|
69
|
+
return inferBinaryExpression(engine, node, env);
|
|
70
|
+
// --- Unary expressions ---
|
|
71
|
+
case 'UnaryExpression':
|
|
72
|
+
return inferUnaryExpression(engine, node, env);
|
|
73
|
+
// --- Logical expressions ---
|
|
74
|
+
case 'LogicalExpression':
|
|
75
|
+
return inferLogicalExpression(engine, node, env);
|
|
76
|
+
// --- Function / Arrow functions ---
|
|
77
|
+
case 'ArrowFunctionExpression':
|
|
78
|
+
case 'FunctionExpression':
|
|
79
|
+
return (0, expr_functions_1.inferFunctionExpression)(engine, node, env, expectedType);
|
|
80
|
+
// --- Call expressions ---
|
|
81
|
+
case 'CallExpression': {
|
|
82
|
+
// CommonJS `require ("…")` used as an EXPRESSION (re-export barrels
|
|
83
|
+
// `module.exports = { RTask: require ("./RTask") }`, inline
|
|
84
|
+
// `require ("./x").prop`). Declaration forms (`const x = require …`)
|
|
85
|
+
// are handled in statements.ts; this mirrors their semantics.
|
|
86
|
+
// Without it, `require` was looked up as a plain variable and every
|
|
87
|
+
// barrel entry reported a misleading "Unbound variable: 'require'".
|
|
88
|
+
if ((0, narrowing_2.isRequireCall)(node) && !env.lookup('require')) {
|
|
89
|
+
return inferRequireExpression(engine, node);
|
|
90
|
+
}
|
|
91
|
+
// `m.get (k)` after `m.has (k)` (see `presentKeyMarker`): the key is
|
|
92
|
+
// there, so the lookup's `| Undefined` (a miss) goes. Inferred without
|
|
93
|
+
// the expected type, which the caller compares with the narrowed one.
|
|
94
|
+
{
|
|
95
|
+
const marker = (0, narrowing_2.getCallMarker)(node);
|
|
96
|
+
if (marker && env.lookup(marker)) {
|
|
97
|
+
const looked = engine.subst.apply(engine.inferCallExpression(node, env));
|
|
98
|
+
const present = (0, narrowing_2.filterUnion)(looked, m => !(m.tag === 'TCon' && m.name === 'Undefined' && m.args.length === 0));
|
|
99
|
+
engine.recordNodeType(node, present);
|
|
100
|
+
return present;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return engine.inferCallExpression(node, env, expectedType);
|
|
104
|
+
}
|
|
105
|
+
// --- New expressions (treated like call to constructor) ---
|
|
106
|
+
case 'NewExpression':
|
|
107
|
+
return engine.inferCallExpression(node, env, expectedType);
|
|
108
|
+
// --- Conditional (ternary) ---
|
|
109
|
+
case 'ConditionalExpression':
|
|
110
|
+
return inferConditionalExpression(engine, node, env, expectedType);
|
|
111
|
+
// --- Array expression ---
|
|
112
|
+
case 'ArrayExpression':
|
|
113
|
+
return inferArrayExpression(engine, node, env, expectedType);
|
|
114
|
+
// --- Object expression ---
|
|
115
|
+
case 'ObjectExpression':
|
|
116
|
+
return inferObjectExpression(engine, node, env, expectedType);
|
|
117
|
+
// --- Assignment ---
|
|
118
|
+
case 'AssignmentExpression':
|
|
119
|
+
return (0, expr_assignment_1.inferAssignmentExpression)(engine, node, env);
|
|
120
|
+
// --- Template literal — infer interpolated expressions ---
|
|
121
|
+
case 'TemplateLiteral': {
|
|
122
|
+
for (const expr of (node.expressions ?? [])) {
|
|
123
|
+
inferExpression(engine, expr, env);
|
|
124
|
+
}
|
|
125
|
+
return types_1.tString;
|
|
126
|
+
}
|
|
127
|
+
// --- Member expression (simplified) ---
|
|
128
|
+
case 'MemberExpression':
|
|
129
|
+
return (0, expr_member_1.inferMemberExpression)(engine, node, env);
|
|
130
|
+
// --- this expression ---
|
|
131
|
+
case 'ThisExpression': {
|
|
132
|
+
const thisScheme = env.lookup('this');
|
|
133
|
+
if (thisScheme) {
|
|
134
|
+
const t = (0, env_1.instantiate)(thisScheme);
|
|
135
|
+
// Rule #1: the signature wins. When `this` is bound to a method
|
|
136
|
+
// annotation's receiver (`Type a ~> ...`), freeze the receiver at this
|
|
137
|
+
// node so hover renders it with the signature's OWN variable letters
|
|
138
|
+
// instead of re-lettering from the enclosing method scope (which would
|
|
139
|
+
// turn `[a]` into `[b]`).
|
|
140
|
+
if (env.lookup('__signatureThis')) {
|
|
141
|
+
engine.frozenParamType.set(node.start, t);
|
|
142
|
+
}
|
|
143
|
+
return t;
|
|
144
|
+
}
|
|
145
|
+
return (0, types_1.tVar)();
|
|
146
|
+
}
|
|
147
|
+
// --- Update expression (i++, i--, ++i, --i) ---
|
|
148
|
+
case 'UpdateExpression': {
|
|
149
|
+
const argType = inferExpression(engine, node.argument, env);
|
|
150
|
+
engine.unifyWithDiagnostic(argType, types_1.tNumber, node);
|
|
151
|
+
return types_1.tNumber;
|
|
152
|
+
}
|
|
153
|
+
// --- Await expression: unwrap Promise<T> → T ---
|
|
154
|
+
case 'AwaitExpression':
|
|
155
|
+
return inferAwaitExpression(engine, node, env);
|
|
156
|
+
// --- Optional chaining: obj?.prop, obj?.[expr], obj?.() ---
|
|
157
|
+
case 'ChainExpression': {
|
|
158
|
+
// ChainExpression wraps a MemberExpression or CallExpression.
|
|
159
|
+
// We infer the inner expression as-is; we do NOT add Undefined to
|
|
160
|
+
// the result because optional-chaining semantics are handled at
|
|
161
|
+
// the property/call level and adding Undefined would cause noise.
|
|
162
|
+
const innerType = inferExpression(engine, node.expression, env);
|
|
163
|
+
return innerType;
|
|
164
|
+
}
|
|
165
|
+
// --- Sequence expression (comma operator): (a, b, c) → type of c ---
|
|
166
|
+
case 'SequenceExpression': {
|
|
167
|
+
let lastType = types_1.tVoid;
|
|
168
|
+
for (const expr of (node.expressions ?? [])) {
|
|
169
|
+
lastType = inferExpression(engine, expr, env);
|
|
170
|
+
}
|
|
171
|
+
return lastType;
|
|
172
|
+
}
|
|
173
|
+
// --- Class expression ---
|
|
174
|
+
case 'ClassExpression':
|
|
175
|
+
return inferClassExpression(engine, node, env);
|
|
176
|
+
// --- Tagged template expression ---
|
|
177
|
+
case 'TaggedTemplateExpression':
|
|
178
|
+
return inferTaggedTemplateExpression(engine, node, env);
|
|
179
|
+
// --- Yield expression ---
|
|
180
|
+
case 'YieldExpression': {
|
|
181
|
+
const yieldNode = node;
|
|
182
|
+
const argType = yieldNode.argument
|
|
183
|
+
? inferExpression(engine, yieldNode.argument, env)
|
|
184
|
+
: types_1.tUndefined;
|
|
185
|
+
// Record the yielded element type on the enclosing generator frame so
|
|
186
|
+
// `inferFunctionExpression` can model the function's result as
|
|
187
|
+
// `Generator <yield>`. `yield* iterable` delegates: the contributed
|
|
188
|
+
// element type is the iterable's element, not the iterable itself.
|
|
189
|
+
const frame = engine.generatorYieldStack[engine.generatorYieldStack.length - 1];
|
|
190
|
+
if (frame) {
|
|
191
|
+
frame.push(yieldNode.delegate ? iterableElementType(engine, argType) : argType);
|
|
192
|
+
}
|
|
193
|
+
// The *value* of a `yield`/`yield*` expression (what it evaluates to when
|
|
194
|
+
// the generator is resumed) is unknown to us — model it as a fresh var.
|
|
195
|
+
return (0, types_1.tVar)();
|
|
196
|
+
}
|
|
197
|
+
// --- MetaProperty: new.target, import.meta ---
|
|
198
|
+
case 'MetaProperty':
|
|
199
|
+
return (0, types_1.tVar)();
|
|
200
|
+
// --- Dynamic import: import('./mod') -> Promise<{...exports}> ---
|
|
201
|
+
case 'ImportExpression': {
|
|
202
|
+
const src = node.source;
|
|
203
|
+
// If the argument is a string literal we can resolve the module via the
|
|
204
|
+
// same import resolver used for static imports — this gives real
|
|
205
|
+
// completion / hover on `(await import('./mod')).foo`.
|
|
206
|
+
if (src && src.type === 'Literal' && typeof src.value === 'string' && engine.importResolver) {
|
|
207
|
+
const specifier = src.value;
|
|
208
|
+
const exportedBindings = engine.importResolver(specifier);
|
|
209
|
+
if (exportedBindings && !(0, types_3.isUntypedModule)(exportedBindings)) {
|
|
210
|
+
return (0, types_1.tCon)('Promise', [(0, types_1.tVar)(), (0, helpers_1.exportsToRecord)(exportedBindings)]);
|
|
211
|
+
}
|
|
212
|
+
if ((0, types_3.isUntypedModule)(exportedBindings)) {
|
|
213
|
+
return (0, types_1.tCon)('Promise', [(0, types_1.tVar)(), (0, types_1.tVar)()]);
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
// Fall back to inferring the argument (for diagnostics on non-string
|
|
217
|
+
// sources) and returning Promise<*> for unresolvable specifiers.
|
|
218
|
+
if (src)
|
|
219
|
+
inferExpression(engine, src, env);
|
|
220
|
+
return (0, types_1.tCon)('Promise', [(0, types_1.tVar)(), types_1.tAny]);
|
|
221
|
+
}
|
|
222
|
+
// --- JSX (parsed by the Babel backend; see expr-jsx.ts) ---
|
|
223
|
+
case 'JSXElement':
|
|
224
|
+
return (0, expr_jsx_1.inferJSXElement)(engine, node, env);
|
|
225
|
+
case 'JSXFragment':
|
|
226
|
+
return (0, expr_jsx_1.inferJSXFragment)(engine, node, env);
|
|
227
|
+
case 'JSXExpressionContainer':
|
|
228
|
+
// Reached only when a container is inferred directly (normally its
|
|
229
|
+
// inner expression is extracted by expr-jsx.ts first).
|
|
230
|
+
return node.expression.type === 'JSXEmptyExpression'
|
|
231
|
+
? types_1.tUndefined
|
|
232
|
+
: inferExpression(engine, node.expression, env);
|
|
233
|
+
case 'JSXText':
|
|
234
|
+
return types_1.tString;
|
|
235
|
+
default:
|
|
236
|
+
return (0, types_1.tVar)();
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
// -----------------------------------------------------------------------
|
|
240
|
+
// Expression helpers
|
|
241
|
+
// -----------------------------------------------------------------------
|
|
242
|
+
/** Await expression: unwrap Promise e a → a. */
|
|
243
|
+
function inferAwaitExpression(engine, node, env) {
|
|
244
|
+
const argType = inferExpression(engine, node.argument, env);
|
|
245
|
+
const resolved = engine.subst.apply(argType);
|
|
246
|
+
if (resolved.tag === 'TCon' && resolved.name === 'Promise' && resolved.args.length === 2) {
|
|
247
|
+
return resolved.args[1];
|
|
248
|
+
}
|
|
249
|
+
if (resolved.tag === 'TVar') {
|
|
250
|
+
const innerType = (0, types_1.tVar)();
|
|
251
|
+
engine.unifyWithDiagnostic(argType, (0, types_1.tCon)('Promise', [(0, types_1.tVar)(), innerType]), node);
|
|
252
|
+
return engine.subst.apply(innerType);
|
|
253
|
+
}
|
|
254
|
+
// JS allows awaiting non-promises
|
|
255
|
+
return resolved;
|
|
256
|
+
}
|
|
257
|
+
/** Class expression: return the constructor type. */
|
|
258
|
+
function inferClassExpression(engine, node, env) {
|
|
259
|
+
const classBody = node.body?.body ?? [];
|
|
260
|
+
const constructorMethod = (0, helpers_1.findConstructor)(classBody);
|
|
261
|
+
if (constructorMethod) {
|
|
262
|
+
return (0, expr_functions_1.inferFunctionExpression)(engine, constructorMethod.value, env);
|
|
263
|
+
}
|
|
264
|
+
return (0, types_1.tVar)();
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Tagged template expression — typed as the equivalent call
|
|
268
|
+
* `tag([...strings], ...expressions)`, mirroring the runtime semantics, when
|
|
269
|
+
* the tag's type is known and can absorb the interpolations. This is what
|
|
270
|
+
* makes annotated template tags (e.g. a query builder's
|
|
271
|
+
* `sql :: ([String], ...) -> SQLTag p o`) produce real result types and
|
|
272
|
+
* thread interpolation types into the tag's signature.
|
|
273
|
+
*
|
|
274
|
+
* Falls back to the historical behavior (infer interpolations for side
|
|
275
|
+
* effects, return a fresh var) when the tag is untyped or its arity cannot
|
|
276
|
+
* accept `strings + interpolations` — plain JS tag helpers often declare only
|
|
277
|
+
* `(strings)`, and routing those through the strict call path would produce
|
|
278
|
+
* spurious arity diagnostics.
|
|
279
|
+
*/
|
|
280
|
+
function inferTaggedTemplateExpression(engine, node, env) {
|
|
281
|
+
const exprs = node.quasi?.expressions ?? [];
|
|
282
|
+
const tagType = inferExpression(engine, node.tag, env);
|
|
283
|
+
const resolved = engine.subst.apply(tagType);
|
|
284
|
+
const branches = resolved.tag === 'TCon' && resolved.name === types_1.T_UNION
|
|
285
|
+
? resolved.args.map((a) => engine.subst.apply(a))
|
|
286
|
+
: [resolved];
|
|
287
|
+
const canRoute = branches.some((b) => {
|
|
288
|
+
if (b.tag !== 'TFun')
|
|
289
|
+
return false;
|
|
290
|
+
// Variadic tag `(a, ...) -> r`: absorbs any number of interpolations.
|
|
291
|
+
if (b.param.tag === 'TCon' && b.param.name === types_1.T_TUPLE) {
|
|
292
|
+
if (b.param.args.some(types_1.isSpread))
|
|
293
|
+
return true;
|
|
294
|
+
// Non-variadic tuples take all args at once — no partial application,
|
|
295
|
+
// so the arity must match exactly.
|
|
296
|
+
return b.param.args.length === 1 + exprs.length;
|
|
297
|
+
}
|
|
298
|
+
// Curried form: count parameter slots.
|
|
299
|
+
return (0, types_1.flattenCurriedType)(b).params.length >= 1 + exprs.length;
|
|
300
|
+
});
|
|
301
|
+
if (canRoute && node.quasi?.quasis) {
|
|
302
|
+
// Synthesize `tag(["s0", "s1", ...], e0, e1, ...)` with source positions
|
|
303
|
+
// taken from the real template parts so diagnostics land on the template.
|
|
304
|
+
const strings = node.quasi.quasis.map((q) => ({
|
|
305
|
+
type: 'Literal',
|
|
306
|
+
value: q.value?.cooked ?? '',
|
|
307
|
+
raw: JSON.stringify(q.value?.cooked ?? ''),
|
|
308
|
+
start: q.start,
|
|
309
|
+
end: q.end,
|
|
310
|
+
}));
|
|
311
|
+
const arrNode = {
|
|
312
|
+
type: 'ArrayExpression',
|
|
313
|
+
elements: strings,
|
|
314
|
+
start: node.quasi.start,
|
|
315
|
+
end: node.quasi.end,
|
|
316
|
+
};
|
|
317
|
+
const callNode = {
|
|
318
|
+
type: 'CallExpression',
|
|
319
|
+
callee: node.tag,
|
|
320
|
+
arguments: [arrNode, ...exprs],
|
|
321
|
+
optional: false,
|
|
322
|
+
start: node.start,
|
|
323
|
+
end: node.end,
|
|
324
|
+
};
|
|
325
|
+
const result = engine.inferCallExpression(callNode, env);
|
|
326
|
+
// Params threading for template tags: function interpolations
|
|
327
|
+
// (`sql\`... ${p => p.riziv} ...\``) contribute their accessed fields
|
|
328
|
+
// to the result's parameter slot, mirroring the selector-array
|
|
329
|
+
// harvest in call-rows.
|
|
330
|
+
(0, call_rows_1.harvestTaggedTemplateParams)(engine, env, callNode, result);
|
|
331
|
+
return result;
|
|
332
|
+
}
|
|
333
|
+
for (const expr of exprs) {
|
|
334
|
+
inferExpression(engine, expr, env);
|
|
335
|
+
}
|
|
336
|
+
return (0, types_1.tVar)();
|
|
337
|
+
}
|
|
338
|
+
function inferLiteral(engine, node, expectedType) {
|
|
339
|
+
const val = node.value;
|
|
340
|
+
if (typeof val === 'bigint')
|
|
341
|
+
return types_1.tBigInt;
|
|
342
|
+
if (typeof val === 'number') {
|
|
343
|
+
// Take the numeric literal type only where exactly that literal is
|
|
344
|
+
// expected (a `2 -> …` overload branch, or a union listing it).
|
|
345
|
+
if (expectedType) {
|
|
346
|
+
const lit = String(val);
|
|
347
|
+
const resolved = engine.resolve(expectedType);
|
|
348
|
+
if (resolved.tag === 'TCon' && resolved.args.length === 0 && (0, types_1.isNumLitName)(resolved.name)) {
|
|
349
|
+
return (0, types_1.tNumLit)(val);
|
|
350
|
+
}
|
|
351
|
+
if (resolved.tag === 'TCon' && resolved.name === types_1.T_UNION
|
|
352
|
+
&& resolved.args.some(m => { const r = engine.resolve(m); return r.tag === 'TCon' && r.name === lit; })) {
|
|
353
|
+
return (0, types_1.tNumLit)(val);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return types_1.tNumber;
|
|
357
|
+
}
|
|
358
|
+
if (typeof val === 'string') {
|
|
359
|
+
// Promote string literals to label literals when context demands it
|
|
360
|
+
// (e.g. as the label argument of a label-polymorphic function such as
|
|
361
|
+
// `drop2 :: k -> { [k] :: a, ...r } -> { ...r }`).
|
|
362
|
+
//
|
|
363
|
+
// Also promote when the expected position is a Union containing one
|
|
364
|
+
// or more TLabelLit members — this is what makes per-table selector
|
|
365
|
+
// unions work, e.g. `Foo :: ['id' | 'name' | Prop t a | ...] -> ...`
|
|
366
|
+
// accepts `"id"` by matching the label-lit branch of the union, and
|
|
367
|
+
// rejects `"naame"` because no TLabelLit branch matches and no other
|
|
368
|
+
// branch accepts a label. We promote unconditionally whenever there
|
|
369
|
+
// is *any* TLabelLit in the union (not only when one matches), so a
|
|
370
|
+
// typo like `"naame"` gets a real "Cannot unify" diagnostic instead
|
|
371
|
+
// of being silently absorbed via the TLabel↔String compat rule.
|
|
372
|
+
if (expectedType) {
|
|
373
|
+
const resolved = engine.resolve(expectedType);
|
|
374
|
+
if (resolved.tag === 'TLabel')
|
|
375
|
+
return (0, types_1.tLabelLit)(val);
|
|
376
|
+
if (resolved.tag === 'TCon' && resolved.name === types_1.T_UNION) {
|
|
377
|
+
let hasLit = false;
|
|
378
|
+
for (const arg of resolved.args) {
|
|
379
|
+
const m = engine.resolve(arg);
|
|
380
|
+
if (m.tag === 'TLabel' && m.kind === 'lit') {
|
|
381
|
+
hasLit = true;
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
if (hasLit)
|
|
386
|
+
return (0, types_1.tLabelLit)(val);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return types_1.tString;
|
|
390
|
+
}
|
|
391
|
+
if (typeof val === 'boolean')
|
|
392
|
+
return types_1.tBool;
|
|
393
|
+
if (val === null)
|
|
394
|
+
return types_1.tNull;
|
|
395
|
+
if (val instanceof RegExp)
|
|
396
|
+
return (0, types_1.tCon)('RegExp');
|
|
397
|
+
return types_1.tVoid;
|
|
398
|
+
}
|
|
399
|
+
/** True when type variable `id` carries a constraint of kind `* -> *`
|
|
400
|
+
* (Functor/Monad/… — the variable stands for a type constructor). */
|
|
401
|
+
function isHigherKindedVar(engine, id) {
|
|
402
|
+
const names = engine.kvConstraints.get(id) ?? [];
|
|
403
|
+
return names.some((n) => (0, constraintRegistry_1.lookupConstraint)((0, types_2.constraintBaseName)(n))?.expectedKind === '* -> *');
|
|
404
|
+
}
|
|
405
|
+
function inferIdentifier(engine, node, env, expectedType) {
|
|
406
|
+
const name = node.name;
|
|
407
|
+
if (name === 'undefined')
|
|
408
|
+
return types_1.tUndefined;
|
|
409
|
+
if (name === 'true' || name === 'false')
|
|
410
|
+
return types_1.tBool;
|
|
411
|
+
if (name === 'NaN' || name === 'Infinity')
|
|
412
|
+
return types_1.tNumber;
|
|
413
|
+
// A registered sumtype *carrier* (`function Maybe(){throw}`) referenced where
|
|
414
|
+
// a `TypeRep m` is expected acts as a *type representative witness*, exactly
|
|
415
|
+
// like a built-in constructor. Without this the carrier's inferred function
|
|
416
|
+
// type (`() -> ()`) reaches `unifyTypeRep`, whose return-type extraction pins
|
|
417
|
+
// `m = ()` (yielding a spurious `Cannot unify 'Maybe a' with '()'`). Guarded
|
|
418
|
+
// on an expected `TypeRep …` so member access (`Maybe.of`) and direct calls
|
|
419
|
+
// (`Maybe()`) — which carry no such expectation — keep the carrier binding.
|
|
420
|
+
if (expectedType && /^[A-Z]/.test(name) && (0, dataTypeRegistry_1.isDataType)(name)) {
|
|
421
|
+
const expected = engine.resolve(expectedType);
|
|
422
|
+
if (expected.tag === 'TCon' && expected.name === types_1.T_TYPEREP) {
|
|
423
|
+
// Apply the carrier to one fresh var per declared type parameter so the
|
|
424
|
+
// witness is at the same kind (`*`) as the values it will be compared
|
|
425
|
+
// against — e.g. `Maybe a`, not the bare `Maybe` (kind `* -> *`), which
|
|
426
|
+
// would clash with `Nothing :: Maybe a` on arity.
|
|
427
|
+
const dt = (0, dataTypeRegistry_1.getDataType)(name);
|
|
428
|
+
let args = dt ? dt.decl.typeVars.map(() => (0, types_1.tVar)()) : [];
|
|
429
|
+
// ...unless the representative stands for a higher-kinded variable
|
|
430
|
+
// (`TypeRep m` under `Monad m`, as in a monad-transformer factory
|
|
431
|
+
// `StateT (Either)`): then the witness is the constructor itself, one
|
|
432
|
+
// argument short (`Either e`), so `m (Pair a s)` re-applies it.
|
|
433
|
+
// Saturating it (`Either e a`) made `m (Pair a s)` ill-kinded.
|
|
434
|
+
const inner = engine.resolve(expected.args[0]);
|
|
435
|
+
if (inner.tag === 'TVar' && args.length > 0 && isHigherKindedVar(engine, inner.id)) {
|
|
436
|
+
args = args.slice(0, -1);
|
|
437
|
+
}
|
|
438
|
+
else if (inner.tag === 'TCon' && inner.name === name && inner.args.length < args.length) {
|
|
439
|
+
// The expected representative is already a (partial) application of
|
|
440
|
+
// this constructor — e.g. an annotation `TypeRep (FutureT (Either l) e)`
|
|
441
|
+
// flowed into `FutureT (Either)` and fixed `m := Either l` first.
|
|
442
|
+
// Match its arity instead of saturating.
|
|
443
|
+
args = args.slice(0, inner.args.length);
|
|
444
|
+
}
|
|
445
|
+
const witness = (0, types_1.tCon)(types_1.T_TYPEREP, [(0, types_1.tCon)(name, args)]);
|
|
446
|
+
engine.recordNodeType(node, witness);
|
|
447
|
+
return witness;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
const scheme = env.lookup(name);
|
|
451
|
+
if (!scheme) {
|
|
452
|
+
// A built-in type constructor referenced in value position (e.g.
|
|
453
|
+
// `id(Function)`, `of(String)`) acts as a *type representative witness*:
|
|
454
|
+
// the global object stands in for its type constructor. Give it the type
|
|
455
|
+
// `TypeRep <Name>` so it satisfies a `TypeRep f` parameter.
|
|
456
|
+
if (/^[A-Z]/.test(name) && (0, methodRegistry_1.isBuiltinType)(name)) {
|
|
457
|
+
// `Function` represents the reader functor `Function [x]` (one fixed
|
|
458
|
+
// argument type, like `Either e`), so `chainRec (Function)` yields an
|
|
459
|
+
// applied `Function [x] b` — a real function type.
|
|
460
|
+
if (name === types_1.T_FUNCTION)
|
|
461
|
+
return (0, types_1.tCon)(types_1.T_TYPEREP, [(0, types_1.tCon)(types_1.T_FUNCTION, [(0, types_1.tCon)(types_1.T_ARRAY, [(0, types_1.tVar)()])])]);
|
|
462
|
+
return (0, types_1.tCon)(types_1.T_TYPEREP, [(0, types_1.tCon)(name)]);
|
|
463
|
+
}
|
|
464
|
+
// A free identifier that has no binding but is declared as a value in the
|
|
465
|
+
// project globals file (e.g. a `jest.hm` declaring `describe :: ...`)
|
|
466
|
+
// resolves to that global signature. Only plain value annotations from
|
|
467
|
+
// the globals file qualify — method/receiver annotations (`Type#m`) and
|
|
468
|
+
// local annotations are excluded so this stays a genuine global binding.
|
|
469
|
+
const globalAnn = engine.annotationMap.get(name);
|
|
470
|
+
if (globalAnn && globalAnn.origin === 'globals' && globalAnn.scheme
|
|
471
|
+
&& !globalAnn.receiver && !globalAnn.error
|
|
472
|
+
&& !name.includes('#') && !name.includes('.')) {
|
|
473
|
+
const result = engine.instantiateWithConstraints(globalAnn.scheme, node);
|
|
474
|
+
engine.recordNodeType(node, result);
|
|
475
|
+
return result;
|
|
476
|
+
}
|
|
477
|
+
engine.addDiag(`Unbound variable: '${name}'`, node);
|
|
478
|
+
engine.unboundIdentifiers.add(node.start);
|
|
479
|
+
return (0, types_1.tVar)();
|
|
480
|
+
}
|
|
481
|
+
// Mark reference sites of curried variables so signature help can detect them
|
|
482
|
+
if (scheme.isCurriedResult) {
|
|
483
|
+
engine.curriedNodes.add(node.start);
|
|
484
|
+
}
|
|
485
|
+
const result = engine.instantiateWithConstraints(scheme, node);
|
|
486
|
+
engine.recordNodeType(node, result);
|
|
487
|
+
// A reference to an annotated parameter must display the signature form, not
|
|
488
|
+
// the body-poisoned substitution. The param's binding carries `frozenDisplay`
|
|
489
|
+
// (the annotation); control-flow narrowing rebinds the name via plain `mono`,
|
|
490
|
+
// dropping it, so a reference inside an accepted narrow still shows the
|
|
491
|
+
// narrowed type.
|
|
492
|
+
if (scheme.frozenDisplay) {
|
|
493
|
+
engine.frozenParamType.set(node.start, scheme.frozenDisplay);
|
|
494
|
+
}
|
|
495
|
+
return result;
|
|
496
|
+
}
|
|
497
|
+
/** Unify both operands of a numeric binary expression with Number. */
|
|
498
|
+
function requireNumericOperands(engine, left, right, node) {
|
|
499
|
+
engine.unifyWithDiagnostic(left, types_1.tNumber, node.left);
|
|
500
|
+
engine.unifyWithDiagnostic(right, types_1.tNumber, node.right);
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Relational operators (`<`, `>`, `<=`, `>=`) in JS are not Number-only: they
|
|
504
|
+
* also compare Strings lexicographically (and, via valueOf, other ordered
|
|
505
|
+
* values). We therefore do NOT force the operands to Number. Instead we make
|
|
506
|
+
* the two sides agree with each other (so beneficial inference still flows),
|
|
507
|
+
* but SWALLOW a unification failure the same way `===` does — a heterogeneous
|
|
508
|
+
* comparison is legal JS and must not raise a type error. This fixes
|
|
509
|
+
* `String <= String` wrongly reporting `Cannot unify 'String' with 'Number'`.
|
|
510
|
+
*/
|
|
511
|
+
function relateComparableOperands(engine, left, right) {
|
|
512
|
+
try {
|
|
513
|
+
engine.subst.mergeFrom((0, unify_1.unify)(engine.resolve(left), engine.resolve(right)));
|
|
514
|
+
}
|
|
515
|
+
catch (e) {
|
|
516
|
+
if (!(e instanceof unify_1.UnificationError))
|
|
517
|
+
throw e;
|
|
518
|
+
// Heterogeneous comparison — no diagnostic.
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Element type of an iterable value type, used for `yield* iterable` and
|
|
523
|
+
* `for…of`. Arrays / typed-array-likes / Generator / Set expose their element
|
|
524
|
+
* as their single type argument; a String iterates over Strings; anything else
|
|
525
|
+
* contributes a fresh variable so inference stays permissive.
|
|
526
|
+
*/
|
|
527
|
+
function iterableElementType(engine, t) {
|
|
528
|
+
const r = engine.subst.apply(t);
|
|
529
|
+
if (r.tag === 'TCon') {
|
|
530
|
+
if (r.name === types_1.T_STRING)
|
|
531
|
+
return types_1.tString;
|
|
532
|
+
if (r.args.length === 1)
|
|
533
|
+
return r.args[0];
|
|
534
|
+
}
|
|
535
|
+
return (0, types_1.tVar)();
|
|
536
|
+
}
|
|
537
|
+
function inferBinaryExpression(engine, node, env) {
|
|
538
|
+
const left = inferExpression(engine, node.left, env);
|
|
539
|
+
const right = inferExpression(engine, node.right, env);
|
|
540
|
+
const op = node.operator;
|
|
541
|
+
switch (op) {
|
|
542
|
+
// Arithmetic
|
|
543
|
+
case '+': {
|
|
544
|
+
// + is polymorphic in JS:
|
|
545
|
+
// String + any = String (concatenation)
|
|
546
|
+
// any + String = String (concatenation)
|
|
547
|
+
// Number + Number = Number (arithmetic)
|
|
548
|
+
const resolvedLeft = engine.subst.apply(left);
|
|
549
|
+
const resolvedRight = engine.subst.apply(right);
|
|
550
|
+
if ((resolvedLeft.tag === 'TCon' && resolvedLeft.name === types_1.T_STRING) ||
|
|
551
|
+
(resolvedRight.tag === 'TCon' && resolvedRight.name === types_1.T_STRING)) {
|
|
552
|
+
// At least one side is String → result is String (JS coercion)
|
|
553
|
+
return types_1.tString;
|
|
554
|
+
}
|
|
555
|
+
// Otherwise default to number addition
|
|
556
|
+
requireNumericOperands(engine, left, right, node);
|
|
557
|
+
return types_1.tNumber;
|
|
558
|
+
}
|
|
559
|
+
case '-':
|
|
560
|
+
case '*':
|
|
561
|
+
case '/':
|
|
562
|
+
case '%':
|
|
563
|
+
case '**':
|
|
564
|
+
requireNumericOperands(engine, left, right, node);
|
|
565
|
+
return types_1.tNumber;
|
|
566
|
+
// Strict equality — JS reference/value equality is heterogeneous: any two
|
|
567
|
+
// values may be compared (e.g. comparing a value of type `(* -> a)` with
|
|
568
|
+
// one of type `(* -> b)`, or two distinct rigid skolems). We attempt to
|
|
569
|
+
// unify the operands so that beneficial inference still happens (e.g.
|
|
570
|
+
// `s === ""` refines `s` to String), but we SWALLOW a unification failure
|
|
571
|
+
// instead of reporting a mismatch. This stays sound w.r.t. type-class
|
|
572
|
+
// constraints: constraints are validated post-hoc against each variable's
|
|
573
|
+
// resolved concrete type (see validatePendingConstraints), not by unify,
|
|
574
|
+
// so a swallowed structural failure can never hide a constraint diagnostic.
|
|
575
|
+
case '===':
|
|
576
|
+
case '!==':
|
|
577
|
+
try {
|
|
578
|
+
engine.subst.mergeFrom((0, unify_1.unify)(engine.resolve(left), engine.resolve(right)));
|
|
579
|
+
}
|
|
580
|
+
catch (e) {
|
|
581
|
+
if (!(e instanceof unify_1.UnificationError))
|
|
582
|
+
throw e;
|
|
583
|
+
// Heterogeneous comparison — no diagnostic.
|
|
584
|
+
}
|
|
585
|
+
return types_1.tBool;
|
|
586
|
+
// Loose equality — JS allows comparing any two values with coercion,
|
|
587
|
+
// so we do NOT unify the operands.
|
|
588
|
+
case '==':
|
|
589
|
+
case '!=':
|
|
590
|
+
return types_1.tBool;
|
|
591
|
+
case '<':
|
|
592
|
+
case '>':
|
|
593
|
+
case '<=':
|
|
594
|
+
case '>=':
|
|
595
|
+
relateComparableOperands(engine, left, right);
|
|
596
|
+
return types_1.tBool;
|
|
597
|
+
// Bitwise
|
|
598
|
+
case '|':
|
|
599
|
+
case '&':
|
|
600
|
+
case '^':
|
|
601
|
+
case '<<':
|
|
602
|
+
case '>>':
|
|
603
|
+
case '>>>':
|
|
604
|
+
requireNumericOperands(engine, left, right, node);
|
|
605
|
+
return types_1.tNumber;
|
|
606
|
+
// instanceof operator
|
|
607
|
+
case 'instanceof':
|
|
608
|
+
return types_1.tBool;
|
|
609
|
+
// in operator (key in object)
|
|
610
|
+
case 'in':
|
|
611
|
+
return types_1.tBool;
|
|
612
|
+
default:
|
|
613
|
+
return (0, types_1.tVar)();
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
function inferUnaryExpression(engine, node, env) {
|
|
617
|
+
const arg = inferExpression(engine, node.argument, env);
|
|
618
|
+
switch (node.operator) {
|
|
619
|
+
case '-':
|
|
620
|
+
case '+':
|
|
621
|
+
case '~':
|
|
622
|
+
engine.unifyWithDiagnostic(arg, types_1.tNumber, node.argument);
|
|
623
|
+
return types_1.tNumber;
|
|
624
|
+
case '!':
|
|
625
|
+
return types_1.tBool; // ! always returns Boolean, argument can be any type
|
|
626
|
+
case 'typeof':
|
|
627
|
+
return types_1.tString;
|
|
628
|
+
case 'void':
|
|
629
|
+
return types_1.tVoid;
|
|
630
|
+
case 'delete':
|
|
631
|
+
return types_1.tBool;
|
|
632
|
+
default:
|
|
633
|
+
return (0, types_1.tVar)();
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
function inferLogicalExpression(engine, node, env) {
|
|
637
|
+
const left = inferExpression(engine, node.left, env);
|
|
638
|
+
const op = node.operator;
|
|
639
|
+
if (op === '??') {
|
|
640
|
+
// Nullish coalescing: left ?? right — see `defaultedType`.
|
|
641
|
+
const right = inferExpression(engine, node.right, env);
|
|
642
|
+
return defaultedType(engine, node.left, left, right);
|
|
643
|
+
}
|
|
644
|
+
if (op === '||') {
|
|
645
|
+
// Logical OR: left || right.
|
|
646
|
+
// When `left` is a bare identifier, narrow it for `right`'s env to its
|
|
647
|
+
// falsy refinement, and compute the result as `truthyLeft | right` (so
|
|
648
|
+
// `value || "x"` where value :: String | Undefined returns String,
|
|
649
|
+
// not String | Undefined). Identifier-LHS only to avoid the
|
|
650
|
+
// typeof/null cascade surprises seen in `typeof x === 'object' && x !== null`.
|
|
651
|
+
if (node.left.type === 'Identifier') {
|
|
652
|
+
const narrowed = (0, narrowing_1.computeNarrowedEnvs)(engine.subst, node.left, env, engine.annotationMap);
|
|
653
|
+
const right = inferExpression(engine, node.right, narrowed.altEnv);
|
|
654
|
+
const truthyScheme = narrowed.consEnv.lookup(node.left.name);
|
|
655
|
+
const truthyLeft = truthyScheme ? engine.subst.apply(truthyScheme.type) : left;
|
|
656
|
+
return (0, types_1.tUnion)([truthyLeft, right]);
|
|
657
|
+
}
|
|
658
|
+
const right = inferExpression(engine, node.right, narrowForOrRight(engine, node.left, env));
|
|
659
|
+
return defaultedType(engine, node.left, left, right);
|
|
660
|
+
}
|
|
661
|
+
if (op === '&&') {
|
|
662
|
+
// Logical AND: left && right
|
|
663
|
+
// When `left` is a bare identifier, narrow it (e.g. remove Undefined
|
|
664
|
+
// from a union) in the env used to infer `right`. Only Identifier-LHS
|
|
665
|
+
// is narrowed here — see comment on `||` above.
|
|
666
|
+
const rightEnv = narrowForAndRight(engine, node.left, env);
|
|
667
|
+
const right = inferExpression(engine, node.right, rightEnv);
|
|
668
|
+
return right;
|
|
669
|
+
}
|
|
670
|
+
inferExpression(engine, node.right, env);
|
|
671
|
+
return types_1.tBool;
|
|
672
|
+
}
|
|
673
|
+
/**
|
|
674
|
+
* Result of a default expression `left ?? right` / `left || right` (the
|
|
675
|
+
* latter for a non-identifier left; identifiers are narrowed above).
|
|
676
|
+
* - `left` is an unknown FIELD (`p.from`, still a type variable): the field
|
|
677
|
+
* becomes optional, `right | Undefined`, and the result is `right`. A
|
|
678
|
+
* default says the field may be absent and what type it has —
|
|
679
|
+
* `startsAt.gte (p => p.from ?? new Date ())` gives `from :: Date |
|
|
680
|
+
* Undefined`, and `p => p.from || 2` makes the `2` meet the `Date` the
|
|
681
|
+
* callback must return, instead of disappearing;
|
|
682
|
+
* - otherwise `Undefined`/`Null` are dropped from `left` and the result is
|
|
683
|
+
* `left | right` (both may be returned at runtime).
|
|
684
|
+
*/
|
|
685
|
+
function defaultedType(engine, leftNode, left, right) {
|
|
686
|
+
const l = engine.resolve(left);
|
|
687
|
+
const r = engine.resolve(right);
|
|
688
|
+
if (l.tag === 'TVar' && leftNode.type === 'MemberExpression') {
|
|
689
|
+
try {
|
|
690
|
+
engine.subst.mergeFrom((0, unify_1.unify)(l, (0, types_1.tUnion)([r, types_1.tUndefined])));
|
|
691
|
+
return r;
|
|
692
|
+
}
|
|
693
|
+
catch { /* fall through to the union */ }
|
|
694
|
+
}
|
|
695
|
+
const present = stripNullish(l);
|
|
696
|
+
if (present === null)
|
|
697
|
+
return r;
|
|
698
|
+
// `Any | x` is `Any`: an unknown left side may be returned as is.
|
|
699
|
+
if ((0, types_1.isAnyType)(present) || (0, types_1.isAnyType)(r))
|
|
700
|
+
return types_1.tAnyType;
|
|
701
|
+
try {
|
|
702
|
+
const s = (0, unify_1.unify)(present, r);
|
|
703
|
+
engine.subst.mergeFrom(s);
|
|
704
|
+
return engine.resolve(r);
|
|
705
|
+
}
|
|
706
|
+
catch {
|
|
707
|
+
return (0, typeUtils_1.mergeUnion)(present, r);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
/** `t` without `Undefined`/`Null` members; null when nothing remains. */
|
|
711
|
+
function stripNullish(t) {
|
|
712
|
+
const isNullish = (x) => x.tag === 'TCon' && (x.name === 'Undefined' || x.name === 'Null');
|
|
713
|
+
if (isNullish(t))
|
|
714
|
+
return null;
|
|
715
|
+
if (t.tag !== 'TCon' || t.name !== types_1.T_UNION)
|
|
716
|
+
return t;
|
|
717
|
+
const kept = t.args.filter(a => !isNullish(a));
|
|
718
|
+
if (kept.length === 0)
|
|
719
|
+
return null;
|
|
720
|
+
return kept.length === 1 ? kept[0] : (0, types_1.tUnion)(kept);
|
|
721
|
+
}
|
|
722
|
+
/** A string literal, or a ternary whose branches all are (`ok ? "success"
|
|
723
|
+
* : failed ? "danger" : "primary"`): such an expression meets an expected
|
|
724
|
+
* literal union with its literals. */
|
|
725
|
+
function isStringLiteralChoice(node) {
|
|
726
|
+
if (node.type === 'Literal')
|
|
727
|
+
return typeof node.value === 'string';
|
|
728
|
+
if (node.type !== 'ConditionalExpression')
|
|
729
|
+
return false;
|
|
730
|
+
const c = node;
|
|
731
|
+
return isStringLiteralChoice(c.consequent) && isStringLiteralChoice(c.alternate);
|
|
732
|
+
}
|
|
733
|
+
function inferConditionalExpression(engine, node, env, expectedType) {
|
|
734
|
+
inferExpression(engine, node.test, env);
|
|
735
|
+
const { consEnv, altEnv } = (0, narrowing_1.computeNarrowedEnvs)(engine.subst, node.test, env, engine.annotationMap);
|
|
736
|
+
// A string-literal branch gets the expected type, so
|
|
737
|
+
// `paint (ok ? "success" : "danger")` meets a literal union with its
|
|
738
|
+
// literals (other branches keep their own inference).
|
|
739
|
+
const branch = (b, branchEnv) => expectedType && isStringLiteralChoice(b)
|
|
740
|
+
? inferExpressionWithExpected(engine, b, branchEnv, expectedType)
|
|
741
|
+
: inferExpression(engine, b, branchEnv);
|
|
742
|
+
const consType = branch(node.consequent, consEnv);
|
|
743
|
+
const altType = branch(node.alternate, altEnv);
|
|
744
|
+
try {
|
|
745
|
+
const s = (0, unify_1.unify)(engine.resolve(consType), engine.resolve(altType));
|
|
746
|
+
engine.subst.mergeFrom(s);
|
|
747
|
+
// Unification also succeeds when one branch is a MEMBER of the other's
|
|
748
|
+
// union (`c ? null : f (x)` with `f x :: String | Null`): the result is
|
|
749
|
+
// then the union, not the narrower branch.
|
|
750
|
+
const rc = engine.resolve(consType);
|
|
751
|
+
const ra = engine.resolve(altType);
|
|
752
|
+
const isUnionT = (t) => t.tag === 'TCon' && t.name === types_1.T_UNION;
|
|
753
|
+
if ((isUnionT(rc) || isUnionT(ra)) && !(0, typeUtils_1.structuralEquals)(rc, ra))
|
|
754
|
+
return (0, typeUtils_1.mergeUnion)(rc, ra);
|
|
755
|
+
return consType;
|
|
756
|
+
}
|
|
757
|
+
catch (e) {
|
|
758
|
+
if (e instanceof unify_1.UnificationError) {
|
|
759
|
+
const rc = engine.resolve(consType);
|
|
760
|
+
const ra = engine.resolve(altType);
|
|
761
|
+
// Try merging same-name parameterized types before falling back to flat union
|
|
762
|
+
const merged = (0, typeUtils_1.mergeSameConstructor)(rc, ra);
|
|
763
|
+
if (merged)
|
|
764
|
+
return merged;
|
|
765
|
+
return (0, typeUtils_1.mergeUnion)(rc, ra);
|
|
766
|
+
}
|
|
767
|
+
throw e;
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
function hasSpreadElementBelow(node) {
|
|
771
|
+
for (const e of node.elements) {
|
|
772
|
+
if (e !== null && e.type === 'SpreadElement')
|
|
773
|
+
return true;
|
|
774
|
+
}
|
|
775
|
+
return false;
|
|
776
|
+
}
|
|
777
|
+
function inferArrayExpression(engine, node, env, expectedType) {
|
|
778
|
+
// annotation so that elements unify against the expected element type
|
|
779
|
+
// rather than each other. This allows annotated union element types
|
|
780
|
+
// like [Either String (Number | String)] even when auto-union is
|
|
781
|
+
// suppressed during annotation checking.
|
|
782
|
+
let elemType;
|
|
783
|
+
const resolved = expectedType ? engine.subst.apply(expectedType) : undefined;
|
|
784
|
+
// If the expected type is `Any` (e.g. the array is an argument to a
|
|
785
|
+
// call whose callee resolved to `Any`, as happens when destructuring
|
|
786
|
+
// from a fully opaque source like `tables.organisation`), each element
|
|
787
|
+
// is checked independently against `Any` instead of being unified
|
|
788
|
+
// against a shared element TVar. Without this, mixed-shape literals
|
|
789
|
+
// such as `[Limit(5), "id", Prop("name")]` would fail because the
|
|
790
|
+
// first element's type would pin the shared element slot.
|
|
791
|
+
if (resolved && (0, types_1.isAnyType)(resolved)) {
|
|
792
|
+
for (const elem of node.elements) {
|
|
793
|
+
if (elem)
|
|
794
|
+
inferExpressionWithExpected(engine, elem, env, types_1.tAny);
|
|
795
|
+
}
|
|
796
|
+
engine.recordNodeType(node, (0, types_1.tArray)(types_1.tAny));
|
|
797
|
+
return (0, types_1.tArray)(types_1.tAny);
|
|
798
|
+
}
|
|
799
|
+
// Positional spread-array expected: [a, b, ..., z] or [a, b]
|
|
800
|
+
// Each array literal element gets the corresponding positional type so
|
|
801
|
+
// mixed-type literals like ["3", 3] match [String, Number].
|
|
802
|
+
if (resolved && resolved.tag === 'TCon' && resolved.name === types_1.T_SPREAD_ARRAY) {
|
|
803
|
+
const expArgs = resolved.args;
|
|
804
|
+
const spreadIdx = expArgs.findIndex(types_1.isSpread);
|
|
805
|
+
const before = spreadIdx >= 0 ? expArgs.slice(0, spreadIdx) : expArgs.slice();
|
|
806
|
+
const after = spreadIdx >= 0 ? expArgs.slice(spreadIdx + 1) : [];
|
|
807
|
+
const elements = node.elements;
|
|
808
|
+
const totalElems = elements.length;
|
|
809
|
+
// Arity check
|
|
810
|
+
if (spreadIdx < 0) {
|
|
811
|
+
// Fixed positional: must match exactly
|
|
812
|
+
if (totalElems !== before.length) {
|
|
813
|
+
engine.addDiag(`Array literal has ${totalElems} element${totalElems === 1 ? '' : 's'}, expected ${before.length} for type '${(0, types_1.typeToString)(resolved)}'`, node);
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
else {
|
|
817
|
+
// With spread: must have at least before+after elements
|
|
818
|
+
const minRequired = before.length + after.length;
|
|
819
|
+
if (totalElems < minRequired) {
|
|
820
|
+
engine.addDiag(`Array literal has ${totalElems} element${totalElems === 1 ? '' : 's'}, expected at least ${minRequired} for type '${(0, types_1.typeToString)(resolved)}'`, node);
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
for (let i = 0; i < totalElems; i++) {
|
|
824
|
+
const elem = elements[i];
|
|
825
|
+
if (!elem)
|
|
826
|
+
continue;
|
|
827
|
+
let expectedElem;
|
|
828
|
+
if (i < before.length) {
|
|
829
|
+
expectedElem = before[i];
|
|
830
|
+
}
|
|
831
|
+
else if (spreadIdx >= 0) {
|
|
832
|
+
const idxFromEnd = totalElems - 1 - i;
|
|
833
|
+
if (idxFromEnd >= 0 && idxFromEnd < after.length) {
|
|
834
|
+
expectedElem = after[after.length - 1 - idxFromEnd];
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
const t = expectedElem
|
|
838
|
+
? inferExpressionWithExpected(engine, elem, env, expectedElem)
|
|
839
|
+
: inferExpression(engine, elem, env);
|
|
840
|
+
if (expectedElem) {
|
|
841
|
+
engine.unifyWithDiagnostic(t, expectedElem, elem);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
// Build a representative Array type for hover/display: pick the first
|
|
845
|
+
// non-spread element type, freshened so we don't alias the annotation.
|
|
846
|
+
const firstNonSpread = expArgs.find(a => !(0, types_1.isSpread)(a));
|
|
847
|
+
const arrayElemType = firstNonSpread ? (0, typeUtils_1.freshenType)(firstNonSpread) : (0, types_1.tVar)();
|
|
848
|
+
engine.recordNodeType(node, (0, types_1.tArray)(engine.subst.apply(arrayElemType)));
|
|
849
|
+
// Return the resolved SpreadArray type so it unifies with the param slot
|
|
850
|
+
// at the call site (Array<X> would not unify with SpreadArray<...>).
|
|
851
|
+
return engine.subst.apply(resolved);
|
|
852
|
+
}
|
|
853
|
+
// Track the original (un-expanded) element type so the array literal's
|
|
854
|
+
// returned type uses the alias name (`[Selector]`) when one was provided
|
|
855
|
+
// — element-by-element unification still happens against the expanded
|
|
856
|
+
// union to allow heterogeneous element types.
|
|
857
|
+
let originalElemType;
|
|
858
|
+
let aliasWasExpanded = false;
|
|
859
|
+
// When the expected element type is (or expands to) a Union containing
|
|
860
|
+
// free TVars (e.g. `Prop a | QueryTag a | Table b | ...` from a per-table
|
|
861
|
+
// Selector alias), freshen those TVars per element so distinct elements
|
|
862
|
+
// can match distinct branches with distinct type-arg bindings. This
|
|
863
|
+
// covers two cases:
|
|
864
|
+
// • alias still in TCon form (handled via maybeExpandAlias)
|
|
865
|
+
// • alias eagerly expanded into the annotation already (we must
|
|
866
|
+
// freshen the expanded union ourselves per element)
|
|
867
|
+
let unionWithFreeVars = false;
|
|
868
|
+
if (resolved && resolved.tag === 'TCon' && resolved.name === types_1.T_ARRAY && resolved.args.length === 1) {
|
|
869
|
+
originalElemType = resolved.args[0];
|
|
870
|
+
elemType = resolved.args[0];
|
|
871
|
+
// If the expected element type is a zero-arg type alias (e.g.
|
|
872
|
+
// `[Selector]` where `Selector :: String | Prop a | ...`), expand
|
|
873
|
+
// it so element unification sees the underlying union and can
|
|
874
|
+
// accept heterogeneous element types.
|
|
875
|
+
const expanded = engine.maybeExpandAlias(elemType);
|
|
876
|
+
if (expanded !== elemType)
|
|
877
|
+
aliasWasExpanded = true;
|
|
878
|
+
elemType = expanded;
|
|
879
|
+
// Union element types can carry alias *members* (e.g.
|
|
880
|
+
// `[UserSelector | Limit p]` where `UserSelector :: "id" | "name"`),
|
|
881
|
+
// and generators emit parameterized aliases (`[UserSelector p]`).
|
|
882
|
+
// `maybeExpandAlias` only expands bare zero-arg aliases, so expand the
|
|
883
|
+
// remaining alias references here. Free vars introduced by the
|
|
884
|
+
// expansion are picked up by the `unionWithFreeVars` detection below
|
|
885
|
+
// (per-element freshening with result-pinned vars kept shared).
|
|
886
|
+
if (elemType.tag === 'TCon' &&
|
|
887
|
+
(elemType.name === types_1.T_UNION || elemType.args.length > 0)) {
|
|
888
|
+
const hasAliasRef = (0, typeUtils_1.someType)(elemType, (n) => n.tag === 'TCon' && n.name !== types_1.T_UNION && engine.typeAliases.has(n.name));
|
|
889
|
+
if (hasAliasRef) {
|
|
890
|
+
const fullyExpanded = (0, annotations_1.expandAliases)(engine.typeAliases, elemType, undefined, engine.typeAliasVars);
|
|
891
|
+
if (fullyExpanded !== elemType) {
|
|
892
|
+
// Re-flatten in case an alias member expanded into a nested union.
|
|
893
|
+
elemType = fullyExpanded.tag === 'TCon' && fullyExpanded.name === types_1.T_UNION
|
|
894
|
+
? (0, types_1.tUnion)(fullyExpanded.args)
|
|
895
|
+
: fullyExpanded;
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
// Detect the eagerly-expanded case: the resolved element type is
|
|
900
|
+
// already a Union containing free TVars (parameter slot was expanded
|
|
901
|
+
// by `expandAnnotationAliases` before instantiation, so the
|
|
902
|
+
// alias-freshening code path above never fires).
|
|
903
|
+
if (!aliasWasExpanded && elemType.tag === 'TCon' && elemType.name === types_1.T_UNION) {
|
|
904
|
+
const ids = new Map();
|
|
905
|
+
(0, types_1.collectVarNames)(elemType, ids);
|
|
906
|
+
// Only freshen TVars that aren't bound in the current substitution
|
|
907
|
+
// (i.e. genuinely free at this use site).
|
|
908
|
+
let hasFree = false;
|
|
909
|
+
for (const id of ids.keys()) {
|
|
910
|
+
if (engine.subst.lookup(id) === undefined) {
|
|
911
|
+
hasFree = true;
|
|
912
|
+
break;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
if (hasFree)
|
|
916
|
+
unionWithFreeVars = true;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
else {
|
|
920
|
+
elemType = (0, types_1.tVar)();
|
|
921
|
+
}
|
|
922
|
+
// Detect the "expected element type is a free TVar" case (e.g. callee
|
|
923
|
+
// signature `[b]` with b unbound). When that holds, allow the array
|
|
924
|
+
// literal to have heterogeneous element types: collect each element's
|
|
925
|
+
// inferred type and bind the TVar to a union of those types in one
|
|
926
|
+
// shot. Otherwise the per-element unification against the shared
|
|
927
|
+
// `elemType` would pin it to the first element's type and reject every
|
|
928
|
+
// subsequent element of a different type — even though `b` was free
|
|
929
|
+
// and could legitimately be a union. Constraint validation against a
|
|
930
|
+
// resolved TUnion is enforced separately in
|
|
931
|
+
// `validatePendingUnionConstraints` (every member must satisfy the
|
|
932
|
+
// constraint, not just one).
|
|
933
|
+
let elemTypeIsFreeTVar = false;
|
|
934
|
+
if (resolved && !aliasWasExpanded && !unionWithFreeVars) {
|
|
935
|
+
const pruned = engine.subst.apply(elemType);
|
|
936
|
+
if (pruned.tag === 'TVar') {
|
|
937
|
+
elemTypeIsFreeTVar = true;
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
// No-expected-type fallback widening (cross-tag mixes): when the array
|
|
941
|
+
// has no expected element type and no spread element (a spread imports
|
|
942
|
+
// its element type from a typed source whose stricter type should be
|
|
943
|
+
// honoured by the surrounding literal — see the
|
|
944
|
+
// `Class##field annotation enforces type at private assignment site`
|
|
945
|
+
// regression test), enable a try/rollback strategy below: do the
|
|
946
|
+
// strict per-element unify first to give the existing auto-union /
|
|
947
|
+
// mergeSameConstructor logic a chance to merge cleanly; if any
|
|
948
|
+
// diagnostic fires from that pass, roll back the substitution and the
|
|
949
|
+
// emitted diagnostics, then bind elemType to the union of inferred
|
|
950
|
+
// element types (cross-tag widening like `[1, [2,3]]` →
|
|
951
|
+
// `[Number | [Number]]`, `[function(){}, 1]` → `[Number | (() -> ())]`).
|
|
952
|
+
const tryNoExpectedWidening = !resolved && !hasSpreadElementBelow(node);
|
|
953
|
+
const substSnapshot = tryNoExpectedWidening ? engine.subst.snapshot() : null;
|
|
954
|
+
// Indices of diagnostics emitted by the per-element `unifyWithDiagnostic`
|
|
955
|
+
// below. Only THOSE are rolled back by the cross-tag widening pass:
|
|
956
|
+
// diagnostics emitted while inferring the elements themselves (e.g. a
|
|
957
|
+
// missing-field error inside a nested call like `[f(), g({})]`) are
|
|
958
|
+
// genuine and must survive the rollback.
|
|
959
|
+
const unifyDiagIndices = [];
|
|
960
|
+
// First pass: infer each element and collect resolved types so we can
|
|
961
|
+
// merge heterogeneous closed-record element shapes below. The plain
|
|
962
|
+
// element-by-element unification with a shared `elemType` is lenient
|
|
963
|
+
// for closed records (only common keys are unified), which means the
|
|
964
|
+
// callback in `[{a, b}, {a, c}].map(x => …)` would see `x :: { a }`
|
|
965
|
+
// and the surplus fields disappear. We post-process the literal to
|
|
966
|
+
// merge all field names across element records, with `T | Undefined`
|
|
967
|
+
// for fields that are missing from at least one element — matching JS
|
|
968
|
+
// runtime semantics where missing keys read as `undefined`.
|
|
969
|
+
const elemTypes = [];
|
|
970
|
+
for (const elem of node.elements) {
|
|
971
|
+
if (elem) {
|
|
972
|
+
// For element-type unions originating from an expanded alias
|
|
973
|
+
// (e.g. `Selector :: String | Prop a | ...`), re-instantiate fresh
|
|
974
|
+
// type variables for each element so distinct elements can match
|
|
975
|
+
// distinct branches with distinct type-arg bindings (e.g. one
|
|
976
|
+
// element matches `Prop String`, another `Prop Number`).
|
|
977
|
+
const perElemExpected = aliasWasExpanded && originalElemType
|
|
978
|
+
? engine.maybeExpandAlias(originalElemType)
|
|
979
|
+
: unionWithFreeVars
|
|
980
|
+
? (0, typeUtils_1.freshenType)(elemType, engine.pinnedElementVarIds ?? undefined)
|
|
981
|
+
: elemType;
|
|
982
|
+
// Only forward the expected element type into inference for
|
|
983
|
+
// *literal* elements — those are the ones that can be promoted
|
|
984
|
+
// (e.g. a string literal becoming a TLabelLit when the expected
|
|
985
|
+
// element type contains a label-literal). Forwarding the expected
|
|
986
|
+
// type into arbitrary expressions (call sites, identifiers) would
|
|
987
|
+
// over-constrain return-type unification (cf. auto-union of
|
|
988
|
+
// `[WLeft("foo"), WRight(10), WRight("bar")]`).
|
|
989
|
+
// A ternary of literals (`flag ? "id" : "name"`, also nested) gets it too.
|
|
990
|
+
const isLiteralElem = elem.type === 'Literal' || isStringLiteralChoice(elem);
|
|
991
|
+
// Skip forwarding the (free) shared TVar to literal inference too —
|
|
992
|
+
// it would just bind the TVar to the first literal's type and then
|
|
993
|
+
// the next literal would fail unification against it.
|
|
994
|
+
const t = isLiteralElem && !elemTypeIsFreeTVar
|
|
995
|
+
? inferExpressionWithExpected(engine, elem, env, perElemExpected)
|
|
996
|
+
: inferExpression(engine, elem, env);
|
|
997
|
+
if (!elemTypeIsFreeTVar) {
|
|
998
|
+
const beforeUnify = engine.diagnostics.length;
|
|
999
|
+
engine.unifyWithDiagnostic(t, perElemExpected, elem);
|
|
1000
|
+
// An element of a list with an expected type must fit it, in that
|
|
1001
|
+
// direction (a `String` is not one of `'id' | 'name'`), as a call
|
|
1002
|
+
// argument must.
|
|
1003
|
+
if (resolved && engine.diagnostics.length === beforeUnify) {
|
|
1004
|
+
const outside = (0, unifyDiag_1.argumentOutsideParameter)(engine, t, perElemExpected);
|
|
1005
|
+
if (outside)
|
|
1006
|
+
engine.addDiag(outside, elem);
|
|
1007
|
+
}
|
|
1008
|
+
if (tryNoExpectedWidening) {
|
|
1009
|
+
for (let i = beforeUnify; i < engine.diagnostics.length; i++) {
|
|
1010
|
+
unifyDiagIndices.push(i);
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
elemTypes.push(engine.subst.apply(t));
|
|
1015
|
+
}
|
|
1016
|
+
else {
|
|
1017
|
+
elemTypes.push(types_1.tUndefined);
|
|
1018
|
+
}
|
|
1019
|
+
}
|
|
1020
|
+
// Free-TVar widening: bind the parameter's element TVar to the union
|
|
1021
|
+
// of inferred element types, deduped structurally. When all elements
|
|
1022
|
+
// agree this is a no-op (single-member unions degrade to that member);
|
|
1023
|
+
// when they differ, the TVar resolves to `T1 | T2 | ...`.
|
|
1024
|
+
if (elemTypeIsFreeTVar && elemTypes.length > 0) {
|
|
1025
|
+
const unique = [];
|
|
1026
|
+
for (const et of elemTypes) {
|
|
1027
|
+
if (!unique.some(u => (0, typeUtils_1.structuralEquals)(u, et)))
|
|
1028
|
+
unique.push(et);
|
|
1029
|
+
}
|
|
1030
|
+
const widened = unique.length === 1 ? unique[0] : (0, types_1.tUnion)(unique);
|
|
1031
|
+
engine.unifyWithDiagnostic(elemType, widened, node);
|
|
1032
|
+
}
|
|
1033
|
+
// Cross-tag widening (no expected type, no spread): if the strict
|
|
1034
|
+
// per-element unification above produced one or more diagnostics
|
|
1035
|
+
// (e.g. `[1, [2,3]]` → "Cannot unify '[Number]' with 'Number'"), roll
|
|
1036
|
+
// back the substitution and the emitted diagnostics, then bind elemType
|
|
1037
|
+
// to the union of inferred element types so the literal types as
|
|
1038
|
+
// `[Number | [Number]]` instead. Annotated arrays are protected: the
|
|
1039
|
+
// `tryNoExpectedWidening` flag is false when an expected type is in
|
|
1040
|
+
// play, and a spread element disables widening so annotation-derived
|
|
1041
|
+
// element types still get strict-checked against sibling literals
|
|
1042
|
+
// (cf. the `Class##field` regression test).
|
|
1043
|
+
if (tryNoExpectedWidening && substSnapshot &&
|
|
1044
|
+
unifyDiagIndices.length > 0) {
|
|
1045
|
+
engine.subst.restore(substSnapshot);
|
|
1046
|
+
for (let i = unifyDiagIndices.length - 1; i >= 0; i--) {
|
|
1047
|
+
engine.diagnostics.splice(unifyDiagIndices[i], 1);
|
|
1048
|
+
}
|
|
1049
|
+
// Re-resolve element types under the rolled-back substitution.
|
|
1050
|
+
const widenedElems = elemTypes.map(t => engine.subst.apply(t));
|
|
1051
|
+
const unique = [];
|
|
1052
|
+
for (const et of widenedElems) {
|
|
1053
|
+
if (!unique.some(u => (0, typeUtils_1.structuralEquals)(u, et)))
|
|
1054
|
+
unique.push(et);
|
|
1055
|
+
}
|
|
1056
|
+
const widened = unique.length === 1 ? unique[0] : (0, types_1.tUnion)(unique);
|
|
1057
|
+
engine.unifyWithDiagnostic(elemType, widened, node);
|
|
1058
|
+
// Refresh elemTypes so the closed-record-merge pass below sees the
|
|
1059
|
+
// post-rollback shapes.
|
|
1060
|
+
elemTypes.splice(0, elemTypes.length, ...widenedElems);
|
|
1061
|
+
}
|
|
1062
|
+
// Try to merge closed-record element shapes when the array literal
|
|
1063
|
+
// mixes records with differing field sets. Only kicks in when:
|
|
1064
|
+
// • there's no expected element type (otherwise the expectation wins)
|
|
1065
|
+
// • there are >= 2 elements all resolving to closed TRecords
|
|
1066
|
+
// • the field-name sets are not all identical
|
|
1067
|
+
if (!resolved && elemTypes.length >= 2) {
|
|
1068
|
+
const allClosedRecords = elemTypes.every(t => t.tag === 'TRecord' && !t.rest);
|
|
1069
|
+
if (allClosedRecords) {
|
|
1070
|
+
const records = elemTypes;
|
|
1071
|
+
const allKeys = new Set();
|
|
1072
|
+
for (const r of records)
|
|
1073
|
+
for (const k of Object.keys(r.fields))
|
|
1074
|
+
allKeys.add(k);
|
|
1075
|
+
const sameShape = records.every(r => {
|
|
1076
|
+
const ks = Object.keys(r.fields);
|
|
1077
|
+
return ks.length === allKeys.size && ks.every(k => allKeys.has(k));
|
|
1078
|
+
});
|
|
1079
|
+
if (!sameShape) {
|
|
1080
|
+
const mergedFields = {};
|
|
1081
|
+
for (const k of allKeys) {
|
|
1082
|
+
const present = [];
|
|
1083
|
+
let missing = false;
|
|
1084
|
+
for (const r of records) {
|
|
1085
|
+
if (k in r.fields)
|
|
1086
|
+
present.push(engine.subst.apply(r.fields[k]));
|
|
1087
|
+
else
|
|
1088
|
+
missing = true;
|
|
1089
|
+
}
|
|
1090
|
+
// Deduplicate present types so `String | String` stays `String`.
|
|
1091
|
+
const valueType = present.length === 1 ? present[0] : (0, types_1.tUnion)(present);
|
|
1092
|
+
mergedFields[k] = missing ? (0, types_1.tUnion)([valueType, types_1.tUndefined]) : valueType;
|
|
1093
|
+
}
|
|
1094
|
+
const merged = (0, types_1.tRecord)(mergedFields);
|
|
1095
|
+
// Replace elemType so the array's element type carries the merged
|
|
1096
|
+
// shape — used by Array.prototype.map, hover, and completion.
|
|
1097
|
+
elemType = merged;
|
|
1098
|
+
// Re-record each element node's type under the merged shape so
|
|
1099
|
+
// hovering an inline literal also shows the unified view.
|
|
1100
|
+
for (let i = 0; i < node.elements.length; i++) {
|
|
1101
|
+
const e = node.elements[i];
|
|
1102
|
+
if (e)
|
|
1103
|
+
engine.recordNodeType(e, merged);
|
|
1104
|
+
}
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
const finalElem = originalElemType ?? engine.subst.apply(elemType);
|
|
1109
|
+
// An empty array literal `[]` carries no element information. Flag its
|
|
1110
|
+
// (unbound) element var as `emptyArray` so (1) union dedup can collapse
|
|
1111
|
+
// members differing only in such a var (see `TVar.emptyArray`), and (2) a
|
|
1112
|
+
// strict-empty array annotation `[]` accepts this literal. Applies whether
|
|
1113
|
+
// or not an expected element type was present (the expected var, if any, is
|
|
1114
|
+
// a throwaway fresh var of this instantiation).
|
|
1115
|
+
if (node.elements.length === 0 && finalElem.tag === 'TVar') {
|
|
1116
|
+
finalElem.emptyArray = true;
|
|
1117
|
+
}
|
|
1118
|
+
return (0, types_1.tArray)(finalElem);
|
|
1119
|
+
}
|
|
1120
|
+
function inferObjectExpression(engine, node, env, expectedType) {
|
|
1121
|
+
// Rank-N: when the expected (annotated) record declares a `forall` field,
|
|
1122
|
+
// the corresponding literal property must be checked by SUBSUMPTION — a
|
|
1123
|
+
// plain unify would silently instantiate the quantifier and accept a
|
|
1124
|
+
// monomorphic value. Resolve the expected record once up-front.
|
|
1125
|
+
// Perf: `containsForall` is a cheap allocation-free scan that guards the
|
|
1126
|
+
// substitution/alias work, so the rank-1 hot path pays one tag walk and no
|
|
1127
|
+
// allocations. (A `forall` field hidden behind an unexpanded alias TCon is
|
|
1128
|
+
// not seen here and falls back to the lenient legacy unify path.)
|
|
1129
|
+
let expectedRecord;
|
|
1130
|
+
if (expectedType && (0, types_1.containsForall)(expectedType)) {
|
|
1131
|
+
const resolvedExpected = engine.maybeExpandAlias(engine.subst.apply(expectedType));
|
|
1132
|
+
if (resolvedExpected.tag === 'TRecord'
|
|
1133
|
+
&& Object.values(resolvedExpected.fields).some(f => engine.subst.apply(f).tag === 'TForall')) {
|
|
1134
|
+
expectedRecord = resolvedExpected;
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
// Inline function values (`{ render: () => … }`, a JSX child callback)
|
|
1138
|
+
// get the expected field type, like an inline function argument does: a
|
|
1139
|
+
// callback that ignores trailing parameters is fine in JS, and the
|
|
1140
|
+
// function-literal inference pads it to the expected shape. Resolved
|
|
1141
|
+
// lazily, only when a property value is a function literal.
|
|
1142
|
+
let expectedFields;
|
|
1143
|
+
const expectedFunctionField = (key) => {
|
|
1144
|
+
if (!expectedType)
|
|
1145
|
+
return undefined;
|
|
1146
|
+
if (expectedFields === undefined) {
|
|
1147
|
+
const r = engine.maybeExpandAlias(engine.subst.apply(expectedType));
|
|
1148
|
+
expectedFields = r.tag === 'TRecord' ? r.fields : null;
|
|
1149
|
+
}
|
|
1150
|
+
if (!expectedFields || !(key in expectedFields))
|
|
1151
|
+
return undefined;
|
|
1152
|
+
const field = engine.subst.apply(expectedFields[key]);
|
|
1153
|
+
if (field.tag === 'TFun')
|
|
1154
|
+
return field;
|
|
1155
|
+
// An optional callback (`(a -> b) | Undefined`): its single function member.
|
|
1156
|
+
if (field.tag === 'TCon' && field.name === types_1.T_UNION) {
|
|
1157
|
+
const fns = field.args.filter(a => engine.subst.apply(a).tag === 'TFun');
|
|
1158
|
+
if (fns.length === 1)
|
|
1159
|
+
return engine.subst.apply(fns[0]);
|
|
1160
|
+
}
|
|
1161
|
+
return undefined;
|
|
1162
|
+
};
|
|
1163
|
+
// A string literal value gets the expected field type when that type
|
|
1164
|
+
// lists string literals (`intent :: Intent | Undefined` with
|
|
1165
|
+
// `Intent :: "none" | "primary" | …`), like a literal argument does:
|
|
1166
|
+
// `{ intent: "succes" }` is then a typo, not a `String`. Aliases inside
|
|
1167
|
+
// the union are expanded so `inferLiteral` sees the literal members.
|
|
1168
|
+
const expectedLiteralField = (key) => {
|
|
1169
|
+
if (!expectedType)
|
|
1170
|
+
return undefined;
|
|
1171
|
+
if (expectedFields === undefined) {
|
|
1172
|
+
const r = engine.maybeExpandAlias(engine.subst.apply(expectedType));
|
|
1173
|
+
expectedFields = r.tag === 'TRecord' ? r.fields : null;
|
|
1174
|
+
}
|
|
1175
|
+
if (!expectedFields || !(key in expectedFields))
|
|
1176
|
+
return undefined;
|
|
1177
|
+
const members = [];
|
|
1178
|
+
const collect = (t, depth) => {
|
|
1179
|
+
const r = engine.maybeExpandAlias(engine.subst.apply(t));
|
|
1180
|
+
if (depth < 4 && r.tag === 'TCon' && r.name === types_1.T_UNION) {
|
|
1181
|
+
for (const a of r.args)
|
|
1182
|
+
collect(a, depth + 1);
|
|
1183
|
+
}
|
|
1184
|
+
else {
|
|
1185
|
+
members.push(r);
|
|
1186
|
+
}
|
|
1187
|
+
};
|
|
1188
|
+
collect(expectedFields[key], 0);
|
|
1189
|
+
if (!members.some(m => m.tag === 'TLabel' && m.kind === 'lit'))
|
|
1190
|
+
return undefined;
|
|
1191
|
+
return (0, types_1.tUnion)(members);
|
|
1192
|
+
};
|
|
1193
|
+
// A nested object literal gets the expected field type when that is a
|
|
1194
|
+
// record (or `Record | Undefined`), like an object literal argument does
|
|
1195
|
+
// (`drawerProps={{ position: "left", onClose: () => close () }}`): its
|
|
1196
|
+
// callbacks then get their parameter types and its string literals the
|
|
1197
|
+
// literal union.
|
|
1198
|
+
const expectedRecordField = (key) => {
|
|
1199
|
+
if (!expectedType)
|
|
1200
|
+
return undefined;
|
|
1201
|
+
if (expectedFields === undefined) {
|
|
1202
|
+
const r = engine.maybeExpandAlias(engine.subst.apply(expectedType));
|
|
1203
|
+
expectedFields = r.tag === 'TRecord' ? r.fields : null;
|
|
1204
|
+
}
|
|
1205
|
+
if (!expectedFields || !(key in expectedFields))
|
|
1206
|
+
return undefined;
|
|
1207
|
+
const field = engine.maybeExpandAlias(engine.subst.apply(expectedFields[key]));
|
|
1208
|
+
if (field.tag === 'TRecord')
|
|
1209
|
+
return field;
|
|
1210
|
+
if (field.tag === 'TCon' && field.name === types_1.T_UNION) {
|
|
1211
|
+
const records = field.args
|
|
1212
|
+
.map(a => engine.maybeExpandAlias(engine.subst.apply(a)))
|
|
1213
|
+
.filter(a => a.tag === 'TRecord');
|
|
1214
|
+
if (records.length === 1)
|
|
1215
|
+
return records[0];
|
|
1216
|
+
}
|
|
1217
|
+
return undefined;
|
|
1218
|
+
};
|
|
1219
|
+
const fields = {};
|
|
1220
|
+
const labelFields = [];
|
|
1221
|
+
// Open rows contributed by spreading open records (`{...a}`, `{a}`) or
|
|
1222
|
+
// pre-existing Merge markers. Preserving them keeps a spread of open
|
|
1223
|
+
// records OPEN — `{ ...x, ...y }` where x,y are `{...a}`/`{...b}` becomes
|
|
1224
|
+
// `Merge a b` (matching the annotation `{ ...a, ...b }`) instead of
|
|
1225
|
+
// collapsing to a closed `{}`.
|
|
1226
|
+
const openRows = [];
|
|
1227
|
+
let hiddenFields;
|
|
1228
|
+
const mergeField = (k, incoming) => {
|
|
1229
|
+
const prior = fields[k];
|
|
1230
|
+
if (prior) {
|
|
1231
|
+
const stripped = (0, expr_assignment_1.stripUndefinedFromUnion)(incoming);
|
|
1232
|
+
if (stripped !== incoming) {
|
|
1233
|
+
fields[k] = stripped;
|
|
1234
|
+
return;
|
|
1235
|
+
}
|
|
1236
|
+
const priorR = engine.subst.apply(prior);
|
|
1237
|
+
const incomingR = engine.subst.apply(incoming);
|
|
1238
|
+
fields[k] = (0, types_1.deepMergeTypes)(priorR, incomingR);
|
|
1239
|
+
return;
|
|
1240
|
+
}
|
|
1241
|
+
fields[k] = incoming;
|
|
1242
|
+
};
|
|
1243
|
+
// Absorb one spread source into fields / labelFields / openRows.
|
|
1244
|
+
const absorbSpread = (part) => {
|
|
1245
|
+
if (part.tag === 'TRecord') {
|
|
1246
|
+
// Special case: prior concrete field + incoming `T | Undefined` (the
|
|
1247
|
+
// "key may be missing" marker) — an absent key is not copied by spread,
|
|
1248
|
+
// so the prior value wins. Handled inside mergeField via stripUndefined.
|
|
1249
|
+
for (const k in part.fields)
|
|
1250
|
+
mergeField(k, part.fields[k]);
|
|
1251
|
+
if (part.labelFields)
|
|
1252
|
+
for (const lf of part.labelFields)
|
|
1253
|
+
labelFields.push(lf);
|
|
1254
|
+
if (part.rest)
|
|
1255
|
+
openRows.push(part.rest);
|
|
1256
|
+
return;
|
|
1257
|
+
}
|
|
1258
|
+
if (part.tag === 'TCon' && part.name === types_1.T_MERGE) {
|
|
1259
|
+
for (const arg of part.args)
|
|
1260
|
+
absorbSpread(engine.subst.apply(arg));
|
|
1261
|
+
return;
|
|
1262
|
+
}
|
|
1263
|
+
if (part.tag === 'TRow' || part.tag === 'TVar') {
|
|
1264
|
+
openRows.push(part);
|
|
1265
|
+
}
|
|
1266
|
+
};
|
|
1267
|
+
// A copy of one value (`{ ...props }`, a JSX `<Comp {...props} />`) has the
|
|
1268
|
+
// type of that value, also when it is a type variable (`props :: p`);
|
|
1269
|
+
// absorbing it into a record lost it (`{}`).
|
|
1270
|
+
if (node.properties.length === 1 && node.properties[0].type === 'SpreadElement') {
|
|
1271
|
+
const only = engine.subst.apply(inferExpression(engine, node.properties[0].argument, env));
|
|
1272
|
+
if (only.tag !== 'TRecord' && !(only.tag === 'TCon' && only.name === types_1.T_MERGE)) {
|
|
1273
|
+
engine.recordNodeType(node, only);
|
|
1274
|
+
return only;
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
for (const prop of node.properties) {
|
|
1278
|
+
if (prop.type === 'SpreadElement') {
|
|
1279
|
+
// Spread in object: { ...obj, x: 1 }
|
|
1280
|
+
const spreadType = inferExpression(engine, prop.argument, env);
|
|
1281
|
+
const resolved = engine.subst.apply(spreadType);
|
|
1282
|
+
// Only records (closed or open) and Merge markers contribute structure;
|
|
1283
|
+
// a bare spread of an unknown type variable is left untouched, matching
|
|
1284
|
+
// the previous behaviour.
|
|
1285
|
+
if (resolved.tag === 'TRecord' || (resolved.tag === 'TCon' && resolved.name === types_1.T_MERGE)) {
|
|
1286
|
+
absorbSpread(resolved);
|
|
1287
|
+
}
|
|
1288
|
+
continue;
|
|
1289
|
+
}
|
|
1290
|
+
if (prop.type === 'Property') {
|
|
1291
|
+
let keyName = null;
|
|
1292
|
+
if (prop.key.type === 'Literal') {
|
|
1293
|
+
keyName = String(prop.key.value);
|
|
1294
|
+
}
|
|
1295
|
+
else if (prop.key.type === 'Identifier' && !prop.computed) {
|
|
1296
|
+
keyName = prop.key.name;
|
|
1297
|
+
}
|
|
1298
|
+
// Computed key `{ [expr]: value }`: the key is the VALUE of `expr`. A
|
|
1299
|
+
// literal type names the field, a label variable makes a label field,
|
|
1300
|
+
// anything else is a key known only at runtime (a fresh label: the
|
|
1301
|
+
// record is a dictionary for it).
|
|
1302
|
+
if (prop.computed && !keyName) {
|
|
1303
|
+
const keyType = engine.subst.apply(inferExpression(engine, prop.key, env));
|
|
1304
|
+
const literal = keyType.tag === 'TLabel' && keyType.kind === 'lit'
|
|
1305
|
+
? keyType.value
|
|
1306
|
+
: keyType.tag === 'TCon' && keyType.stringLiteral !== undefined ? keyType.stringLiteral : null;
|
|
1307
|
+
if (literal !== null) {
|
|
1308
|
+
keyName = literal;
|
|
1309
|
+
}
|
|
1310
|
+
else if (node.properties.length === 1 && (keyType.tag === 'TVar'
|
|
1311
|
+
|| (keyType.tag === 'TCon' && keyType.args.length === 0
|
|
1312
|
+
&& (keyType.name === 'String' || keyType.name === 'Number')))) {
|
|
1313
|
+
// The usual form, `{ [key]: value }` with a runtime key (a String, a
|
|
1314
|
+
// Number, or a key of a type not known yet): a dictionary, which
|
|
1315
|
+
// `Object.assign` and spreads merge as such.
|
|
1316
|
+
const valueType = inferExpression(engine, prop.value, env);
|
|
1317
|
+
const dict = (0, types_1.tCon)('Object', [(0, types_1.tCon)('String'), valueType]);
|
|
1318
|
+
engine.recordNodeType(prop, valueType);
|
|
1319
|
+
engine.recordNodeType(node, dict);
|
|
1320
|
+
return dict;
|
|
1321
|
+
}
|
|
1322
|
+
else {
|
|
1323
|
+
const valueType = inferExpression(engine, prop.value, env);
|
|
1324
|
+
const label = keyType.tag === 'TLabel' ? keyType : (0, types_1.tLabelVar)();
|
|
1325
|
+
labelFields.push({ label, type: valueType });
|
|
1326
|
+
engine.recordNodeType(prop, valueType);
|
|
1327
|
+
continue;
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
if (prop.computed && !keyName) {
|
|
1331
|
+
inferExpression(engine, prop.key, env);
|
|
1332
|
+
inferExpression(engine, prop.value, env);
|
|
1333
|
+
continue;
|
|
1334
|
+
}
|
|
1335
|
+
if (keyName) {
|
|
1336
|
+
const expectedField = expectedRecord && expectedRecord.tag === 'TRecord'
|
|
1337
|
+
? expectedRecord.fields[keyName] && engine.subst.apply(expectedRecord.fields[keyName])
|
|
1338
|
+
: undefined;
|
|
1339
|
+
if (expectedField && expectedField.tag === 'TForall') {
|
|
1340
|
+
// Polymorphic field: check the value against the skolemized body
|
|
1341
|
+
// and keep the quantifier on the field so the record still matches
|
|
1342
|
+
// the annotation.
|
|
1343
|
+
engine.inferRankNArgument(prop.value, env, expectedField, new Set());
|
|
1344
|
+
fields[keyName] = expectedField;
|
|
1345
|
+
engine.recordNodeType(prop, expectedField);
|
|
1346
|
+
continue;
|
|
1347
|
+
}
|
|
1348
|
+
const isFunctionLiteral = prop.value.type === 'ArrowFunctionExpression' || prop.value.type === 'FunctionExpression';
|
|
1349
|
+
const functionField = isFunctionLiteral ? expectedFunctionField(keyName) : undefined;
|
|
1350
|
+
const isStringLiteral = isStringLiteralChoice(prop.value);
|
|
1351
|
+
const literalField = isStringLiteral ? expectedLiteralField(keyName) : undefined;
|
|
1352
|
+
const recordField = prop.value.type === 'ObjectExpression' ? expectedRecordField(keyName) : undefined;
|
|
1353
|
+
const valueType = functionField
|
|
1354
|
+
? engine.inferExpressionWithExpected(prop.value, env, functionField)
|
|
1355
|
+
: literalField
|
|
1356
|
+
? (prop.value.type === 'Literal'
|
|
1357
|
+
? inferLiteral(engine, prop.value, literalField)
|
|
1358
|
+
: engine.inferExpressionWithExpected(prop.value, env, literalField))
|
|
1359
|
+
: recordField
|
|
1360
|
+
? engine.inferExpressionWithExpected(prop.value, env, recordField)
|
|
1361
|
+
: inferExpression(engine, prop.value, env);
|
|
1362
|
+
if (literalField)
|
|
1363
|
+
engine.recordNodeType(prop.value, valueType);
|
|
1364
|
+
// Standalone `// ::hidden` directive above this property: still
|
|
1365
|
+
// include the field in the record so structural unification at
|
|
1366
|
+
// call sites accepts callers that require it, but record the name
|
|
1367
|
+
// in `hiddenFields` so completion/hover suppress it.
|
|
1368
|
+
fields[keyName] = valueType;
|
|
1369
|
+
if ((0, methodRegistry_1.isHiddenPropertyOffset)(prop.start)) {
|
|
1370
|
+
if (!hiddenFields)
|
|
1371
|
+
hiddenFields = new Set();
|
|
1372
|
+
hiddenFields.add(keyName);
|
|
1373
|
+
}
|
|
1374
|
+
engine.recordNodeType(prop, valueType);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
}
|
|
1378
|
+
const hasConcrete = Object.keys(fields).length > 0 || labelFields.length > 0;
|
|
1379
|
+
const buildRecord = (rest) => {
|
|
1380
|
+
const out = rest ? (0, types_1.tOpenRecord)(fields, rest) : (0, types_1.tRecord)(fields);
|
|
1381
|
+
if (labelFields.length > 0)
|
|
1382
|
+
out.labelFields = labelFields;
|
|
1383
|
+
if (hiddenFields)
|
|
1384
|
+
out.hiddenFields = hiddenFields;
|
|
1385
|
+
return out;
|
|
1386
|
+
};
|
|
1387
|
+
let rec;
|
|
1388
|
+
if (openRows.length === 0) {
|
|
1389
|
+
rec = buildRecord();
|
|
1390
|
+
}
|
|
1391
|
+
else if (openRows.length === 1) {
|
|
1392
|
+
rec = buildRecord(openRows[0]);
|
|
1393
|
+
}
|
|
1394
|
+
else {
|
|
1395
|
+
// Two or more open rows: mirror the annotation parser's lowering of
|
|
1396
|
+
// `{ ...a, ...b }` to `Merge a b` so the body type matches the
|
|
1397
|
+
// declared return type. A leading concrete record carries any
|
|
1398
|
+
// fixed fields/labels.
|
|
1399
|
+
const args = [];
|
|
1400
|
+
if (hasConcrete)
|
|
1401
|
+
args.push(buildRecord());
|
|
1402
|
+
for (const r of openRows)
|
|
1403
|
+
args.push(r);
|
|
1404
|
+
rec = (0, types_1.tCon)(types_1.T_MERGE, args);
|
|
1405
|
+
}
|
|
1406
|
+
return rec;
|
|
1407
|
+
}
|
|
1408
|
+
// --- Constraint-method dispatch moved to ./expr-constraint-lookup ---
|
|
1409
|
+
var expr_constraint_lookup_1 = require("./expr-constraint-lookup");
|
|
1410
|
+
Object.defineProperty(exports, "resolveKvConstraintNames", { enumerable: true, get: function () { return expr_constraint_lookup_1.resolveKvConstraintNames; } });
|
|
1411
|
+
Object.defineProperty(exports, "collectAllKvConstraintNames", { enumerable: true, get: function () { return expr_constraint_lookup_1.collectAllKvConstraintNames; } });
|
|
1412
|
+
Object.defineProperty(exports, "lookupConstraintMethod", { enumerable: true, get: function () { return expr_constraint_lookup_1.lookupConstraintMethod; } });
|
|
1413
|
+
// --- Prototype method assignment moved to ./expr-prototype ---
|
|
1414
|
+
var expr_prototype_1 = require("./expr-prototype");
|
|
1415
|
+
Object.defineProperty(exports, "tryInferPrototypeMethodAssignment", { enumerable: true, get: function () { return expr_prototype_1.tryInferPrototypeMethodAssignment; } });
|
|
1416
|
+
// --- Function-expression inference moved to ./expr-functions ---
|
|
1417
|
+
var expr_functions_2 = require("./expr-functions");
|
|
1418
|
+
Object.defineProperty(exports, "inferFunctionExpression", { enumerable: true, get: function () { return expr_functions_2.inferFunctionExpression; } });
|
|
1419
|
+
Object.defineProperty(exports, "bindFunctionParams", { enumerable: true, get: function () { return expr_functions_2.bindFunctionParams; } });
|
|
1420
|
+
Object.defineProperty(exports, "tryDetectConditionalReturn", { enumerable: true, get: function () { return expr_functions_2.tryDetectConditionalReturn; } });
|
|
1421
|
+
Object.defineProperty(exports, "checkUnionVsExpected", { enumerable: true, get: function () { return expr_functions_2.checkUnionVsExpected; } });
|
|
1422
|
+
Object.defineProperty(exports, "inferBlockReturnType", { enumerable: true, get: function () { return expr_functions_2.inferBlockReturnType; } });
|
|
1423
|
+
Object.defineProperty(exports, "collectAllReturnTypes", { enumerable: true, get: function () { return expr_functions_2.collectAllReturnTypes; } });
|
|
1424
|
+
// --- Assignment-expression inference moved to ./expr-assignment ---
|
|
1425
|
+
var expr_assignment_2 = require("./expr-assignment");
|
|
1426
|
+
Object.defineProperty(exports, "inferAssignmentExpression", { enumerable: true, get: function () { return expr_assignment_2.inferAssignmentExpression; } });
|
|
1427
|
+
Object.defineProperty(exports, "trackModuleExports", { enumerable: true, get: function () { return expr_assignment_2.trackModuleExports; } });
|
|
1428
|
+
// --- Member-expression inference moved to ./expr-member ---
|
|
1429
|
+
var expr_member_2 = require("./expr-member");
|
|
1430
|
+
Object.defineProperty(exports, "inferMemberExpression", { enumerable: true, get: function () { return expr_member_2.inferMemberExpression; } });
|
|
1431
|
+
Object.defineProperty(exports, "builtinConstructorType", { enumerable: true, get: function () { return expr_member_2.builtinConstructorType; } });
|
|
1432
|
+
Object.defineProperty(exports, "OBJECT_PROTOTYPE_METHOD_NAMES", { enumerable: true, get: function () { return expr_member_2.OBJECT_PROTOTYPE_METHOD_NAMES; } });
|
|
1433
|
+
Object.defineProperty(exports, "objectPrototypeMethodType", { enumerable: true, get: function () { return expr_member_2.objectPrototypeMethodType; } });
|
|
1434
|
+
/**
|
|
1435
|
+
* Type of a `require ("specifier")` expression: the module's runtime value.
|
|
1436
|
+
* CommonJS `module.exports = X` modules expose that value as their `default`
|
|
1437
|
+
* export; otherwise the value is the record of all named exports. An untyped
|
|
1438
|
+
* module yields the opaque `Any`; an unresolvable specifier reports
|
|
1439
|
+
* "Cannot resolve module" on the specifier (and yields `Any` so the error
|
|
1440
|
+
* does not cascade into unrelated "unbound" diagnostics).
|
|
1441
|
+
*/
|
|
1442
|
+
function inferRequireExpression(engine, node) {
|
|
1443
|
+
const arg = node.arguments[0];
|
|
1444
|
+
const specifier = arg.value;
|
|
1445
|
+
engine.recordNodeType(node.callee, types_1.tAnyType);
|
|
1446
|
+
if (!engine.importResolver)
|
|
1447
|
+
return types_1.tAnyType;
|
|
1448
|
+
const resolved = engine.importResolver(specifier);
|
|
1449
|
+
if (!resolved) {
|
|
1450
|
+
engine.addDiag(`Cannot resolve module '${specifier}'`, arg);
|
|
1451
|
+
return types_1.tAnyType;
|
|
1452
|
+
}
|
|
1453
|
+
if ((0, types_3.isUntypedModule)(resolved))
|
|
1454
|
+
return types_1.tAnyType;
|
|
1455
|
+
const def = resolved.get('default');
|
|
1456
|
+
return def ? (0, env_1.instantiate)(def) : (0, helpers_1.exportsToRecord)(resolved);
|
|
1457
|
+
}
|
|
1458
|
+
/**
|
|
1459
|
+
* Environment for the right operand of `left && right`: what `left` being
|
|
1460
|
+
* truthy proves. A bare identifier, a `typeof x === "…"` test and a
|
|
1461
|
+
* `::narrow` predicate call narrow; a nested `a && b` narrows by both
|
|
1462
|
+
* (`typeof x === "number" && Math.floor (x) === x && x >= MIN`). Other
|
|
1463
|
+
* tests (`x !== null`, member checks) are left alone here.
|
|
1464
|
+
*/
|
|
1465
|
+
function narrowForAndRight(engine, left, env) {
|
|
1466
|
+
if (left.type === 'LogicalExpression' && left.operator === '&&') {
|
|
1467
|
+
const l = left;
|
|
1468
|
+
return narrowForAndRight(engine, l.right, narrowForAndRight(engine, l.left, env));
|
|
1469
|
+
}
|
|
1470
|
+
if (left.type === 'Identifier'
|
|
1471
|
+
|| isNullCheckTest(left)
|
|
1472
|
+
|| (0, narrowing_1.extractTypeofCheck)(left)
|
|
1473
|
+
|| (0, narrowing_1.extractTypePredicateNarrowing)(engine.subst, left, env)
|
|
1474
|
+
|| (0, narrowing_2.isHasTest)(left)) {
|
|
1475
|
+
return (0, narrowing_1.computeNarrowedEnvs)(engine.subst, left, env, engine.annotationMap).consEnv;
|
|
1476
|
+
}
|
|
1477
|
+
return env;
|
|
1478
|
+
}
|
|
1479
|
+
/** `x == null`, `x !== undefined`, `obj.prop != null` … */
|
|
1480
|
+
function isNullCheckTest(node) {
|
|
1481
|
+
return (0, narrowing_1.extractNullCheck)(node) !== null || (0, narrowing_1.extractMemberNullCheck)(node) !== null;
|
|
1482
|
+
}
|
|
1483
|
+
/**
|
|
1484
|
+
* The env for the right side of `left || right`: `right` only runs when
|
|
1485
|
+
* `left` is falsy. Null checks narrow (`until == null || until.getTime ()`);
|
|
1486
|
+
* other tests leave the env as it is.
|
|
1487
|
+
*/
|
|
1488
|
+
function narrowForOrRight(engine, left, env) {
|
|
1489
|
+
if (left.type === 'LogicalExpression' && left.operator === '||') {
|
|
1490
|
+
const l = left;
|
|
1491
|
+
return narrowForOrRight(engine, l.right, narrowForOrRight(engine, l.left, env));
|
|
1492
|
+
}
|
|
1493
|
+
return isNullCheckTest(left) || (0, narrowing_2.isHasTest)(left)
|
|
1494
|
+
? (0, narrowing_1.computeNarrowedEnvs)(engine.subst, left, env, engine.annotationMap).altEnv
|
|
1495
|
+
: env;
|
|
1496
|
+
}
|
|
1497
|
+
//# sourceMappingURL=expressions.js.map
|