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,2487 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
// ============================================================================
|
|
3
|
+
// Comment Parser — parses HM type signatures from JS comments
|
|
4
|
+
//
|
|
5
|
+
// Plain language: users write their type notes inside ordinary JavaScript
|
|
6
|
+
// comments (the checker never changes how their code runs). This file is
|
|
7
|
+
// the "mail sorter": it scans a file's comments, picks out everything that
|
|
8
|
+
// looks like a type annotation or a `::directive` command, parses it, and
|
|
9
|
+
// attaches each note to the piece of code directly below it.
|
|
10
|
+
//
|
|
11
|
+
// Recognizes these patterns:
|
|
12
|
+
// // :: Number -> String
|
|
13
|
+
// /* :: a -> a */
|
|
14
|
+
// /** :: Number -> Number -> Number */
|
|
15
|
+
//
|
|
16
|
+
// The `::` prefix is required to distinguish HM annotations from regular
|
|
17
|
+
// comments. Comments are associated with the declaration that immediately
|
|
18
|
+
// follows them.
|
|
19
|
+
// ============================================================================
|
|
20
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
21
|
+
if (k2 === undefined) k2 = k;
|
|
22
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
23
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
24
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
25
|
+
}
|
|
26
|
+
Object.defineProperty(o, k2, desc);
|
|
27
|
+
}) : (function(o, m, k, k2) {
|
|
28
|
+
if (k2 === undefined) k2 = k;
|
|
29
|
+
o[k2] = m[k];
|
|
30
|
+
}));
|
|
31
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
32
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
33
|
+
}) : function(o, v) {
|
|
34
|
+
o["default"] = v;
|
|
35
|
+
});
|
|
36
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
37
|
+
var ownKeys = function(o) {
|
|
38
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
39
|
+
var ar = [];
|
|
40
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
41
|
+
return ar;
|
|
42
|
+
};
|
|
43
|
+
return ownKeys(o);
|
|
44
|
+
};
|
|
45
|
+
return function (mod) {
|
|
46
|
+
if (mod && mod.__esModule) return mod;
|
|
47
|
+
var result = {};
|
|
48
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
49
|
+
__setModuleDefault(result, mod);
|
|
50
|
+
return result;
|
|
51
|
+
};
|
|
52
|
+
})();
|
|
53
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
54
|
+
exports.TYPE_DIRECTIVE_PART_BOUNDARY = void 0;
|
|
55
|
+
exports.extractPrototypeMethod = extractPrototypeMethod;
|
|
56
|
+
exports.isLocalAnnotation = isLocalAnnotation;
|
|
57
|
+
exports.extractAnnotations = extractAnnotations;
|
|
58
|
+
exports.extractStandaloneHiddenMarkers = extractStandaloneHiddenMarkers;
|
|
59
|
+
exports.extractStandalonePrivateMarkers = extractStandalonePrivateMarkers;
|
|
60
|
+
exports.buildAnnotationMap = buildAnnotationMap;
|
|
61
|
+
exports.extractInstanceCallables = extractInstanceCallables;
|
|
62
|
+
exports.declarationStarts = declarationStarts;
|
|
63
|
+
exports.buildAnnotationsByDeclaration = buildAnnotationsByDeclaration;
|
|
64
|
+
exports.buildAnnotationByOffset = buildAnnotationByOffset;
|
|
65
|
+
exports.extractTypeDirectives = extractTypeDirectives;
|
|
66
|
+
exports.extractTypeDirectivesWithLocations = extractTypeDirectivesWithLocations;
|
|
67
|
+
exports.extractPreferDirectives = extractPreferDirectives;
|
|
68
|
+
exports.extractAliasExtensions = extractAliasExtensions;
|
|
69
|
+
exports.extractConstraintDirectives = extractConstraintDirectives;
|
|
70
|
+
exports.extractCurriedDirectiveLocations = extractCurriedDirectiveLocations;
|
|
71
|
+
exports.extractRepDirectives = extractRepDirectives;
|
|
72
|
+
exports.extractGlobalDirectives = extractGlobalDirectives;
|
|
73
|
+
exports.fieldTypeVars = fieldTypeVars;
|
|
74
|
+
exports.recordFields = recordFields;
|
|
75
|
+
exports.isDataShorthand = isDataShorthand;
|
|
76
|
+
exports.parseDataShorthand = parseDataShorthand;
|
|
77
|
+
exports.extractDataDirectives = extractDataDirectives;
|
|
78
|
+
exports.hasIgnoreFileDirective = hasIgnoreFileDirective;
|
|
79
|
+
exports.extractIgnoreLineDirectives = extractIgnoreLineDirectives;
|
|
80
|
+
exports.extractIgnoreFunctionDirectives = extractIgnoreFunctionDirectives;
|
|
81
|
+
exports.extractImportedNames = extractImportedNames;
|
|
82
|
+
exports.extractImportModuleSpecifiers = extractImportModuleSpecifiers;
|
|
83
|
+
const walk = __importStar(require("./walking"));
|
|
84
|
+
const parsing_1 = require("./parsing");
|
|
85
|
+
const types_1 = require("./hm/types");
|
|
86
|
+
const typeParser_1 = require("./hm/typeParser");
|
|
87
|
+
/** Sentinel comment inserted between sidecar/override parts in the merged
|
|
88
|
+
* source returned by `ImportInferenceContext.createTypeDirectiveResolver`.
|
|
89
|
+
* `processTypeDirectives` splits on it to apply override semantics for
|
|
90
|
+
* instance-callables (later parts win on `Name() :: ...` collisions).
|
|
91
|
+
* Comments survive the JS-parse pass that processes the merged source
|
|
92
|
+
* for annotations, so the sentinel itself is harmless to all other
|
|
93
|
+
* consumers. */
|
|
94
|
+
exports.TYPE_DIRECTIVE_PART_BOUNDARY = '//__HM_TYPE_DIRECTIVE_BOUNDARY__';
|
|
95
|
+
// ---------------------------------------------------------------------------
|
|
96
|
+
// Prototype method pattern extraction
|
|
97
|
+
// ---------------------------------------------------------------------------
|
|
98
|
+
/**
|
|
99
|
+
* Extract X.prototype.method pattern from a MemberExpression node.
|
|
100
|
+
* Returns { typeName, methodName } or null.
|
|
101
|
+
*/
|
|
102
|
+
function extractPrototypeMethod(memberExpr) {
|
|
103
|
+
const obj = memberExpr.object;
|
|
104
|
+
const prop = memberExpr.property;
|
|
105
|
+
if (obj?.type === 'MemberExpression' && !obj.computed
|
|
106
|
+
&& obj.object?.type === 'Identifier'
|
|
107
|
+
&& obj.property?.type === 'Identifier' && obj.property.name === 'prototype'
|
|
108
|
+
&& prop?.type === 'Identifier') {
|
|
109
|
+
return { typeName: obj.object.name, methodName: prop.name };
|
|
110
|
+
}
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Single source of truth for "is this annotation file-local?".
|
|
115
|
+
*
|
|
116
|
+
* Inference-feeding consumers (export-scheme construction, dotted-name
|
|
117
|
+
* constraint injection, prototype receiver inference, bare-binding
|
|
118
|
+
* annotation lookup, …) must call this rather than naked
|
|
119
|
+
* `annotationMap.get(...)` so that sidecar / globals / `::types`
|
|
120
|
+
* entries with colliding names cannot silently hijack user bindings.
|
|
121
|
+
*
|
|
122
|
+
* Treats `undefined` origin as `'local'` so that any code path that
|
|
123
|
+
* still constructs `TypeAnnotation` objects without setting `origin`
|
|
124
|
+
* remains correct by default.
|
|
125
|
+
*/
|
|
126
|
+
function isLocalAnnotation(ann) {
|
|
127
|
+
if (!ann)
|
|
128
|
+
return false;
|
|
129
|
+
return ann.origin === undefined || ann.origin === 'local';
|
|
130
|
+
}
|
|
131
|
+
// ---------------------------------------------------------------------------
|
|
132
|
+
// Shared parse helper
|
|
133
|
+
// ---------------------------------------------------------------------------
|
|
134
|
+
/** Parse source with the parser, collecting comments. Falls back to the loose mode on
|
|
135
|
+
* parse failure so annotations and other comment-driven features still work
|
|
136
|
+
* on partially-broken sources. */
|
|
137
|
+
// Tiny LRU memoization keyed by source string identity. Re-parsing huge
|
|
138
|
+
// sources (e.g. an 8000-line `.query-builder/client/index.hm` globals addendum) on
|
|
139
|
+
// every hover / completion / diagnostic call dominates request latency,
|
|
140
|
+
// so we keep the last few parses ready to be reused as long as the caller
|
|
141
|
+
// hands us the SAME string instance. The cache is intentionally kept
|
|
142
|
+
// small — entries hold full ASTs and comment arrays.
|
|
143
|
+
const PARSE_CACHE_MAX = 8;
|
|
144
|
+
const parseCache = [];
|
|
145
|
+
function parseWithComments(source) {
|
|
146
|
+
for (let i = 0; i < parseCache.length; i++) {
|
|
147
|
+
if (parseCache[i].source === source) {
|
|
148
|
+
// Promote to most-recent
|
|
149
|
+
const hit = parseCache[i];
|
|
150
|
+
if (i !== 0) {
|
|
151
|
+
parseCache.splice(i, 1);
|
|
152
|
+
parseCache.unshift(hit);
|
|
153
|
+
}
|
|
154
|
+
return hit.result;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const comments = [];
|
|
158
|
+
let result;
|
|
159
|
+
try {
|
|
160
|
+
const ast = (0, parsing_1.parseStrict)(source, comments);
|
|
161
|
+
result = { ast, comments };
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
// Try fault-tolerant parser
|
|
165
|
+
try {
|
|
166
|
+
const looseComments = [];
|
|
167
|
+
const ast = (0, parsing_1.parseLoose)(source, looseComments);
|
|
168
|
+
result = { ast, comments: looseComments };
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
result = null;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
parseCache.unshift({ source, result });
|
|
175
|
+
if (parseCache.length > PARSE_CACHE_MAX)
|
|
176
|
+
parseCache.length = PARSE_CACHE_MAX;
|
|
177
|
+
return result;
|
|
178
|
+
}
|
|
179
|
+
// ---------------------------------------------------------------------------
|
|
180
|
+
// Extraction
|
|
181
|
+
// ---------------------------------------------------------------------------
|
|
182
|
+
/** Regex to match optional `name ::`, `Name#method ::`, `Name.method ::`,
|
|
183
|
+
* `Name##private ::`, `Name() ::` (instance-callable annotation),
|
|
184
|
+
* or just `::` in a comment body. */
|
|
185
|
+
const HM_PATTERN = /^[\s*]*(?:([\w$]+(?:\(\)|(?:##|[#.])(?:@@)?[\w$]+)?)\s+)?::\s*(.+)$/m;
|
|
186
|
+
/** Regex to match `// ::narrow <Type>` directive in comments. */
|
|
187
|
+
/**
|
|
188
|
+
* For a block comment's HM_PATTERN match: does the annotation line start a
|
|
189
|
+
* paragraph? True when every line before it is blank, or the line directly
|
|
190
|
+
* above it is blank (JSDoc `*` gutters count as blank). `[\s*]*` in
|
|
191
|
+
* HM_PATTERN may swallow leading blank lines, so locate the real annotation
|
|
192
|
+
* line via the `::` separator.
|
|
193
|
+
*/
|
|
194
|
+
function blockAnnotationStartsParagraph(text, match) {
|
|
195
|
+
const sepIdx = match.index + match[0].indexOf('::');
|
|
196
|
+
const lineStart = text.lastIndexOf('\n', sepIdx) + 1;
|
|
197
|
+
if (lineStart === 0)
|
|
198
|
+
return true;
|
|
199
|
+
const before = text.slice(0, lineStart - 1); // drop the separating '\n'
|
|
200
|
+
const prevLine = before.slice(before.lastIndexOf('\n') + 1);
|
|
201
|
+
return /^[\s*]*$/.test(prevLine);
|
|
202
|
+
}
|
|
203
|
+
const NARROW_DIRECTIVE_PATTERN = /^[\s*]*::narrow\s+(.+)$/m;
|
|
204
|
+
/** Regex to match `// ::hidden` or `// ::hidden <Qualified.Name>` directives.
|
|
205
|
+
* The optional capture group selects a single registration target (by its
|
|
206
|
+
* qualified `Base.field` / `Base#method` name) in a chained / multi-binding
|
|
207
|
+
* annotation; without it the directive hides every member-shaped target. */
|
|
208
|
+
const HIDDEN_DIRECTIVE_PATTERN = /^[\s*]*::hidden(?:\s+([\w$]+(?:[#.][\w$]+)?))?\s*$/m;
|
|
209
|
+
/** Regex to match `// ::private` or `// ::private <Qualified.Name>` directives.
|
|
210
|
+
* See {@link HIDDEN_DIRECTIVE_PATTERN} for the optional target argument. */
|
|
211
|
+
const PRIVATE_DIRECTIVE_PATTERN = /^[\s*]*::private(?:\s+([\w$]+(?:[#.][\w$]+)?))?\s*$/m;
|
|
212
|
+
function findImmediatePreviousLineDirective(comments, index, source, pattern) {
|
|
213
|
+
if (index <= 0)
|
|
214
|
+
return null;
|
|
215
|
+
const prev = comments[index - 1];
|
|
216
|
+
const curr = comments[index];
|
|
217
|
+
/* istanbul ignore next */
|
|
218
|
+
if (!prev || !curr)
|
|
219
|
+
return null;
|
|
220
|
+
if (prev.type !== 'Line' || curr.type !== 'Line')
|
|
221
|
+
return null;
|
|
222
|
+
const gap = source.slice(prev.end, curr.start);
|
|
223
|
+
if (!/^\s*$/.test(gap))
|
|
224
|
+
return null;
|
|
225
|
+
const match = pattern.exec(prev.value);
|
|
226
|
+
if (!match)
|
|
227
|
+
return null;
|
|
228
|
+
return { match, start: prev.start, end: prev.end };
|
|
229
|
+
}
|
|
230
|
+
function collectStackedDirectives(comments, index, source, pattern) {
|
|
231
|
+
const args = new Set();
|
|
232
|
+
let hasNoArg = false;
|
|
233
|
+
let present = false;
|
|
234
|
+
let curr = comments[index];
|
|
235
|
+
if (!curr || curr.type !== 'Line')
|
|
236
|
+
return { args, hasNoArg, present };
|
|
237
|
+
for (let j = index - 1; j >= 0; j--) {
|
|
238
|
+
const prev = comments[j];
|
|
239
|
+
if (!prev || prev.type !== 'Line')
|
|
240
|
+
break;
|
|
241
|
+
const gap = source.slice(prev.end, curr.start);
|
|
242
|
+
if (!/^\s*$/.test(gap))
|
|
243
|
+
break;
|
|
244
|
+
// Only `::hidden` / `::private` lines continue the directive stack.
|
|
245
|
+
const isDirectiveLine = HIDDEN_DIRECTIVE_PATTERN.test(prev.value) || PRIVATE_DIRECTIVE_PATTERN.test(prev.value);
|
|
246
|
+
if (!isDirectiveLine)
|
|
247
|
+
break;
|
|
248
|
+
const m = pattern.exec(prev.value);
|
|
249
|
+
if (m) {
|
|
250
|
+
present = true;
|
|
251
|
+
const arg = m[1]?.trim();
|
|
252
|
+
if (arg)
|
|
253
|
+
args.add(arg);
|
|
254
|
+
else
|
|
255
|
+
hasNoArg = true;
|
|
256
|
+
}
|
|
257
|
+
curr = prev;
|
|
258
|
+
}
|
|
259
|
+
return { args, hasNoArg, present };
|
|
260
|
+
}
|
|
261
|
+
/** A `// ::narrow T` line comment directly next to the signature comment
|
|
262
|
+
* `curr` (only whitespace, no blank line, in between). */
|
|
263
|
+
function narrowDirectiveNextTo(directive, curr, source) {
|
|
264
|
+
if (!directive || directive.type !== 'Line' || curr.type !== 'Line')
|
|
265
|
+
return null;
|
|
266
|
+
const gap = directive.end <= curr.start
|
|
267
|
+
? source.slice(directive.end, curr.start)
|
|
268
|
+
: source.slice(curr.end, directive.start);
|
|
269
|
+
if (!/^[ \t]*\r?\n[ \t]*$/.test(gap))
|
|
270
|
+
return null;
|
|
271
|
+
const match = NARROW_DIRECTIVE_PATTERN.exec(directive.value);
|
|
272
|
+
return match ? { narrowedTypeRaw: match[1].trim(), start: directive.start, end: directive.end } : null;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* The `::narrow` directive of the signature comment at `index`: the line
|
|
276
|
+
* directly above it, or else the line directly below it (both orders occur:
|
|
277
|
+
* `// ::narrow Array` + `// isArray :: …`, or the signature first).
|
|
278
|
+
*/
|
|
279
|
+
function findImmediateNarrowDirective(comments, index, source) {
|
|
280
|
+
const curr = comments[index];
|
|
281
|
+
/* istanbul ignore next — always defined for a valid index */
|
|
282
|
+
if (!curr)
|
|
283
|
+
return null;
|
|
284
|
+
const above = narrowDirectiveNextTo(index > 0 ? comments[index - 1] : undefined, curr, source);
|
|
285
|
+
if (above)
|
|
286
|
+
return above;
|
|
287
|
+
// Below: only when no signature follows the directive directly — then the
|
|
288
|
+
// directive belongs to THAT signature (the usual "directive above" order).
|
|
289
|
+
const below = narrowDirectiveNextTo(comments[index + 1], curr, source);
|
|
290
|
+
const after = comments[index + 2];
|
|
291
|
+
const belongsToNext = below !== null && after !== undefined && after.type === 'Line'
|
|
292
|
+
&& /^[ \t]*\r?\n[ \t]*$/.test(source.slice(below.end, after.start))
|
|
293
|
+
&& HM_PATTERN.test(after.value) && !NARROW_DIRECTIVE_PATTERN.test(after.value);
|
|
294
|
+
return belongsToNext ? null : below;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Find the first label-variable name referenced anywhere in a type
|
|
298
|
+
* (e.g. 'k' in `{ [k] :: a }`). Used to link a narrowed record's polymorphic
|
|
299
|
+
* label to the signature parameter that supplies its concrete value. Returns
|
|
300
|
+
* null when the type has no polymorphic-label field.
|
|
301
|
+
*/
|
|
302
|
+
function firstLabelVarName(t) {
|
|
303
|
+
switch (t.tag) {
|
|
304
|
+
case 'TRecord': {
|
|
305
|
+
for (const lf of t.labelFields ?? []) {
|
|
306
|
+
if (lf.label.tag === 'TLabel' && lf.label.kind === 'var')
|
|
307
|
+
return lf.label.name;
|
|
308
|
+
const inner = firstLabelVarName(lf.type);
|
|
309
|
+
if (inner)
|
|
310
|
+
return inner;
|
|
311
|
+
}
|
|
312
|
+
for (const key of Object.keys(t.fields)) {
|
|
313
|
+
const inner = firstLabelVarName(t.fields[key]);
|
|
314
|
+
if (inner)
|
|
315
|
+
return inner;
|
|
316
|
+
}
|
|
317
|
+
return t.rest ? firstLabelVarName(t.rest) : null;
|
|
318
|
+
}
|
|
319
|
+
case 'TCon': {
|
|
320
|
+
for (const a of t.args) {
|
|
321
|
+
const inner = firstLabelVarName(a);
|
|
322
|
+
if (inner)
|
|
323
|
+
return inner;
|
|
324
|
+
}
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
case 'TFun':
|
|
328
|
+
return firstLabelVarName(t.param) ?? firstLabelVarName(t.result);
|
|
329
|
+
default:
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Extract all HM type annotations from a JavaScript source string.
|
|
335
|
+
*
|
|
336
|
+
* The function:
|
|
337
|
+
* 1. Parses the source with Acorn to get comments + AST
|
|
338
|
+
* 2. For each comment containing `:: <signature>`, parses the type signature
|
|
339
|
+
* 3. Associates the annotation with the next declaration
|
|
340
|
+
*/
|
|
341
|
+
function extractAnnotations(source) {
|
|
342
|
+
for (let i = 0; i < extractCache.length; i++) {
|
|
343
|
+
if (extractCache[i].source === source) {
|
|
344
|
+
const hit = extractCache[i];
|
|
345
|
+
if (i !== 0) {
|
|
346
|
+
extractCache.splice(i, 1);
|
|
347
|
+
extractCache.unshift(hit);
|
|
348
|
+
}
|
|
349
|
+
return hit.annotations;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
// Parse annotation type variables in a RESERVED high ID range, separate
|
|
353
|
+
// from the per-run inference allocator. Parsed schemes are cached by
|
|
354
|
+
// source string and reused across inference runs; every consumer
|
|
355
|
+
// instantiates (or refreshes) them before use, so the reserved template
|
|
356
|
+
// IDs are remapped to fresh per-run vars. Reserving the range here keeps
|
|
357
|
+
// the per-run allocator's trajectory IDENTICAL on cache-hit vs cache-miss
|
|
358
|
+
// runs (parsing no longer advances it), which is essential for
|
|
359
|
+
// deterministic inference — otherwise the same source could intermittently
|
|
360
|
+
// alias unrelated type variables.
|
|
361
|
+
const prevAllocator = (0, types_1.setActiveAllocator)(new types_1.TypeVarAllocator(ANNOTATION_PARSE_VAR_BASE));
|
|
362
|
+
let annotations;
|
|
363
|
+
try {
|
|
364
|
+
annotations = extractAnnotationsImpl(source);
|
|
365
|
+
}
|
|
366
|
+
finally {
|
|
367
|
+
(0, types_1.setActiveAllocator)(prevAllocator);
|
|
368
|
+
}
|
|
369
|
+
extractCache.unshift({ source, annotations });
|
|
370
|
+
if (extractCache.length > PARSE_CACHE_MAX)
|
|
371
|
+
extractCache.length = PARSE_CACHE_MAX;
|
|
372
|
+
return annotations;
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* High base offset for type-variable IDs allocated while parsing cached
|
|
376
|
+
* annotation schemes. Distinct from the builtin-environment range and far
|
|
377
|
+
* above any per-run allocation, so cached template IDs never collide with
|
|
378
|
+
* fresh inference vars.
|
|
379
|
+
*/
|
|
380
|
+
const ANNOTATION_PARSE_VAR_BASE = 2000000000;
|
|
381
|
+
const extractCache = [];
|
|
382
|
+
/** Extract `(typeName, methodName)` pairs for every standalone `::hidden`
|
|
383
|
+
* directive found in `source` whose owning type can be resolved. */
|
|
384
|
+
function extractStandaloneHiddenMarkers(source) {
|
|
385
|
+
return extractStandaloneDirectiveMarkers(source, HIDDEN_DIRECTIVE_PATTERN);
|
|
386
|
+
}
|
|
387
|
+
/** Extract `(typeName, methodName)` pairs for every standalone `::private`
|
|
388
|
+
* directive found in `source` whose owning type can be resolved. */
|
|
389
|
+
function extractStandalonePrivateMarkers(source) {
|
|
390
|
+
return extractStandaloneDirectiveMarkers(source, PRIVATE_DIRECTIVE_PATTERN);
|
|
391
|
+
}
|
|
392
|
+
function extractStandaloneDirectiveMarkers(source, pattern) {
|
|
393
|
+
const parsed = parseWithComments(source);
|
|
394
|
+
if (!parsed)
|
|
395
|
+
return [];
|
|
396
|
+
const { ast, comments } = parsed;
|
|
397
|
+
const markers = [];
|
|
398
|
+
for (let i = 0; i < comments.length; i++) {
|
|
399
|
+
const c = comments[i];
|
|
400
|
+
if (c.type !== 'Line')
|
|
401
|
+
continue;
|
|
402
|
+
if (!pattern.test(c.value))
|
|
403
|
+
continue;
|
|
404
|
+
// Skip when the next comment is line-adjacent and is a real HM annotation.
|
|
405
|
+
// That case is already handled in extractAnnotations by attaching `hidden`
|
|
406
|
+
// to the annotation entry.
|
|
407
|
+
const next = comments[i + 1];
|
|
408
|
+
if (next && next.type === 'Line') {
|
|
409
|
+
const gap = source.slice(c.end, next.start);
|
|
410
|
+
if (/^\s*$/.test(gap) && HM_PATTERN.test(next.value))
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
// Walk the AST to find the next class method or prototype-object property
|
|
414
|
+
// appearing after this directive.
|
|
415
|
+
const target = findNextHidableMember(ast, c.end);
|
|
416
|
+
if (target) {
|
|
417
|
+
markers.push({
|
|
418
|
+
typeName: target.typeName,
|
|
419
|
+
methodName: target.methodName,
|
|
420
|
+
commentStart: c.start,
|
|
421
|
+
commentEnd: c.end,
|
|
422
|
+
memberStart: target.start,
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
return markers;
|
|
427
|
+
}
|
|
428
|
+
/** Look for the next class MethodDefinition or prototype-object Property that
|
|
429
|
+
* starts after `afterOffset` and whose owner type is determinable. */
|
|
430
|
+
function findNextHidableMember(ast, afterOffset) {
|
|
431
|
+
let best = null;
|
|
432
|
+
const consider = (start, typeName, methodName) => {
|
|
433
|
+
if (start <= afterOffset)
|
|
434
|
+
return;
|
|
435
|
+
if (!best || start < best.start)
|
|
436
|
+
best = { typeName, methodName, start };
|
|
437
|
+
};
|
|
438
|
+
const propertyKeyName = (key) => {
|
|
439
|
+
if (!key)
|
|
440
|
+
return null;
|
|
441
|
+
if (key.type === 'Identifier')
|
|
442
|
+
return key.name;
|
|
443
|
+
if (key.type === 'Literal' && typeof key.value === 'string') {
|
|
444
|
+
return key.value;
|
|
445
|
+
}
|
|
446
|
+
return null;
|
|
447
|
+
};
|
|
448
|
+
const ownerOfPrototypeObject = (parent) => {
|
|
449
|
+
if (!parent)
|
|
450
|
+
return null;
|
|
451
|
+
// const X$prototype = { ... } → X
|
|
452
|
+
if (parent.type === 'VariableDeclarator') {
|
|
453
|
+
const vd = parent;
|
|
454
|
+
if (vd.id?.type === 'Identifier' && /\$prototype$/.test(vd.id.name)) {
|
|
455
|
+
return vd.id.name.replace(/\$prototype$/, '');
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
// X.prototype = { ... }
|
|
459
|
+
if (parent.type === 'AssignmentExpression') {
|
|
460
|
+
const ae = parent;
|
|
461
|
+
const left = ae.left;
|
|
462
|
+
if (left.type === 'MemberExpression'
|
|
463
|
+
&& !left.computed
|
|
464
|
+
&& left.object.type === 'Identifier'
|
|
465
|
+
&& left.property.type === 'Identifier'
|
|
466
|
+
&& left.property.name === 'prototype') {
|
|
467
|
+
return left.object.name;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return null;
|
|
471
|
+
};
|
|
472
|
+
walk.ancestor(ast, {
|
|
473
|
+
MethodDefinition(node, _state, ancestors) {
|
|
474
|
+
const methodName = propertyKeyName(node.key);
|
|
475
|
+
if (!methodName)
|
|
476
|
+
return;
|
|
477
|
+
// Climb to the enclosing ClassDeclaration / ClassExpression
|
|
478
|
+
for (let k = ancestors.length - 2; k >= 0; k--) {
|
|
479
|
+
const a = ancestors[k];
|
|
480
|
+
if (a.type === 'ClassDeclaration' || a.type === 'ClassExpression') {
|
|
481
|
+
const className = a.id?.name;
|
|
482
|
+
if (className)
|
|
483
|
+
consider(node.start, className, methodName);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
},
|
|
488
|
+
Property(node, _state, ancestors) {
|
|
489
|
+
const methodName = propertyKeyName(node.key);
|
|
490
|
+
if (!methodName)
|
|
491
|
+
return;
|
|
492
|
+
// Climb: Property -> ObjectExpression -> (VariableDeclarator | AssignmentExpression)
|
|
493
|
+
// ancestors: [Program, ..., parentOfObj, ObjectExpression, Property]
|
|
494
|
+
const objIdx = ancestors.length - 2;
|
|
495
|
+
const parent = ancestors[objIdx - 1];
|
|
496
|
+
const owner = ownerOfPrototypeObject(parent ?? null);
|
|
497
|
+
// Resolved class/prototype owner: register the method-level marker.
|
|
498
|
+
// Otherwise still consider the property so its offset can be marked
|
|
499
|
+
// hidden — plain object-literal fields use offset-based filtering.
|
|
500
|
+
if (owner)
|
|
501
|
+
consider(node.start, owner, methodName);
|
|
502
|
+
else
|
|
503
|
+
consider(node.start, '', methodName);
|
|
504
|
+
},
|
|
505
|
+
});
|
|
506
|
+
return best;
|
|
507
|
+
}
|
|
508
|
+
function extractAnnotationsImpl(source) {
|
|
509
|
+
const parsed = parseWithComments(source);
|
|
510
|
+
if (!parsed)
|
|
511
|
+
return [];
|
|
512
|
+
const { ast, comments } = parsed;
|
|
513
|
+
const annotations = [];
|
|
514
|
+
const skipIndices = new Set(); // comments consumed as continuation lines
|
|
515
|
+
for (let i = 0; i < comments.length; i++) {
|
|
516
|
+
if (skipIndices.has(i))
|
|
517
|
+
continue;
|
|
518
|
+
const comment = comments[i];
|
|
519
|
+
const text = comment.value;
|
|
520
|
+
const match = HM_PATTERN.exec(text);
|
|
521
|
+
if (!match)
|
|
522
|
+
continue;
|
|
523
|
+
// Block comments: the annotation must START A PARAGRAPH — the first
|
|
524
|
+
// non-empty line of the block, or a line directly after a blank (or bare
|
|
525
|
+
// JSDoc `*`) line, as in
|
|
526
|
+
// /**
|
|
527
|
+
// * For more info: …
|
|
528
|
+
// *
|
|
529
|
+
// * Array#traverse :: Applicative f => …
|
|
530
|
+
// */
|
|
531
|
+
// HM_PATTERN is multiline, so without this guard any `Name :: …` line in
|
|
532
|
+
// the middle of a prose paragraph (notes, quoted examples) would be parsed
|
|
533
|
+
// as a real annotation.
|
|
534
|
+
if (comment.type === 'Block' && !blockAnnotationStartsParagraph(text, match))
|
|
535
|
+
continue;
|
|
536
|
+
const annotationName = match[1]; // optional name before ::
|
|
537
|
+
let raw = match[2].trim(); // type signature after ::
|
|
538
|
+
// Compute the source offset of the annotation name within the comment.
|
|
539
|
+
// comment.value starts at comment.start + 2 (after `//` or `/*`).
|
|
540
|
+
let signatureNameStart;
|
|
541
|
+
let signatureNameEnd;
|
|
542
|
+
if (annotationName) {
|
|
543
|
+
const nameIdx = text.indexOf(annotationName, match.index);
|
|
544
|
+
if (nameIdx >= 0) {
|
|
545
|
+
signatureNameStart = comment.start + 2 + nameIdx;
|
|
546
|
+
signatureNameEnd = signatureNameStart + annotationName.length;
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
// Skip ::directive keywords — these are handled by their own extractors.
|
|
550
|
+
// Directives use `::keyword` (no space before keyword after `::` in the
|
|
551
|
+
// comment body), while type annotations always have a space after `::`.
|
|
552
|
+
if (!annotationName && /^(?:types|constraint|global|narrow|hidden|private|extend|rep|prefer|builtin|curried|ignore(?:-file|-function)?)\b/.test(raw))
|
|
553
|
+
continue;
|
|
554
|
+
// Skip shorthand data type declarations (e.g. `// Either2 :: Left e | Right a`).
|
|
555
|
+
// These are handled by extractDataDirectives instead. Also covers the
|
|
556
|
+
// multi-line forms (block comments / `|`-continued line comments) so their
|
|
557
|
+
// continuation lines are not mis-parsed as standalone annotations.
|
|
558
|
+
if (annotationName && /^[A-Z]/.test(annotationName)) {
|
|
559
|
+
const ds = readDataShorthand(comments, i, source);
|
|
560
|
+
if (ds) {
|
|
561
|
+
for (const c of ds.consumed)
|
|
562
|
+
skipIndices.add(c);
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
const commentStart = comment.start;
|
|
567
|
+
let commentEnd = comment.end;
|
|
568
|
+
const narrowDirective = findImmediateNarrowDirective(comments, i, source);
|
|
569
|
+
// Collect EVERY stacked `::hidden` / `::private` directive above this
|
|
570
|
+
// annotation. Several `::hidden <Name>` lines may stack above one chained
|
|
571
|
+
// annotation, each independently selecting a different target.
|
|
572
|
+
const hiddenInfo = collectStackedDirectives(comments, i, source, HIDDEN_DIRECTIVE_PATTERN);
|
|
573
|
+
const privateInfo = collectStackedDirectives(comments, i, source, PRIVATE_DIRECTIVE_PATTERN);
|
|
574
|
+
// --- Multi-line support: block comments (/* ... */) ---
|
|
575
|
+
// HM_PATTERN with /m flag only captures to end of the first matching line.
|
|
576
|
+
// If there is remaining content in the block comment, append it.
|
|
577
|
+
if (comment.type === 'Block') {
|
|
578
|
+
const matchEnd = match.index + match[0].length;
|
|
579
|
+
const remaining = text.slice(matchEnd);
|
|
580
|
+
if (remaining.trim()) {
|
|
581
|
+
// Continuation runs to the end of the PARAGRAPH: a blank (or bare
|
|
582
|
+
// JSDoc `*`) line ends the annotation, so prose that follows in the
|
|
583
|
+
// same block comment is not glued onto the signature.
|
|
584
|
+
const continuationLines = [];
|
|
585
|
+
const remLines = remaining.split('\n');
|
|
586
|
+
// remLines[0] is the (empty) tail of the annotation's own line.
|
|
587
|
+
for (let li = 1; li < remLines.length; li++) {
|
|
588
|
+
const line = remLines[li].replace(/^\s*\*?\s?/, '').trim();
|
|
589
|
+
if (line.length === 0)
|
|
590
|
+
break;
|
|
591
|
+
continuationLines.push(line);
|
|
592
|
+
}
|
|
593
|
+
if (continuationLines.length > 0) {
|
|
594
|
+
raw = raw + ' ' + continuationLines.join(' ');
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
// --- Multi-line support: consecutive line comments (// ...) ---
|
|
599
|
+
// If the current comment is a line comment and the type signature so far
|
|
600
|
+
// has unbalanced brackets/braces/parens, look ahead for continuation
|
|
601
|
+
// lines that are NOT new annotations or directives.
|
|
602
|
+
if (comment.type === 'Line') {
|
|
603
|
+
const joined = joinLineContinuations(comments, i, source, raw, commentEnd);
|
|
604
|
+
raw = joined.raw;
|
|
605
|
+
commentEnd = joined.commentEnd;
|
|
606
|
+
for (const j of joined.consumed)
|
|
607
|
+
skipIndices.add(j);
|
|
608
|
+
}
|
|
609
|
+
let schemeResult = null;
|
|
610
|
+
let error;
|
|
611
|
+
let receiver;
|
|
612
|
+
let methodType;
|
|
613
|
+
let isNarrowableBooleanMember = false;
|
|
614
|
+
// --- Chained annotation: `// A :: B :: TypeSig` ---
|
|
615
|
+
// The first `::` is consumed by HM_PATTERN above (annotationName = A,
|
|
616
|
+
// raw = "B :: TypeSig"). Detect a leading `Identifier(.Identifier)? ::`
|
|
617
|
+
// in `raw` and split off the second name so we can register a secondary
|
|
618
|
+
// annotation entry under that name with the same parsed scheme.
|
|
619
|
+
// Chained names collected from `// A :: B :: C :: … :: TypeSig`. The
|
|
620
|
+
// first `::` is consumed by HM_PATTERN (annotationName = A); here we peel
|
|
621
|
+
// any number of further leading `Name ::` prefixes off `raw`, each of
|
|
622
|
+
// which becomes a secondary annotation entry sharing the parsed scheme.
|
|
623
|
+
const chainedNames = [];
|
|
624
|
+
let chainedError;
|
|
625
|
+
if (annotationName) {
|
|
626
|
+
// Start searching for chained names after the first `::` so we never
|
|
627
|
+
// re-match the leading annotation name itself.
|
|
628
|
+
const firstSepIdx = text.indexOf('::', match.index);
|
|
629
|
+
let searchFrom = firstSepIdx >= 0 ? firstSepIdx + 2 : 0;
|
|
630
|
+
for (;;) {
|
|
631
|
+
const chainMatch = /^([A-Za-z_$][\w$]*(?:[#.][A-Za-z_$][\w$]*)?)\s*::\s*([\s\S]+)$/.exec(raw);
|
|
632
|
+
if (!chainMatch)
|
|
633
|
+
break;
|
|
634
|
+
const secondName = chainMatch[1];
|
|
635
|
+
const isValidShape = /^[A-Za-z_$][\w$]*(?:[.#][A-Za-z_$][\w$]*)?$/.test(secondName);
|
|
636
|
+
if (!isValidShape && chainedError === undefined) {
|
|
637
|
+
chainedError = `Invalid chained annotation name '${secondName}': only Identifier, Identifier.Identifier or Identifier#Identifier are allowed`;
|
|
638
|
+
}
|
|
639
|
+
// Locate this name in the original comment text, advancing past each
|
|
640
|
+
// consumed `::` so repeated names get distinct positions.
|
|
641
|
+
let nameStart;
|
|
642
|
+
let nameEnd;
|
|
643
|
+
const nameIdx = text.indexOf(secondName, searchFrom);
|
|
644
|
+
if (nameIdx >= 0) {
|
|
645
|
+
nameStart = comment.start + 2 + nameIdx;
|
|
646
|
+
nameEnd = nameStart + secondName.length;
|
|
647
|
+
const sepIdx = text.indexOf('::', nameIdx + secondName.length);
|
|
648
|
+
searchFrom = sepIdx >= 0 ? sepIdx + 2 : nameIdx + secondName.length;
|
|
649
|
+
}
|
|
650
|
+
chainedNames.push({ name: secondName, start: nameStart, end: nameEnd });
|
|
651
|
+
// Strip the prefix so the remainder is parsed as the actual signature
|
|
652
|
+
// (or the next chained name on the following iteration).
|
|
653
|
+
raw = chainMatch[2].trim();
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
try {
|
|
657
|
+
if (raw.includes('~>')) {
|
|
658
|
+
// Method type signature: ReceiverType ~> MethodType
|
|
659
|
+
const parsed = (0, typeParser_1.parseMethodTypeSignature)(raw);
|
|
660
|
+
schemeResult = parsed.scheme;
|
|
661
|
+
receiver = parsed.receiver;
|
|
662
|
+
methodType = parsed.methodType;
|
|
663
|
+
if (narrowDirective) {
|
|
664
|
+
// Allow ::narrow on method annotations when the method type is Boolean
|
|
665
|
+
// (getter) or returns Boolean (method like `() -> Boolean`).
|
|
666
|
+
const methodReturnType = methodType ? (0, types_1.getReturnType)(methodType) : undefined;
|
|
667
|
+
if (methodReturnType && methodReturnType.tag === 'TCon' && methodReturnType.name === types_1.T_BOOLEAN) {
|
|
668
|
+
// Store the variant name for use by the narrowing system
|
|
669
|
+
// (stored on the annotation object after construction below)
|
|
670
|
+
}
|
|
671
|
+
else {
|
|
672
|
+
error = '::narrow can only be used with regular function annotations or Boolean-returning methods';
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
else {
|
|
677
|
+
schemeResult = (0, typeParser_1.parseTypeSignature)(raw);
|
|
678
|
+
if (schemeResult && narrowDirective) {
|
|
679
|
+
const returnType = (0, types_1.getReturnType)(schemeResult.type);
|
|
680
|
+
if (!(returnType.tag === 'TCon' && returnType.name === types_1.T_BOOLEAN)) {
|
|
681
|
+
error = '::narrow can only be used on Boolean-returning functions';
|
|
682
|
+
schemeResult = null;
|
|
683
|
+
}
|
|
684
|
+
else if (schemeResult.type.tag !== 'TFun') {
|
|
685
|
+
// A bare Boolean MEMBER annotation (e.g. `// Body#isStream ::
|
|
686
|
+
// Boolean`) is a getter-style narrowing predicate: when the
|
|
687
|
+
// property is truthy the receiver narrows to the named variant.
|
|
688
|
+
// This is valid only on members (`Type#prop`); a free-standing
|
|
689
|
+
// `// foo :: Boolean` has no receiver to narrow.
|
|
690
|
+
if (annotationName && annotationName.includes('#')) {
|
|
691
|
+
isNarrowableBooleanMember = true;
|
|
692
|
+
}
|
|
693
|
+
else {
|
|
694
|
+
error = '::narrow requires a function annotation (e.g. a -> Boolean)';
|
|
695
|
+
schemeResult = null;
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
else {
|
|
699
|
+
// Collect the curried parameters.
|
|
700
|
+
const params = [];
|
|
701
|
+
let cur = schemeResult.type;
|
|
702
|
+
while (cur.tag === 'TFun') {
|
|
703
|
+
params.push(cur.param);
|
|
704
|
+
cur = cur.result;
|
|
705
|
+
}
|
|
706
|
+
// `::narrow <InstanceType>`: the directive body is read wholly as
|
|
707
|
+
// a type. The narrowed parameter is always the LAST parameter
|
|
708
|
+
// (the value being tested).
|
|
709
|
+
const narrowedType = (0, typeParser_1.parseType)(narrowDirective.narrowedTypeRaw);
|
|
710
|
+
// Link a polymorphic label in the narrowed record (e.g. `k` in
|
|
711
|
+
// `{ [k] :: a }`) to the signature parameter that supplies its
|
|
712
|
+
// concrete value, so the call-site narrowing can substitute it.
|
|
713
|
+
// The parser turns a bare `k` parameter into a LABEL variable when
|
|
714
|
+
// `[k]` appears elsewhere in the signature, so match either sort.
|
|
715
|
+
const keyVarName = firstLabelVarName(narrowedType);
|
|
716
|
+
let keyParamIndex;
|
|
717
|
+
if (keyVarName) {
|
|
718
|
+
const idx = params.findIndex(p => (p.tag === 'TVar' && p.name === keyVarName) ||
|
|
719
|
+
(p.tag === 'TLabel' && p.kind === 'var' && p.name === keyVarName));
|
|
720
|
+
if (idx >= 0)
|
|
721
|
+
keyParamIndex = idx;
|
|
722
|
+
}
|
|
723
|
+
// Narrow the LAST parameter (the value being tested). Single-param
|
|
724
|
+
// predicates (`a -> Boolean`) narrow their sole parameter;
|
|
725
|
+
// multi-parameter predicates such as `k -> { [k] :: a } -> Boolean`
|
|
726
|
+
// narrow the trailing record.
|
|
727
|
+
const paramIndex = params.length - 1;
|
|
728
|
+
const narrowedParam = params[paramIndex];
|
|
729
|
+
const paramName = narrowedParam.tag === 'TVar'
|
|
730
|
+
? narrowedParam.name
|
|
731
|
+
: narrowedParam.tag === 'TLabel' && narrowedParam.kind === 'var'
|
|
732
|
+
? narrowedParam.name
|
|
733
|
+
: '';
|
|
734
|
+
schemeResult = {
|
|
735
|
+
...schemeResult,
|
|
736
|
+
typePredicate: {
|
|
737
|
+
paramName,
|
|
738
|
+
paramIndex,
|
|
739
|
+
narrowedType,
|
|
740
|
+
...(keyVarName ? { keyVarName } : {}),
|
|
741
|
+
...(keyParamIndex !== undefined ? { keyParamIndex } : {}),
|
|
742
|
+
},
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
catch (e) {
|
|
749
|
+
/* istanbul ignore else — parseTypeSignature/parseMethodTypeSignature only throw TypeParseError */
|
|
750
|
+
if (e instanceof typeParser_1.TypeParseError) {
|
|
751
|
+
error = e.message;
|
|
752
|
+
}
|
|
753
|
+
else {
|
|
754
|
+
error = `Failed to parse type signature: ${raw}`;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
const isNarrowableMethodType = narrowDirective && !error && methodType
|
|
758
|
+
&& (0, types_1.getReturnType)(methodType).tag === 'TCon'
|
|
759
|
+
&& (0, types_1.getReturnType)(methodType).name === types_1.T_BOOLEAN;
|
|
760
|
+
// ::hidden marks the following annotation as completion-suppressed.
|
|
761
|
+
// It is most useful on instance/static member annotations
|
|
762
|
+
// (`Type#prop`, `Type.method`); on other annotations the flag has no
|
|
763
|
+
// effect and is silently ignored (no error). Standalone
|
|
764
|
+
// `::hidden` directives (no annotation below) are handled separately
|
|
765
|
+
// by `extractStandaloneHiddenMarkers`.
|
|
766
|
+
// Optional `::hidden <Qualified.Name>` / `::private <Qualified.Name>`
|
|
767
|
+
// target argument. When present, only the registration target whose
|
|
768
|
+
// qualified name equals the argument is hidden/privatised. Stacked
|
|
769
|
+
// directives are merged: an argument-less directive hides every member,
|
|
770
|
+
// while each argument-bearing directive selects its own target.
|
|
771
|
+
const isMemberName = !!annotationName
|
|
772
|
+
&& (annotationName.includes('#') || annotationName.includes('.'));
|
|
773
|
+
let hiddenFlag = false;
|
|
774
|
+
if (hiddenInfo.present && isMemberName
|
|
775
|
+
&& (hiddenInfo.hasNoArg || hiddenInfo.args.has(annotationName))) {
|
|
776
|
+
hiddenFlag = true;
|
|
777
|
+
}
|
|
778
|
+
let privateFlag = false;
|
|
779
|
+
if (privateInfo.present && isMemberName
|
|
780
|
+
&& (privateInfo.hasNoArg || privateInfo.args.has(annotationName))) {
|
|
781
|
+
privateFlag = true;
|
|
782
|
+
// ::private implies ::hidden — privates are also filtered from
|
|
783
|
+
// completions.
|
|
784
|
+
hiddenFlag = true;
|
|
785
|
+
}
|
|
786
|
+
const annotation = {
|
|
787
|
+
raw,
|
|
788
|
+
scheme: schemeResult,
|
|
789
|
+
error,
|
|
790
|
+
commentStart,
|
|
791
|
+
commentEnd,
|
|
792
|
+
receiver,
|
|
793
|
+
methodType,
|
|
794
|
+
signatureNameStart,
|
|
795
|
+
signatureNameEnd,
|
|
796
|
+
...((isNarrowableMethodType || isNarrowableBooleanMember) && narrowDirective
|
|
797
|
+
? { narrowVariant: narrowDirective.narrowedTypeRaw }
|
|
798
|
+
: {}),
|
|
799
|
+
...(narrowDirective
|
|
800
|
+
? { narrowLoc: { start: narrowDirective.start, end: narrowDirective.end } }
|
|
801
|
+
: {}),
|
|
802
|
+
...(hiddenFlag ? { hidden: true } : {}),
|
|
803
|
+
...(privateFlag ? { private: true } : {}),
|
|
804
|
+
};
|
|
805
|
+
// Trailing annotation (`const filter = ...; // filter :: String`): when
|
|
806
|
+
// the comment sits AFTER a statement on the same line and that statement
|
|
807
|
+
// declares exactly the annotated name, it documents THAT binding — attach
|
|
808
|
+
// backward instead of leaking forward to the next declaration (which
|
|
809
|
+
// would produce a spurious name-mismatch diagnostic there).
|
|
810
|
+
let attached = annotationName
|
|
811
|
+
? findSameLineDeclaration(ast, commentStart, source, annotationName)
|
|
812
|
+
: null;
|
|
813
|
+
// Try to find the declaration that follows this comment
|
|
814
|
+
if (!attached)
|
|
815
|
+
attached = findNextDeclaration(ast, commentEnd, source, annotationName);
|
|
816
|
+
// If another HM annotation comment sits between this annotation and the
|
|
817
|
+
// found declaration, the declaration belongs to that closer annotation —
|
|
818
|
+
// detach it from this one.
|
|
819
|
+
if (attached) {
|
|
820
|
+
for (let k = i + 1; k < comments.length; k++) {
|
|
821
|
+
if (skipIndices.has(k))
|
|
822
|
+
continue;
|
|
823
|
+
const c = comments[k];
|
|
824
|
+
if (c.start >= attached.nodeStart)
|
|
825
|
+
break;
|
|
826
|
+
if (c.start < commentEnd)
|
|
827
|
+
continue;
|
|
828
|
+
if (HM_PATTERN.test(c.value)) {
|
|
829
|
+
attached = null;
|
|
830
|
+
break;
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
// A type alias (`// Thing :: { … }`) followed by a BLANK line and an
|
|
835
|
+
// unrelated declaration (`// How long …` / `const TTL = 1000;`) stands
|
|
836
|
+
// alone: it is not that declaration's annotation, and must stay a type
|
|
837
|
+
// name that importers can see.
|
|
838
|
+
if (attached && annotationName && /^[A-Z]/.test(annotationName)
|
|
839
|
+
&& !annotationName.includes('#') && !annotationName.includes('.')
|
|
840
|
+
&& attached.name !== undefined && attached.name !== annotationName
|
|
841
|
+
&& /\n[ \t]*\r?\n/.test(source.slice(commentEnd, attached.nodeStart))) {
|
|
842
|
+
attached = null;
|
|
843
|
+
}
|
|
844
|
+
if (attached) {
|
|
845
|
+
// When the annotation has an explicit name with '#' and the attached
|
|
846
|
+
// declaration also has '#', validate that the method name part matches.
|
|
847
|
+
// e.g. `// Left#mapp :: ...` above `Left.prototype.map` is invalid
|
|
848
|
+
// because 'mapp' !== 'map', but `// Either#map :: ...` is valid.
|
|
849
|
+
if (annotationName && attached.name
|
|
850
|
+
&& annotationName.includes('#') && attached.name.includes('#')) {
|
|
851
|
+
const annMethod = annotationName.split('#')[1];
|
|
852
|
+
const attachedMethod = attached.name.split('#')[1];
|
|
853
|
+
annotation.name = annotationName;
|
|
854
|
+
annotation.nodeStart = attached.nodeStart;
|
|
855
|
+
annotation.nameStart = attached.nameStart;
|
|
856
|
+
annotation.nameEnd = attached.nameEnd;
|
|
857
|
+
if (annMethod !== attachedMethod) {
|
|
858
|
+
// Don't set error here — the diagnostic will be produced by the
|
|
859
|
+
// inference engine on the function declaration so the user sees
|
|
860
|
+
// the problem at the implementation site, not at the annotation.
|
|
861
|
+
annotation.methodNameMismatch = attachedMethod;
|
|
862
|
+
annotation.mismatchNameStart = attached.nameStart;
|
|
863
|
+
annotation.mismatchNameEnd = attached.nameEnd;
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
else if (annotationName && attached.name
|
|
867
|
+
&& annotationName.includes('#') && !attached.name.includes('#')) {
|
|
868
|
+
// Method annotation above a plain variable/function.
|
|
869
|
+
// Several valid patterns:
|
|
870
|
+
// (a) Top-level: `// Box#value :: Box a ~> a` above `const Box = ...`
|
|
871
|
+
// The base type name matches the variable → normal attachment.
|
|
872
|
+
// (b) Prototype: `// Box#map :: ...` above `function Box$prototype$map`
|
|
873
|
+
// The JS prototype pattern matches the annotation.
|
|
874
|
+
// (c) Nested: `// Either2#map :: ...` above `const map = fn => ...`
|
|
875
|
+
// The method name part should match the variable name.
|
|
876
|
+
// (d) Top-level: `// Either#map :: ...` above `class Left { ... }`
|
|
877
|
+
// Unrelated — the attached name is a class/type not a method impl.
|
|
878
|
+
const annBase = annotationName.split('#')[0];
|
|
879
|
+
const annMethod = annotationName.split('#')[1];
|
|
880
|
+
annotation.name = annotationName;
|
|
881
|
+
annotation.nodeStart = attached.nodeStart;
|
|
882
|
+
annotation.nameStart = attached.nameStart;
|
|
883
|
+
annotation.nameEnd = attached.nameEnd;
|
|
884
|
+
if (annBase === attached.name) {
|
|
885
|
+
// Case (a): annotation for type "Box" above its constructor "Box"
|
|
886
|
+
// — valid, no mismatch.
|
|
887
|
+
}
|
|
888
|
+
else if (attached.name === `${annBase}$prototype$${annMethod}`) {
|
|
889
|
+
// Case (b): JS prototype pattern — valid, no mismatch.
|
|
890
|
+
}
|
|
891
|
+
else if (chainedNames.some(cn => cn.name === attached.name)) {
|
|
892
|
+
// Case (e): chained annotation `// Array#chain :: builtIn.Array :: T`
|
|
893
|
+
// attached to `builtIn.Array = …`. The attached binding is one of
|
|
894
|
+
// the chained-secondary targets, not a method-name mismatch.
|
|
895
|
+
}
|
|
896
|
+
else if (attached.name.includes('.')) {
|
|
897
|
+
// Case (f): single-name method annotation attached to a member
|
|
898
|
+
// assignment on a plain-object host
|
|
899
|
+
// (`// Array#chain :: T` above `builtIn.Array = …`). The host
|
|
900
|
+
// record extension is incidental — the annotation registers a
|
|
901
|
+
// method on `Array`, not on `builtIn.Array`. No mismatch.
|
|
902
|
+
}
|
|
903
|
+
else if (/^[a-z_$]/.test(attached.name) && annMethod !== attached.name) {
|
|
904
|
+
// Case (c): nested lowercase variable name should match method name
|
|
905
|
+
// part. Uppercase names (case d) are classes/type constructors and
|
|
906
|
+
// don't represent method implementations.
|
|
907
|
+
annotation.methodNameMismatch = attached.name;
|
|
908
|
+
annotation.mismatchNameStart = attached.nameStart;
|
|
909
|
+
annotation.mismatchNameEnd = attached.nameEnd;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
else if (annotationName && attached.name
|
|
913
|
+
&& !annotationName.includes('#') && !annotationName.includes('.')
|
|
914
|
+
&& !attached.name.includes('#') && !attached.name.includes('.')
|
|
915
|
+
&& annotationName !== attached.name
|
|
916
|
+
&& /^[a-z_$]/.test(annotationName)) {
|
|
917
|
+
// Regular function/variable name mismatch:
|
|
918
|
+
// e.g. `// memoize :: ...` above `const memoizee = ...`
|
|
919
|
+
// Only applies when the annotation name is lowercase-initial —
|
|
920
|
+
// uppercase names (e.g. Person, Either) are type aliases or
|
|
921
|
+
// constructors that intentionally differ from the next declaration.
|
|
922
|
+
annotation.name = annotationName;
|
|
923
|
+
annotation.nodeStart = attached.nodeStart;
|
|
924
|
+
annotation.nameStart = attached.nameStart;
|
|
925
|
+
annotation.nameEnd = attached.nameEnd;
|
|
926
|
+
annotation.nameMismatch = attached.name;
|
|
927
|
+
}
|
|
928
|
+
else {
|
|
929
|
+
annotation.name = annotationName || attached.name;
|
|
930
|
+
annotation.nodeStart = attached.nodeStart;
|
|
931
|
+
annotation.nameStart = attached.nameStart;
|
|
932
|
+
annotation.nameEnd = attached.nameEnd;
|
|
933
|
+
if (!annotationName && attached.name) {
|
|
934
|
+
annotation.namelessOnNamed = attached.name;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
else if (annotationName) {
|
|
939
|
+
annotation.name = annotationName;
|
|
940
|
+
}
|
|
941
|
+
annotations.push(annotation);
|
|
942
|
+
// Emit one secondary annotation per chained name in `// A :: B :: C :: T`.
|
|
943
|
+
for (const cn of chainedNames) {
|
|
944
|
+
// A `::hidden` / `::private` directive above a chained annotation hides
|
|
945
|
+
// (or privatises) every member-shaped registration target in the chain,
|
|
946
|
+
// regardless of which position holds the binding name. This covers
|
|
947
|
+
// orderings like `// builtIn.Array :: Array#reduce :: T` where the real
|
|
948
|
+
// registration target (`Array#reduce`) is a chained secondary rather
|
|
949
|
+
// than the primary name.
|
|
950
|
+
const cnIsMember = cn.name.includes('#') || cn.name.includes('.');
|
|
951
|
+
const secondaryPrivate = privateInfo.present && cnIsMember
|
|
952
|
+
&& (privateInfo.hasNoArg || privateInfo.args.has(cn.name));
|
|
953
|
+
const secondaryHidden = ((hiddenInfo.present && (hiddenInfo.hasNoArg || hiddenInfo.args.has(cn.name)))
|
|
954
|
+
|| secondaryPrivate) && cnIsMember;
|
|
955
|
+
const secondary = {
|
|
956
|
+
raw,
|
|
957
|
+
scheme: chainedError ? null : schemeResult,
|
|
958
|
+
error: chainedError ?? error,
|
|
959
|
+
commentStart,
|
|
960
|
+
commentEnd,
|
|
961
|
+
receiver,
|
|
962
|
+
methodType,
|
|
963
|
+
signatureNameStart: cn.start,
|
|
964
|
+
signatureNameEnd: cn.end,
|
|
965
|
+
name: cn.name,
|
|
966
|
+
chainedSecondary: true,
|
|
967
|
+
// Inherit attachment from the primary so hover/sig-help can find
|
|
968
|
+
// the same declaration via any of the chained names.
|
|
969
|
+
nodeStart: annotation.nodeStart,
|
|
970
|
+
nameStart: annotation.nameStart,
|
|
971
|
+
nameEnd: annotation.nameEnd,
|
|
972
|
+
...(secondaryHidden ? { hidden: true } : {}),
|
|
973
|
+
...(secondaryPrivate ? { private: true } : {}),
|
|
974
|
+
};
|
|
975
|
+
annotations.push(secondary);
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
return annotations;
|
|
979
|
+
}
|
|
980
|
+
/**
|
|
981
|
+
* Build a map from declaration name -> parsed Scheme for all valid annotations.
|
|
982
|
+
*
|
|
983
|
+
* When the same name appears more than once with non-method annotations
|
|
984
|
+
* (e.g. two `Table :: ...` lines in a `.hm` file) the schemes are merged
|
|
985
|
+
* into a single overloaded scheme using `mergeOverloadSchemes`. Call sites
|
|
986
|
+
* use the existing union-unification path to pick the matching branch.
|
|
987
|
+
*/
|
|
988
|
+
function buildAnnotationMap(source) {
|
|
989
|
+
const annotations = extractAnnotations(source);
|
|
990
|
+
const map = new Map();
|
|
991
|
+
const declOf = declarationStarts(annotations);
|
|
992
|
+
const firstDecl = new Map();
|
|
993
|
+
// Lazy import to avoid a cycle: env.ts -> types.ts is fine, but
|
|
994
|
+
// commentParser.ts is loaded from many places that don't otherwise
|
|
995
|
+
// pull in env.ts.
|
|
996
|
+
const { mergeOverloadSchemes } = require('./hm/env');
|
|
997
|
+
for (const ann of annotations) {
|
|
998
|
+
if (!ann.name || !ann.scheme || ann.namelessOnNamed)
|
|
999
|
+
continue;
|
|
1000
|
+
// `Name()` (instance-callable) annotations are stored separately via
|
|
1001
|
+
// `extractInstanceCallables`; skip them here so they never enter the
|
|
1002
|
+
// value-level `annotationMap` (where they'd be misread as a constructor
|
|
1003
|
+
// scheme by hover/sig-help/arity/alias passes).
|
|
1004
|
+
if (ann.name.endsWith('()'))
|
|
1005
|
+
continue;
|
|
1006
|
+
const existing = map.get(ann.name);
|
|
1007
|
+
// Overloads are annotation lines above the SAME declaration. A second
|
|
1008
|
+
// declaration with the same name (a nested helper such as `safeReject`
|
|
1009
|
+
// in two closures) is a different binding: it keeps its own annotation,
|
|
1010
|
+
// reachable through `buildAnnotationsByDeclaration`; the map keeps the
|
|
1011
|
+
// first.
|
|
1012
|
+
const at = declOf.get(ann);
|
|
1013
|
+
if (!firstDecl.has(ann.name))
|
|
1014
|
+
firstDecl.set(ann.name, at);
|
|
1015
|
+
const first = firstDecl.get(ann.name);
|
|
1016
|
+
if (existing && first !== undefined && at !== undefined && first !== at)
|
|
1017
|
+
continue;
|
|
1018
|
+
if (existing && existing.scheme
|
|
1019
|
+
&& !ann.name.includes('#')) {
|
|
1020
|
+
// Plain names AND dotted statics (`Task.ask`) merge into an overload
|
|
1021
|
+
// union; method-form (`#`) annotations go through the method registry
|
|
1022
|
+
// instead. Without the dotted case, the LAST `Task.ask :: ...` line
|
|
1023
|
+
// would silently replace earlier overloads (an FP library's `ask :: () -> ...`
|
|
1024
|
+
// / `ask :: (r -> a) -> ...` pair).
|
|
1025
|
+
const merged = mergeOverloadSchemes(existing.scheme, ann.scheme);
|
|
1026
|
+
// Keep the FIRST annotation's metadata (location, raw text) as the
|
|
1027
|
+
// anchor; record the merged scheme. Hover/signature surfaces can
|
|
1028
|
+
// present all branches by re-walking the original annotation list.
|
|
1029
|
+
map.set(ann.name, { ...existing, scheme: merged, origin: 'local' });
|
|
1030
|
+
}
|
|
1031
|
+
else {
|
|
1032
|
+
map.set(ann.name, { ...ann, origin: 'local' });
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
return map;
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* Build a map from type name -> array of Schemes for all `Name() :: T`
|
|
1039
|
+
* (instance-callable) annotations in the source. Multiple `Name()`
|
|
1040
|
+
* declarations produce multiple overload entries, in declaration order.
|
|
1041
|
+
*
|
|
1042
|
+
* Used by the inference engine and hover/signature help to look up the
|
|
1043
|
+
* callable signatures of an uppercase TCon-typed value (e.g. an
|
|
1044
|
+
* `QueryTag {row}` instance is callable as `({}) -> RTask r e [b]`).
|
|
1045
|
+
*/
|
|
1046
|
+
function extractInstanceCallables(source) {
|
|
1047
|
+
const annotations = extractAnnotations(source);
|
|
1048
|
+
const map = new Map();
|
|
1049
|
+
for (const ann of annotations) {
|
|
1050
|
+
if (!ann.name || !ann.scheme)
|
|
1051
|
+
continue;
|
|
1052
|
+
if (!ann.name.endsWith('()'))
|
|
1053
|
+
continue;
|
|
1054
|
+
const baseName = ann.name.slice(0, -2);
|
|
1055
|
+
if (!baseName)
|
|
1056
|
+
continue;
|
|
1057
|
+
const list = map.get(baseName);
|
|
1058
|
+
if (list)
|
|
1059
|
+
list.push(ann.scheme);
|
|
1060
|
+
else
|
|
1061
|
+
map.set(baseName, [ann.scheme]);
|
|
1062
|
+
}
|
|
1063
|
+
return map;
|
|
1064
|
+
}
|
|
1065
|
+
/**
|
|
1066
|
+
* The declaration each annotation belongs to. Only the LAST line of an
|
|
1067
|
+
* overload block carries `nodeStart`; the earlier lines belong to the next
|
|
1068
|
+
* same-named annotation that does.
|
|
1069
|
+
*/
|
|
1070
|
+
const declarationStartsMemo = new WeakMap();
|
|
1071
|
+
function declarationStarts(annotations) {
|
|
1072
|
+
const memo = declarationStartsMemo.get(annotations);
|
|
1073
|
+
if (memo)
|
|
1074
|
+
return memo;
|
|
1075
|
+
const out = new Map();
|
|
1076
|
+
declarationStartsMemo.set(annotations, out);
|
|
1077
|
+
const nextByName = new Map();
|
|
1078
|
+
for (let i = annotations.length - 1; i >= 0; i--) {
|
|
1079
|
+
const ann = annotations[i];
|
|
1080
|
+
if (!ann.name)
|
|
1081
|
+
continue;
|
|
1082
|
+
if (ann.nodeStart !== undefined)
|
|
1083
|
+
nextByName.set(ann.name, ann.nodeStart);
|
|
1084
|
+
out.set(ann, ann.nodeStart ?? nextByName.get(ann.name));
|
|
1085
|
+
}
|
|
1086
|
+
return out;
|
|
1087
|
+
}
|
|
1088
|
+
/**
|
|
1089
|
+
* Map from declaration node start → that declaration's own annotation, with
|
|
1090
|
+
* its overload lines merged (as `buildAnnotationMap` does per name). Lets
|
|
1091
|
+
* same-named bindings in different scopes find their own signature.
|
|
1092
|
+
*/
|
|
1093
|
+
const byDeclarationCache = [];
|
|
1094
|
+
function buildAnnotationsByDeclaration(source) {
|
|
1095
|
+
for (const hit of byDeclarationCache)
|
|
1096
|
+
if (hit.source === source)
|
|
1097
|
+
return hit.map;
|
|
1098
|
+
const map = buildAnnotationsByDeclarationUncached(source);
|
|
1099
|
+
byDeclarationCache.unshift({ source, map });
|
|
1100
|
+
if (byDeclarationCache.length > 8)
|
|
1101
|
+
byDeclarationCache.pop();
|
|
1102
|
+
return map;
|
|
1103
|
+
}
|
|
1104
|
+
function buildAnnotationsByDeclarationUncached(source) {
|
|
1105
|
+
const { mergeOverloadSchemes } = require('./hm/env');
|
|
1106
|
+
const map = new Map();
|
|
1107
|
+
const annotations = extractAnnotations(source);
|
|
1108
|
+
const declOf = declarationStarts(annotations);
|
|
1109
|
+
for (const ann of annotations) {
|
|
1110
|
+
const at = declOf.get(ann);
|
|
1111
|
+
if (!ann.name || !ann.scheme || ann.namelessOnNamed || at === undefined)
|
|
1112
|
+
continue;
|
|
1113
|
+
if (ann.name.endsWith('()') || ann.name.includes('#'))
|
|
1114
|
+
continue;
|
|
1115
|
+
const existing = map.get(at);
|
|
1116
|
+
if (existing?.scheme && existing.name === ann.name) {
|
|
1117
|
+
map.set(at, { ...existing, scheme: mergeOverloadSchemes(existing.scheme, ann.scheme), origin: 'local' });
|
|
1118
|
+
}
|
|
1119
|
+
else if (!existing) {
|
|
1120
|
+
map.set(at, { ...ann, nodeStart: at, origin: 'local' });
|
|
1121
|
+
}
|
|
1122
|
+
}
|
|
1123
|
+
return map;
|
|
1124
|
+
}
|
|
1125
|
+
/**
|
|
1126
|
+
* Build a map from node start offset -> TypeAnnotation.
|
|
1127
|
+
*/
|
|
1128
|
+
function buildAnnotationByOffset(source) {
|
|
1129
|
+
const annotations = extractAnnotations(source);
|
|
1130
|
+
const map = new Map();
|
|
1131
|
+
for (const ann of annotations) {
|
|
1132
|
+
if (ann.nodeStart !== undefined && !ann.namelessOnNamed) {
|
|
1133
|
+
map.set(ann.nodeStart, ann);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
return map;
|
|
1137
|
+
}
|
|
1138
|
+
// ---------------------------------------------------------------------------
|
|
1139
|
+
// ::types directive extraction
|
|
1140
|
+
// ---------------------------------------------------------------------------
|
|
1141
|
+
/** Regex to match `// ::types <specifier>` directives in comments. */
|
|
1142
|
+
const TYPES_DIRECTIVE_PATTERN = /^[\s*]*::types\s+(.+)$/m;
|
|
1143
|
+
/** Regex to match `// ::constraint Name v { ... }` directives in comments. */
|
|
1144
|
+
const CONSTRAINT_DIRECTIVE_PATTERN = /^[\s*]*::constraint\s+/m;
|
|
1145
|
+
/**
|
|
1146
|
+
* Extract all `// ::types <specifier>` directives from a JavaScript source string.
|
|
1147
|
+
*
|
|
1148
|
+
* These directives tell the type system to load type annotations from another
|
|
1149
|
+
* file or package, without requiring a runtime import. Supports:
|
|
1150
|
+
* - Relative paths: `// ::types ./demo`
|
|
1151
|
+
* - Package names: `// ::types fantasy-box`
|
|
1152
|
+
* - Scoped packages: `// ::types @scope/package`
|
|
1153
|
+
*/
|
|
1154
|
+
function extractTypeDirectives(source) {
|
|
1155
|
+
return extractTypeDirectivesWithLocations(source).map(d => d.specifier);
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Extract all `// ::types <specifier>` directives with their source locations.
|
|
1159
|
+
* Returns an array of `{ specifier, start, end }` objects.
|
|
1160
|
+
*/
|
|
1161
|
+
function extractTypeDirectivesWithLocations(source) {
|
|
1162
|
+
const parsed = parseWithComments(source);
|
|
1163
|
+
if (!parsed) {
|
|
1164
|
+
// If parsing fails, try regex-based extraction from raw source as fallback
|
|
1165
|
+
const directives = [];
|
|
1166
|
+
const lineRegex = /\/\/\s*::types\s+(.+)/g;
|
|
1167
|
+
let match;
|
|
1168
|
+
while ((match = lineRegex.exec(source)) !== null) {
|
|
1169
|
+
directives.push({ specifier: match[1].trim(), start: match.index, end: match.index + match[0].length });
|
|
1170
|
+
}
|
|
1171
|
+
return directives;
|
|
1172
|
+
}
|
|
1173
|
+
const { comments } = parsed;
|
|
1174
|
+
const directives = [];
|
|
1175
|
+
for (const comment of comments) {
|
|
1176
|
+
const match = TYPES_DIRECTIVE_PATTERN.exec(comment.value);
|
|
1177
|
+
if (match) {
|
|
1178
|
+
directives.push({ specifier: match[1].trim(), start: comment.start, end: comment.end });
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
return directives;
|
|
1182
|
+
}
|
|
1183
|
+
/** Regex matching `// ::prefer <Name>(, <Name>)* from <specifier>` directives. */
|
|
1184
|
+
const PREFER_DIRECTIVE_PATTERN = /^[\s*]*::prefer\s+([A-Z][A-Za-z0-9_]*(?:\s*,\s*[A-Z][A-Za-z0-9_]*)*)\s+from\s+(\S+)\s*$/m;
|
|
1185
|
+
/**
|
|
1186
|
+
* Extract `// ::prefer <Name>(, <Name>)* from <specifier>` directives. Used
|
|
1187
|
+
* to disambiguate when the same uppercase type/constructor name (e.g.
|
|
1188
|
+
* `Prop`) is defined by multiple loaded sidecars/globals. Multiple names
|
|
1189
|
+
* may share one directive, e.g. `// ::prefer Prop, Table from query-builder`.
|
|
1190
|
+
* Returns a Map from each declared name to its preferred origin specifier
|
|
1191
|
+
* (bare package name or relative path, exactly as written). When the
|
|
1192
|
+
* same name appears in multiple directives, the last wins.
|
|
1193
|
+
*/
|
|
1194
|
+
function extractPreferDirectives(source) {
|
|
1195
|
+
const result = new Map();
|
|
1196
|
+
const parsed = parseWithComments(source);
|
|
1197
|
+
const consume = (names, specifier) => {
|
|
1198
|
+
for (const raw of names.split(',')) {
|
|
1199
|
+
const name = raw.trim();
|
|
1200
|
+
if (name)
|
|
1201
|
+
result.set(name, specifier);
|
|
1202
|
+
}
|
|
1203
|
+
};
|
|
1204
|
+
if (parsed) {
|
|
1205
|
+
for (const comment of parsed.comments) {
|
|
1206
|
+
const m = PREFER_DIRECTIVE_PATTERN.exec(comment.value);
|
|
1207
|
+
if (m)
|
|
1208
|
+
consume(m[1], m[2]);
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
else {
|
|
1212
|
+
// Fallback: regex on raw source when parsing fails
|
|
1213
|
+
const re = /\/\/\s*::prefer\s+([A-Z][A-Za-z0-9_]*(?:\s*,\s*[A-Z][A-Za-z0-9_]*)*)\s+from\s+(\S+)/g;
|
|
1214
|
+
let m;
|
|
1215
|
+
while ((m = re.exec(source)) !== null)
|
|
1216
|
+
consume(m[1], m[2]);
|
|
1217
|
+
}
|
|
1218
|
+
return result;
|
|
1219
|
+
}
|
|
1220
|
+
/** Regex to match `// ::extend <AliasName> <typeExpr>` directives in comments. */
|
|
1221
|
+
const EXTEND_DIRECTIVE_PATTERN = /^[\s*]*::extend\s+([A-Z]\w*)\s+(.+?)\s*$/m;
|
|
1222
|
+
/**
|
|
1223
|
+
* Extract all `// ::extend <AliasName> <typeExpr>` directives from source.
|
|
1224
|
+
*
|
|
1225
|
+
* Each directive appends `typeExpr` to the named union-alias post-build
|
|
1226
|
+
* (see `applyAliasExtensions` in src/infer/annotations.ts). Generic
|
|
1227
|
+
* mechanism — independent of any particular library. When `typeExpr` is
|
|
1228
|
+
* itself a `|`-union, its branches are flattened into the target.
|
|
1229
|
+
*
|
|
1230
|
+
* Returns an array of `{ name, raw, start, end }` where `raw` is the
|
|
1231
|
+
* unparsed RHS to be fed into `parseTypeSignature` later.
|
|
1232
|
+
*/
|
|
1233
|
+
function extractAliasExtensions(source) {
|
|
1234
|
+
const parsed = parseWithComments(source);
|
|
1235
|
+
const results = [];
|
|
1236
|
+
if (!parsed) {
|
|
1237
|
+
// Fallback: regex on raw source when parsing fails.
|
|
1238
|
+
const lineRegex = /\/\/\s*::extend\s+([A-Z]\w*)\s+(.+)/g;
|
|
1239
|
+
let m;
|
|
1240
|
+
while ((m = lineRegex.exec(source)) !== null) {
|
|
1241
|
+
results.push({ name: m[1], raw: m[2].trim(), start: m.index, end: m.index + m[0].length });
|
|
1242
|
+
}
|
|
1243
|
+
return results;
|
|
1244
|
+
}
|
|
1245
|
+
for (const comment of parsed.comments) {
|
|
1246
|
+
const m = EXTEND_DIRECTIVE_PATTERN.exec(comment.value);
|
|
1247
|
+
if (m) {
|
|
1248
|
+
results.push({ name: m[1], raw: m[2].trim(), start: comment.start, end: comment.end });
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
return results;
|
|
1252
|
+
}
|
|
1253
|
+
/**
|
|
1254
|
+
* Extract all `// ::constraint ...` directive comment bodies from source.
|
|
1255
|
+
* Returns the raw comment text for each ::constraint comment.
|
|
1256
|
+
*/
|
|
1257
|
+
function extractConstraintDirectives(source) {
|
|
1258
|
+
const parsed = parseWithComments(source);
|
|
1259
|
+
if (!parsed) {
|
|
1260
|
+
// Fallback: regex on raw source
|
|
1261
|
+
const results = [];
|
|
1262
|
+
const lineRegex = /\/\/\s*(::constraint\s+.+)/g;
|
|
1263
|
+
let match;
|
|
1264
|
+
while ((match = lineRegex.exec(source)) !== null) {
|
|
1265
|
+
results.push({ text: match[1], start: match.index, end: match.index + match[0].length });
|
|
1266
|
+
}
|
|
1267
|
+
return results;
|
|
1268
|
+
}
|
|
1269
|
+
const { comments } = parsed;
|
|
1270
|
+
const results = [];
|
|
1271
|
+
// Continuation rule for `//` directives: a `// ::constraint` line whose
|
|
1272
|
+
// body has unbalanced `{`/`}` is concatenated with adjacent `//` line
|
|
1273
|
+
// comments until the braces are balanced. This allows multi-line
|
|
1274
|
+
// definitions like:
|
|
1275
|
+
// // ::constraint Indexed r e s {
|
|
1276
|
+
// // r :: [e] | Map s e,
|
|
1277
|
+
// // s :: Number | String
|
|
1278
|
+
// // }
|
|
1279
|
+
// Block comments (/* ... */) already contain their newlines in `value`;
|
|
1280
|
+
// we apply the same brace-balance heuristic line-by-line.
|
|
1281
|
+
const braceDelta = (s) => {
|
|
1282
|
+
let d = 0;
|
|
1283
|
+
for (const ch of s) {
|
|
1284
|
+
if (ch === '{')
|
|
1285
|
+
d++;
|
|
1286
|
+
else if (ch === '}')
|
|
1287
|
+
d--;
|
|
1288
|
+
}
|
|
1289
|
+
return d;
|
|
1290
|
+
};
|
|
1291
|
+
const flattenBlock = (value) => {
|
|
1292
|
+
const lines = value
|
|
1293
|
+
.split(/\r?\n/)
|
|
1294
|
+
.map(l => l.replace(/^\s*\*\s?/, '').replace(/^\s+/, ' '))
|
|
1295
|
+
.map(l => l.trim());
|
|
1296
|
+
let out = lines[0] ?? '';
|
|
1297
|
+
let depth = braceDelta(out);
|
|
1298
|
+
for (let i = 1; i < lines.length; i++) {
|
|
1299
|
+
const ln = lines[i];
|
|
1300
|
+
if (!ln)
|
|
1301
|
+
continue;
|
|
1302
|
+
if (depth <= 0)
|
|
1303
|
+
break;
|
|
1304
|
+
out += ' ' + ln;
|
|
1305
|
+
depth += braceDelta(ln);
|
|
1306
|
+
}
|
|
1307
|
+
return out;
|
|
1308
|
+
};
|
|
1309
|
+
for (let i = 0; i < comments.length; i++) {
|
|
1310
|
+
const comment = comments[i];
|
|
1311
|
+
if (!CONSTRAINT_DIRECTIVE_PATTERN.test(comment.value))
|
|
1312
|
+
continue;
|
|
1313
|
+
let text = comment.type === 'Block'
|
|
1314
|
+
? flattenBlock(comment.value).trim()
|
|
1315
|
+
: comment.value.trim();
|
|
1316
|
+
let end = comment.end;
|
|
1317
|
+
// Line-comment continuation: keep scanning adjacent `//` line comments
|
|
1318
|
+
// until the running `{`/`}` balance is zero.
|
|
1319
|
+
if (comment.type === 'Line') {
|
|
1320
|
+
let depth = braceDelta(text);
|
|
1321
|
+
let j = i + 1;
|
|
1322
|
+
while (j < comments.length && depth > 0) {
|
|
1323
|
+
const next = comments[j];
|
|
1324
|
+
if (next.type !== 'Line')
|
|
1325
|
+
break;
|
|
1326
|
+
text += ' ' + next.value.trim();
|
|
1327
|
+
depth += braceDelta(next.value);
|
|
1328
|
+
end = next.end;
|
|
1329
|
+
j++;
|
|
1330
|
+
}
|
|
1331
|
+
i = j - 1;
|
|
1332
|
+
}
|
|
1333
|
+
results.push({ text, start: comment.start, end });
|
|
1334
|
+
}
|
|
1335
|
+
return results;
|
|
1336
|
+
}
|
|
1337
|
+
// ---------------------------------------------------------------------------
|
|
1338
|
+
// ::rep directive extraction
|
|
1339
|
+
// ---------------------------------------------------------------------------
|
|
1340
|
+
/** Regex to match `// ::rep <Constraint> <Type#method>` (instance) or
|
|
1341
|
+
* `// ::rep <Constraint> <Type.method>` (static) directives.
|
|
1342
|
+
* Examples: `// ::rep Foldable Array#reduce`, `// ::rep Foldable Array.off`.
|
|
1343
|
+
* The separator distinguishes an instance method (`#`, carries a `~>`
|
|
1344
|
+
* receiver) from a static method (`.`, no receiver). */
|
|
1345
|
+
const REP_DIRECTIVE_PATTERN = /^[\s*]*::rep\s+([A-Z][\w$]*)\s+([A-Z][\w$]*)(#|\.)([\w$]+)\s*$/m;
|
|
1346
|
+
/**
|
|
1347
|
+
* Extract all `// ::rep <Constraint> <Type#method>` directives.
|
|
1348
|
+
*
|
|
1349
|
+
* A `::rep` directive declares that the named container method (annotated
|
|
1350
|
+
* locally in the same file) represents the constraint's like-named method
|
|
1351
|
+
* when discharging that constraint — scoped to the function that carries it
|
|
1352
|
+
* (see Fase 5). Returns one entry per well-formed directive; malformed
|
|
1353
|
+
* directives are silently skipped (the caller emits no parser error).
|
|
1354
|
+
*/
|
|
1355
|
+
/**
|
|
1356
|
+
* Every `::curried` directive in the comments of a JavaScript source. The
|
|
1357
|
+
* directive belongs in `.hm` files only; in JavaScript the curried behaviour
|
|
1358
|
+
* of a function follows from its code (see `setupPass`).
|
|
1359
|
+
*/
|
|
1360
|
+
function extractCurriedDirectiveLocations(source) {
|
|
1361
|
+
if (!source.includes('::curried'))
|
|
1362
|
+
return [];
|
|
1363
|
+
const parsed = parseWithComments(source);
|
|
1364
|
+
if (!parsed)
|
|
1365
|
+
return [];
|
|
1366
|
+
const out = [];
|
|
1367
|
+
for (const comment of parsed.comments) {
|
|
1368
|
+
const lines = comment.type === 'Block' ? comment.value.split(/\r?\n/) : [comment.value];
|
|
1369
|
+
if (lines.some(l => /^[\s*]*::curried\b/.test(l)))
|
|
1370
|
+
out.push({ start: comment.start, end: comment.end });
|
|
1371
|
+
}
|
|
1372
|
+
return out;
|
|
1373
|
+
}
|
|
1374
|
+
function extractRepDirectives(source) {
|
|
1375
|
+
const parsed = parseWithComments(source);
|
|
1376
|
+
const results = [];
|
|
1377
|
+
const collect = (text, start, end) => {
|
|
1378
|
+
const m = REP_DIRECTIVE_PATTERN.exec(text);
|
|
1379
|
+
if (!m)
|
|
1380
|
+
return;
|
|
1381
|
+
results.push({
|
|
1382
|
+
constraint: m[1],
|
|
1383
|
+
typeName: m[2],
|
|
1384
|
+
isStatic: m[3] === '.',
|
|
1385
|
+
methodName: m[4],
|
|
1386
|
+
start,
|
|
1387
|
+
end,
|
|
1388
|
+
});
|
|
1389
|
+
};
|
|
1390
|
+
if (!parsed) {
|
|
1391
|
+
const lineRegex = /\/\/\s*(::rep\s+.+)/g;
|
|
1392
|
+
let match;
|
|
1393
|
+
while ((match = lineRegex.exec(source)) !== null) {
|
|
1394
|
+
collect(match[1], match.index, match.index + match[0].length);
|
|
1395
|
+
}
|
|
1396
|
+
return results;
|
|
1397
|
+
}
|
|
1398
|
+
for (const comment of parsed.comments) {
|
|
1399
|
+
if (comment.type === 'Block') {
|
|
1400
|
+
for (const line of comment.value.split(/\r?\n/)) {
|
|
1401
|
+
collect(line.replace(/^\s*\*\s?/, '').trim(), comment.start, comment.end);
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
else {
|
|
1405
|
+
collect(comment.value.trim(), comment.start, comment.end);
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
return results;
|
|
1409
|
+
}
|
|
1410
|
+
// ---------------------------------------------------------------------------
|
|
1411
|
+
// ::global directive extraction
|
|
1412
|
+
// ---------------------------------------------------------------------------
|
|
1413
|
+
const GLOBAL_DIRECTIVE_PATTERN = /^[\s*]*::global\s+/m;
|
|
1414
|
+
/**
|
|
1415
|
+
* Extract all `// ::global ...` directive comment bodies from source.
|
|
1416
|
+
* Returns the raw comment text (without the leading `//`) for each ::global comment.
|
|
1417
|
+
*
|
|
1418
|
+
* Supports:
|
|
1419
|
+
* - Instance methods: `// ::global Array#ap :: [a] ~> [a -> b] -> [b]`
|
|
1420
|
+
* - Static methods: `// ::global Array.empty :: () -> [a]`
|
|
1421
|
+
*/
|
|
1422
|
+
function extractGlobalDirectives(source) {
|
|
1423
|
+
const parsed = parseWithComments(source);
|
|
1424
|
+
if (!parsed) {
|
|
1425
|
+
const results = [];
|
|
1426
|
+
const lineRegex = /\/\/\s*(::global\s+.+)/g;
|
|
1427
|
+
let match;
|
|
1428
|
+
while ((match = lineRegex.exec(source)) !== null) {
|
|
1429
|
+
results.push({ text: match[1], start: match.index, end: match.index + match[0].length });
|
|
1430
|
+
}
|
|
1431
|
+
return results;
|
|
1432
|
+
}
|
|
1433
|
+
const { comments } = parsed;
|
|
1434
|
+
const results = [];
|
|
1435
|
+
for (const comment of comments) {
|
|
1436
|
+
if (GLOBAL_DIRECTIVE_PATTERN.test(comment.value)) {
|
|
1437
|
+
results.push({
|
|
1438
|
+
text: comment.value.trim(),
|
|
1439
|
+
start: comment.start,
|
|
1440
|
+
end: comment.end,
|
|
1441
|
+
});
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
return results;
|
|
1445
|
+
}
|
|
1446
|
+
/**
|
|
1447
|
+
* Split `body` on top-level occurrences of a single-character separator,
|
|
1448
|
+
* ignoring separators nested inside parentheses `()` or braces `{}`. Used to
|
|
1449
|
+
* split variant alternations (`|`) and record fields (`,`) without breaking on
|
|
1450
|
+
* delimiters that live inside a variant's field types (e.g. `(Map String a)`
|
|
1451
|
+
* or `{ status :: Int, url :: String }`).
|
|
1452
|
+
*/
|
|
1453
|
+
function splitTopLevel(body, sep) {
|
|
1454
|
+
const out = [];
|
|
1455
|
+
let depth = 0;
|
|
1456
|
+
let cur = '';
|
|
1457
|
+
for (let i = 0; i < body.length; i++) {
|
|
1458
|
+
const ch = body[i];
|
|
1459
|
+
if (ch === '(' || ch === '{')
|
|
1460
|
+
depth++;
|
|
1461
|
+
else if (ch === ')' || ch === '}')
|
|
1462
|
+
depth = Math.max(0, depth - 1);
|
|
1463
|
+
if (ch === sep && depth === 0) {
|
|
1464
|
+
out.push(cur);
|
|
1465
|
+
cur = '';
|
|
1466
|
+
}
|
|
1467
|
+
else {
|
|
1468
|
+
cur += ch;
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
out.push(cur);
|
|
1472
|
+
return out;
|
|
1473
|
+
}
|
|
1474
|
+
/** Return the index of the delimiter matching the opener at `open`, or -1. */
|
|
1475
|
+
function matchDelim(text, open) {
|
|
1476
|
+
let depth = 0;
|
|
1477
|
+
for (let i = open; i < text.length; i++) {
|
|
1478
|
+
const c = text[i];
|
|
1479
|
+
if (c === '(' || c === '{')
|
|
1480
|
+
depth++;
|
|
1481
|
+
else if (c === ')' || c === '}') {
|
|
1482
|
+
depth--;
|
|
1483
|
+
if (depth === 0)
|
|
1484
|
+
return i;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
return -1;
|
|
1488
|
+
}
|
|
1489
|
+
/**
|
|
1490
|
+
* Delimiter-depth delta of `s`: openers minus closers. `includeBrackets`
|
|
1491
|
+
* additionally counts `[`/`]`. Used to maintain a RUNNING depth while
|
|
1492
|
+
* joining multi-line comment annotations so each appended line costs
|
|
1493
|
+
* O(line) instead of re-scanning the whole accumulated body (which made
|
|
1494
|
+
* joining a huge generated record annotation — e.g. an 11k-line
|
|
1495
|
+
* `Tables :: { … }` sidecar — quadratic: seconds of pure char-scanning
|
|
1496
|
+
* per cold parse). A running `depth <= 0` test replaces the old
|
|
1497
|
+
* `isSignatureComplete(acc)` / `!hasOpenDelimiters(acc)` full-body scans.
|
|
1498
|
+
*/
|
|
1499
|
+
function delimDepthDelta(s, includeBrackets) {
|
|
1500
|
+
let d = 0;
|
|
1501
|
+
for (let i = 0; i < s.length; i++) {
|
|
1502
|
+
const c = s[i];
|
|
1503
|
+
if (c === '(' || c === '{' || (includeBrackets && c === '['))
|
|
1504
|
+
d++;
|
|
1505
|
+
else if (c === ')' || c === '}' || (includeBrackets && c === ']'))
|
|
1506
|
+
d--;
|
|
1507
|
+
}
|
|
1508
|
+
return d;
|
|
1509
|
+
}
|
|
1510
|
+
/**
|
|
1511
|
+
* Split a variant body (everything after the variant name) into its top-level
|
|
1512
|
+
* field chunks. A field is a bare word, a balanced `(...)` group, or a
|
|
1513
|
+
* balanced `{...}` record group. Whitespace inside groups is collapsed to a
|
|
1514
|
+
* single space. Returns null on unbalanced or stray delimiters.
|
|
1515
|
+
*/
|
|
1516
|
+
function splitVariantFields(rest) {
|
|
1517
|
+
const fields = [];
|
|
1518
|
+
let i = 0;
|
|
1519
|
+
const n = rest.length;
|
|
1520
|
+
while (i < n) {
|
|
1521
|
+
while (i < n && /\s/.test(rest[i]))
|
|
1522
|
+
i++;
|
|
1523
|
+
if (i >= n)
|
|
1524
|
+
break;
|
|
1525
|
+
const ch = rest[i];
|
|
1526
|
+
if (ch === '(' || ch === '{') {
|
|
1527
|
+
const end = matchDelim(rest, i);
|
|
1528
|
+
if (end < 0)
|
|
1529
|
+
return null;
|
|
1530
|
+
fields.push(rest.slice(i, end + 1).replace(/\s+/g, ' ').trim());
|
|
1531
|
+
i = end + 1;
|
|
1532
|
+
}
|
|
1533
|
+
else if (ch === ')' || ch === '}') {
|
|
1534
|
+
return null;
|
|
1535
|
+
}
|
|
1536
|
+
else {
|
|
1537
|
+
let j = i;
|
|
1538
|
+
while (j < n && !/[\s(){}]/.test(rest[j]))
|
|
1539
|
+
j++;
|
|
1540
|
+
fields.push(rest.slice(i, j));
|
|
1541
|
+
i = j;
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
return fields;
|
|
1545
|
+
}
|
|
1546
|
+
/**
|
|
1547
|
+
* Parse a single variant string into its name + fields. Handles positional
|
|
1548
|
+
* fields (`Redirect Number String`), parenthesized type applications
|
|
1549
|
+
* (`Render String (Object String a)`), and record fields
|
|
1550
|
+
* (`Redirect { status :: Number, url :: String }`). Returns null when the
|
|
1551
|
+
* first token isn't an uppercase name or delimiters are unbalanced.
|
|
1552
|
+
*/
|
|
1553
|
+
function parseVariant(vs) {
|
|
1554
|
+
const trimmed = vs.trim();
|
|
1555
|
+
const m = /^([A-Z]\w*)/.exec(trimmed);
|
|
1556
|
+
if (!m)
|
|
1557
|
+
return null;
|
|
1558
|
+
const fields = splitVariantFields(trimmed.slice(m[0].length));
|
|
1559
|
+
if (fields === null)
|
|
1560
|
+
return null;
|
|
1561
|
+
return { name: m[1], fields };
|
|
1562
|
+
}
|
|
1563
|
+
/**
|
|
1564
|
+
* Collect type-variable names (lowercase identifiers) referenced inside a
|
|
1565
|
+
* field type text, in first-appearance order. Record labels — the identifier
|
|
1566
|
+
* immediately before each `::` inside `{...}` — are field names, not type
|
|
1567
|
+
* variables, and are skipped. Nested records / parens are handled recursively.
|
|
1568
|
+
*/
|
|
1569
|
+
function collectVarsFromTypeText(text, seen, out) {
|
|
1570
|
+
let i = 0;
|
|
1571
|
+
const n = text.length;
|
|
1572
|
+
while (i < n) {
|
|
1573
|
+
const ch = text[i];
|
|
1574
|
+
if (ch === '{') {
|
|
1575
|
+
const end = matchDelim(text, i);
|
|
1576
|
+
if (end < 0) {
|
|
1577
|
+
i++;
|
|
1578
|
+
continue;
|
|
1579
|
+
}
|
|
1580
|
+
collectVarsFromRecord(text.slice(i + 1, end), seen, out);
|
|
1581
|
+
i = end + 1;
|
|
1582
|
+
}
|
|
1583
|
+
else if (ch === '(') {
|
|
1584
|
+
const end = matchDelim(text, i);
|
|
1585
|
+
if (end < 0) {
|
|
1586
|
+
i++;
|
|
1587
|
+
continue;
|
|
1588
|
+
}
|
|
1589
|
+
collectVarsFromTypeText(text.slice(i + 1, end), seen, out);
|
|
1590
|
+
i = end + 1;
|
|
1591
|
+
}
|
|
1592
|
+
else if (/[A-Za-z_]/.test(ch)) {
|
|
1593
|
+
let j = i;
|
|
1594
|
+
while (j < n && /[\w.]/.test(text[j]))
|
|
1595
|
+
j++;
|
|
1596
|
+
const word = text.slice(i, j);
|
|
1597
|
+
if (/^[a-z]/.test(word) && !word.includes('.') && !seen.has(word)) {
|
|
1598
|
+
seen.add(word);
|
|
1599
|
+
out.push(word);
|
|
1600
|
+
}
|
|
1601
|
+
i = j;
|
|
1602
|
+
}
|
|
1603
|
+
else {
|
|
1604
|
+
i++;
|
|
1605
|
+
}
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
/** Collect type vars from a record body (`label :: T, label :: T`), skipping labels. */
|
|
1609
|
+
function collectVarsFromRecord(inner, seen, out) {
|
|
1610
|
+
for (const part of splitTopLevel(inner, ',')) {
|
|
1611
|
+
const dbl = part.indexOf('::');
|
|
1612
|
+
// The text before the first `::` is the field label (not a type var).
|
|
1613
|
+
const typePart = dbl < 0 ? part : part.slice(dbl + 2);
|
|
1614
|
+
collectVarsFromTypeText(typePart, seen, out);
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* Return the parent type variables a single field references, in order.
|
|
1619
|
+
* Exposed so the sumtype identifier-union builder can map complex fields
|
|
1620
|
+
* (records / parenthesized applications) back to their type parameters.
|
|
1621
|
+
*/
|
|
1622
|
+
function fieldTypeVars(field) {
|
|
1623
|
+
const seen = new Set();
|
|
1624
|
+
const out = [];
|
|
1625
|
+
collectVarsFromTypeText(field, seen, out);
|
|
1626
|
+
return out;
|
|
1627
|
+
}
|
|
1628
|
+
/**
|
|
1629
|
+
* Extract the labelled fields from a record-style variant field
|
|
1630
|
+
* (`{ ext :: String, handler :: EngineFn }` -> [{name:'ext', type:'String'},
|
|
1631
|
+
* {name:'handler', type:'EngineFn'}]). Returns [] when `field` is not a
|
|
1632
|
+
* `{...}` record group (e.g. a positional word or parenthesized application).
|
|
1633
|
+
*/
|
|
1634
|
+
function recordFields(field) {
|
|
1635
|
+
const t = field.trim();
|
|
1636
|
+
if (!t.startsWith('{') || !t.endsWith('}'))
|
|
1637
|
+
return [];
|
|
1638
|
+
const inner = t.slice(1, -1);
|
|
1639
|
+
const out = [];
|
|
1640
|
+
for (const part of splitTopLevel(inner, ',')) {
|
|
1641
|
+
const dbl = part.indexOf('::');
|
|
1642
|
+
if (dbl < 0)
|
|
1643
|
+
continue;
|
|
1644
|
+
const name = part.slice(0, dbl).trim();
|
|
1645
|
+
const type = part.slice(dbl + 2).trim();
|
|
1646
|
+
if (/^[A-Za-z_$][\w$]*$/.test(name))
|
|
1647
|
+
out.push({ name, type });
|
|
1648
|
+
}
|
|
1649
|
+
return out;
|
|
1650
|
+
}
|
|
1651
|
+
/**
|
|
1652
|
+
* Detect whether an annotation with an uppercase name and a raw body
|
|
1653
|
+
* represents the shorthand data type syntax:
|
|
1654
|
+
* `// TypeName :: Variant1 a | Variant2 b`
|
|
1655
|
+
* Variant fields may be positional words, parenthesized type applications, or
|
|
1656
|
+
* record groups; at least two `|`-separated variants are required so that a
|
|
1657
|
+
* plain type annotation like `Maybe a` is not mistaken for a declaration.
|
|
1658
|
+
*/
|
|
1659
|
+
/**
|
|
1660
|
+
* Built-in type names that can never be the variant of a user sum type:
|
|
1661
|
+
* `Cell :: String | Number | Null` is an alias for a union of existing
|
|
1662
|
+
* types, not a declaration of three new constructors.
|
|
1663
|
+
*/
|
|
1664
|
+
const NON_VARIANT_TYPE_NAMES = new Set([
|
|
1665
|
+
'Number', 'String', 'Boolean', 'Null', 'Undefined', 'Void', 'Any', 'Object',
|
|
1666
|
+
'Array', 'Date', 'Error', 'Promise', 'RegExp', 'Map', 'Set', 'BigInt', 'Symbol',
|
|
1667
|
+
'ReactElement', 'Element',
|
|
1668
|
+
]);
|
|
1669
|
+
function isDataShorthand(annotationName, raw) {
|
|
1670
|
+
if (!/^[A-Z]/.test(annotationName))
|
|
1671
|
+
return false;
|
|
1672
|
+
if (annotationName.includes('#') || annotationName.includes('.'))
|
|
1673
|
+
return false;
|
|
1674
|
+
const variantStrs = splitTopLevel(raw, '|').map(s => s.trim()).filter(s => s.length > 0);
|
|
1675
|
+
if (variantStrs.length < 2)
|
|
1676
|
+
return false;
|
|
1677
|
+
const variants = variantStrs.map(vs => parseVariant(vs));
|
|
1678
|
+
if (variants.some(v => v === null))
|
|
1679
|
+
return false;
|
|
1680
|
+
return !variants.some(v => NON_VARIANT_TYPE_NAMES.has(v.name));
|
|
1681
|
+
}
|
|
1682
|
+
/**
|
|
1683
|
+
* Parse the shorthand data type syntax:
|
|
1684
|
+
* `// TypeName :: Variant1 a | Variant2 b`
|
|
1685
|
+
*
|
|
1686
|
+
* Type variables are inferred from the variant fields in order of first
|
|
1687
|
+
* appearance. Fields can be type variables (lowercase) or concrete types
|
|
1688
|
+
* (uppercase), e.g. `// Result :: Ok Int | Err String`.
|
|
1689
|
+
* Returns null if the body doesn't match.
|
|
1690
|
+
*/
|
|
1691
|
+
function parseDataShorthand(typeName, body, commentStart, commentEnd) {
|
|
1692
|
+
const variantStrs = splitTopLevel(body, '|').map(s => s.trim()).filter(s => s.length > 0);
|
|
1693
|
+
if (variantStrs.length < 2)
|
|
1694
|
+
return null;
|
|
1695
|
+
const variants = [];
|
|
1696
|
+
const seenVars = new Set();
|
|
1697
|
+
const typeVars = [];
|
|
1698
|
+
for (const vs of variantStrs) {
|
|
1699
|
+
const variant = parseVariant(vs);
|
|
1700
|
+
if (variant === null)
|
|
1701
|
+
return null;
|
|
1702
|
+
for (const f of variant.fields) {
|
|
1703
|
+
collectVarsFromTypeText(f, seenVars, typeVars);
|
|
1704
|
+
}
|
|
1705
|
+
variants.push(variant);
|
|
1706
|
+
}
|
|
1707
|
+
return { name: typeName, typeVars, variants, commentStart, commentEnd };
|
|
1708
|
+
}
|
|
1709
|
+
/** A sum-type alternation body is "incomplete" when it ends with a trailing `|`. */
|
|
1710
|
+
function isAlternationIncomplete(body) {
|
|
1711
|
+
return /\|\s*$/.test(body.trim());
|
|
1712
|
+
}
|
|
1713
|
+
/**
|
|
1714
|
+
* Starting from the line comment at `index` whose accumulated signature body
|
|
1715
|
+
* is `raw` (ending at `commentEnd`), scan forward and consume contiguous
|
|
1716
|
+
* continuation line comments that belong to the same multi-line `//`
|
|
1717
|
+
* annotation (e.g. a record body `{ … }` split across several `//` lines, or
|
|
1718
|
+
* a constraint signature broken after `=>`).
|
|
1719
|
+
*
|
|
1720
|
+
* Returns the joined `raw`, the new `commentEnd`, and the indices consumed.
|
|
1721
|
+
* Shared by `extractAnnotationsImpl` (to build the annotation) and by
|
|
1722
|
+
* `extractDataDirectives` (to avoid mis-parsing a continuation line such as
|
|
1723
|
+
* `Route :: String -> String | RegExp -> RouteFn -> a` as its own sumtype
|
|
1724
|
+
* declaration).
|
|
1725
|
+
*/
|
|
1726
|
+
function joinLineContinuations(comments, index, source, raw, commentEnd) {
|
|
1727
|
+
const consumed = [];
|
|
1728
|
+
// Incremental joining state: `parts` accumulates chunks (joined once at the
|
|
1729
|
+
// end), `depth` tracks the running delimiter balance of the accumulated
|
|
1730
|
+
// body, and `tail` is the last appended chunk. The trailing-continuation
|
|
1731
|
+
// and completeness tests below are equivalent to running them on the full
|
|
1732
|
+
// accumulated body (which ends with `tail` and whose delimiter balance is
|
|
1733
|
+
// `depth`) but keep each iteration O(line) instead of O(accumulated).
|
|
1734
|
+
const parts = [raw];
|
|
1735
|
+
let depth = delimDepthDelta(raw, true);
|
|
1736
|
+
let tail = raw;
|
|
1737
|
+
for (let j = index + 1; j < comments.length; j++) {
|
|
1738
|
+
const next = comments[j];
|
|
1739
|
+
if (next.type !== 'Line')
|
|
1740
|
+
break;
|
|
1741
|
+
// Only allow whitespace between this comment and the next.
|
|
1742
|
+
const gap = source.slice(commentEnd, next.start);
|
|
1743
|
+
if (!/^\s*$/.test(gap))
|
|
1744
|
+
break;
|
|
1745
|
+
const continuationText = next.value.trim();
|
|
1746
|
+
if (continuationText.length === 0)
|
|
1747
|
+
break;
|
|
1748
|
+
const startsWithContinuation = /^(?:=>|->|~>|[|,)}\]])/.test(continuationText);
|
|
1749
|
+
const endsWithContinuation = /(?:=>|->|~>|[|,])\s*$/.test(tail);
|
|
1750
|
+
if (depth <= 0 && !startsWithContinuation && !endsWithContinuation)
|
|
1751
|
+
break;
|
|
1752
|
+
// A nameless annotation (`// :: ...`) or a directive starts something new.
|
|
1753
|
+
const nextText = next.value;
|
|
1754
|
+
const nextMatch = HM_PATTERN.exec(nextText);
|
|
1755
|
+
if (nextMatch && !nextMatch[1])
|
|
1756
|
+
break;
|
|
1757
|
+
if (TYPES_DIRECTIVE_PATTERN.test(nextText))
|
|
1758
|
+
break;
|
|
1759
|
+
if (CONSTRAINT_DIRECTIVE_PATTERN.test(nextText))
|
|
1760
|
+
break;
|
|
1761
|
+
if (EXTEND_DIRECTIVE_PATTERN.test(nextText))
|
|
1762
|
+
break;
|
|
1763
|
+
parts.push(continuationText);
|
|
1764
|
+
depth += delimDepthDelta(continuationText, true);
|
|
1765
|
+
tail = continuationText;
|
|
1766
|
+
commentEnd = next.end;
|
|
1767
|
+
consumed.push(j);
|
|
1768
|
+
}
|
|
1769
|
+
return { raw: parts.join(' '), commentEnd, consumed };
|
|
1770
|
+
}
|
|
1771
|
+
/**
|
|
1772
|
+
* Compute the set of comment indices that are *continuation* lines of a
|
|
1773
|
+
* multi-line `//` annotation (or of a multi-line `//` data shorthand). These
|
|
1774
|
+
* indices must NOT be treated as the start of an independent annotation or
|
|
1775
|
+
* sumtype declaration. Mirrors the forward-scan performed by
|
|
1776
|
+
* `extractAnnotationsImpl` so both extractors agree on grouping.
|
|
1777
|
+
*/
|
|
1778
|
+
function computeContinuationSkips(comments, source) {
|
|
1779
|
+
const skip = new Set();
|
|
1780
|
+
for (let i = 0; i < comments.length; i++) {
|
|
1781
|
+
if (skip.has(i))
|
|
1782
|
+
continue;
|
|
1783
|
+
const comment = comments[i];
|
|
1784
|
+
const match = HM_PATTERN.exec(comment.value);
|
|
1785
|
+
if (!match)
|
|
1786
|
+
continue;
|
|
1787
|
+
const annotationName = match[1];
|
|
1788
|
+
// A multi-line `//` data shorthand consumes its own continuation lines.
|
|
1789
|
+
if (annotationName && /^[A-Z]/.test(annotationName)) {
|
|
1790
|
+
const ds = readDataShorthand(comments, i, source);
|
|
1791
|
+
if (ds) {
|
|
1792
|
+
for (const c of ds.consumed)
|
|
1793
|
+
skip.add(c);
|
|
1794
|
+
continue;
|
|
1795
|
+
}
|
|
1796
|
+
}
|
|
1797
|
+
if (comment.type !== 'Line')
|
|
1798
|
+
continue; // block continuations are intra-comment
|
|
1799
|
+
const raw = match[2].trim();
|
|
1800
|
+
const { consumed } = joinLineContinuations(comments, i, source, raw, comment.end);
|
|
1801
|
+
for (const c of consumed)
|
|
1802
|
+
skip.add(c);
|
|
1803
|
+
}
|
|
1804
|
+
return skip;
|
|
1805
|
+
}
|
|
1806
|
+
/**
|
|
1807
|
+
* If `comments[index]` begins a (possibly multi-line) sum-type shorthand
|
|
1808
|
+
* declaration, return the joined declaration plus the indices of any
|
|
1809
|
+
* continuation line comments that were consumed.
|
|
1810
|
+
*
|
|
1811
|
+
* Supports:
|
|
1812
|
+
* - single-line: `// T :: A x | B y`
|
|
1813
|
+
* - block comment: variants split across several physical lines
|
|
1814
|
+
* - line comments: consecutive `//` lines joined while the alternation is
|
|
1815
|
+
* incomplete (a trailing `|`, or the next line begins with `|`).
|
|
1816
|
+
*/
|
|
1817
|
+
function readDataShorthand(comments, index, source) {
|
|
1818
|
+
const comment = comments[index];
|
|
1819
|
+
const hmMatch = HM_PATTERN.exec(comment.value);
|
|
1820
|
+
let name;
|
|
1821
|
+
let firstBody;
|
|
1822
|
+
let matchIndex;
|
|
1823
|
+
if (hmMatch && hmMatch[1]) {
|
|
1824
|
+
name = hmMatch[1];
|
|
1825
|
+
firstBody = (hmMatch[2] ?? '').trim();
|
|
1826
|
+
matchIndex = hmMatch.index;
|
|
1827
|
+
}
|
|
1828
|
+
else if (comment.type === 'Line') {
|
|
1829
|
+
// The first line may declare only the name with an empty body
|
|
1830
|
+
// (`// Component ::`), with every variant on the following `//` lines.
|
|
1831
|
+
// HM_PATTERN requires at least one char after `::`, so match it here.
|
|
1832
|
+
const empty = /^[\s*]*([A-Za-z_$][\w$]*)\s*::\s*$/.exec(comment.value);
|
|
1833
|
+
if (!empty)
|
|
1834
|
+
return null;
|
|
1835
|
+
name = empty[1];
|
|
1836
|
+
firstBody = '';
|
|
1837
|
+
matchIndex = empty.index;
|
|
1838
|
+
}
|
|
1839
|
+
else {
|
|
1840
|
+
return null;
|
|
1841
|
+
}
|
|
1842
|
+
if (!/^[A-Z]/.test(name) || name.includes('#') || name.includes('.'))
|
|
1843
|
+
return null;
|
|
1844
|
+
const consumed = [];
|
|
1845
|
+
let commentEnd = comment.end;
|
|
1846
|
+
let body;
|
|
1847
|
+
if (comment.type === 'Block') {
|
|
1848
|
+
const dblIdx = comment.value.indexOf('::', matchIndex);
|
|
1849
|
+
if (dblIdx < 0)
|
|
1850
|
+
return null;
|
|
1851
|
+
const lines = comment.value.slice(dblIdx + 2).split('\n')
|
|
1852
|
+
.map(l => l.replace(/^\s*\*?\s?/, '').trim());
|
|
1853
|
+
const parts = [];
|
|
1854
|
+
// Running joining state (see delimDepthDelta): depth = delimiter balance
|
|
1855
|
+
// of the accumulated body, lastPart = last non-empty appended line.
|
|
1856
|
+
let depth = 0;
|
|
1857
|
+
let lastPart = '';
|
|
1858
|
+
for (const line of lines) {
|
|
1859
|
+
if (parts.length === 0) {
|
|
1860
|
+
if (line.length > 0) {
|
|
1861
|
+
parts.push(line);
|
|
1862
|
+
depth += delimDepthDelta(line, false);
|
|
1863
|
+
lastPart = line;
|
|
1864
|
+
}
|
|
1865
|
+
continue;
|
|
1866
|
+
}
|
|
1867
|
+
// Keep joining while the alternation is unfinished: either a trailing `|`
|
|
1868
|
+
// or an unbalanced `(`/`{` (a record / paren field spanning lines).
|
|
1869
|
+
const incomplete = isAlternationIncomplete(lastPart) || depth > 0;
|
|
1870
|
+
if (line.length === 0) {
|
|
1871
|
+
if (incomplete)
|
|
1872
|
+
continue;
|
|
1873
|
+
break;
|
|
1874
|
+
}
|
|
1875
|
+
if (incomplete || /^\|/.test(line)) {
|
|
1876
|
+
parts.push(line);
|
|
1877
|
+
depth += delimDepthDelta(line, false);
|
|
1878
|
+
lastPart = line;
|
|
1879
|
+
}
|
|
1880
|
+
else
|
|
1881
|
+
break;
|
|
1882
|
+
}
|
|
1883
|
+
body = parts.join(' ').replace(/\s+/g, ' ').trim();
|
|
1884
|
+
}
|
|
1885
|
+
else {
|
|
1886
|
+
// Incremental joining state, mirroring the block path above: appending a
|
|
1887
|
+
// line costs O(line) — testing the FULL accumulated body per line made
|
|
1888
|
+
// joining huge generated multi-line annotations quadratic.
|
|
1889
|
+
const parts = firstBody.length > 0 ? [firstBody.replace(/\s+/g, ' ')] : [];
|
|
1890
|
+
let depth = delimDepthDelta(firstBody, false);
|
|
1891
|
+
let lastPart = firstBody;
|
|
1892
|
+
for (let j = index + 1; j < comments.length; j++) {
|
|
1893
|
+
const next = comments[j];
|
|
1894
|
+
if (next.type !== 'Line')
|
|
1895
|
+
break;
|
|
1896
|
+
const gap = source.slice(commentEnd, next.start);
|
|
1897
|
+
if (!/^\s*$/.test(gap))
|
|
1898
|
+
break;
|
|
1899
|
+
const nextText = next.value.trim();
|
|
1900
|
+
if (nextText.length === 0)
|
|
1901
|
+
break;
|
|
1902
|
+
// Keep joining while the declaration is unfinished — nothing captured yet
|
|
1903
|
+
// (empty first-line body), a trailing `|`, or an unbalanced `(`/`{` (a
|
|
1904
|
+
// record / paren field spanning lines) — OR the next line begins a new
|
|
1905
|
+
// alternation branch (`| Variant …`). This covers the vertically laid
|
|
1906
|
+
// out form:
|
|
1907
|
+
// // Component ::
|
|
1908
|
+
// // Engine { ext :: String }
|
|
1909
|
+
// // | Locals { obj :: Object String Any }
|
|
1910
|
+
const incomplete = parts.length === 0
|
|
1911
|
+
|| isAlternationIncomplete(lastPart)
|
|
1912
|
+
|| depth > 0;
|
|
1913
|
+
const nextIsAlternation = /^\|/.test(nextText);
|
|
1914
|
+
if (!incomplete && !nextIsAlternation)
|
|
1915
|
+
break;
|
|
1916
|
+
parts.push(nextText.replace(/\s+/g, ' '));
|
|
1917
|
+
depth += delimDepthDelta(nextText, false);
|
|
1918
|
+
lastPart = nextText;
|
|
1919
|
+
commentEnd = next.end;
|
|
1920
|
+
consumed.push(j);
|
|
1921
|
+
}
|
|
1922
|
+
body = parts.join(' ').trim();
|
|
1923
|
+
}
|
|
1924
|
+
if (!body || !isDataShorthand(name, body))
|
|
1925
|
+
return null;
|
|
1926
|
+
const nameIdx = comment.value.indexOf(name, matchIndex);
|
|
1927
|
+
return { name, body, commentStart: comment.start, commentEnd, nameIdx, consumed };
|
|
1928
|
+
}
|
|
1929
|
+
/**
|
|
1930
|
+
* Extract all sum type declarations from a JavaScript source string.
|
|
1931
|
+
*
|
|
1932
|
+
* Recognises the `// TypeName :: Variant1 a | Variant2 b` syntax, including
|
|
1933
|
+
* multi-line forms (block comments whose variants span several lines, or
|
|
1934
|
+
* consecutive `//` line comments joined by a trailing/leading `|`).
|
|
1935
|
+
*/
|
|
1936
|
+
function extractDataDirectives(source) {
|
|
1937
|
+
const parsed = parseWithComments(source);
|
|
1938
|
+
if (!parsed)
|
|
1939
|
+
return [];
|
|
1940
|
+
const { comments } = parsed;
|
|
1941
|
+
const results = [];
|
|
1942
|
+
// Comment indices that are continuation lines of a multi-line `//`
|
|
1943
|
+
// annotation (e.g. the fields inside `Component#matchWith :: Component ~> {
|
|
1944
|
+
// … }`). These must not be re-parsed here as standalone sumtype decls.
|
|
1945
|
+
const skip = computeContinuationSkips(comments, source);
|
|
1946
|
+
for (let ci = 0; ci < comments.length; ci++) {
|
|
1947
|
+
if (skip.has(ci))
|
|
1948
|
+
continue;
|
|
1949
|
+
const ds = readDataShorthand(comments, ci, source);
|
|
1950
|
+
if (!ds)
|
|
1951
|
+
continue;
|
|
1952
|
+
const decl = parseDataShorthand(ds.name, ds.body, ds.commentStart, ds.commentEnd);
|
|
1953
|
+
if (decl) {
|
|
1954
|
+
if (ds.nameIdx >= 0) {
|
|
1955
|
+
decl.signatureNameStart = ds.commentStart + 2 + ds.nameIdx;
|
|
1956
|
+
decl.signatureNameEnd = decl.signatureNameStart + ds.name.length;
|
|
1957
|
+
}
|
|
1958
|
+
results.push(decl);
|
|
1959
|
+
}
|
|
1960
|
+
// Consumed continuation comments are the contiguous indices that follow.
|
|
1961
|
+
ci += ds.consumed.length;
|
|
1962
|
+
}
|
|
1963
|
+
return results;
|
|
1964
|
+
}
|
|
1965
|
+
// ---------------------------------------------------------------------------
|
|
1966
|
+
// ::ignore-file / ::ignore directive extraction
|
|
1967
|
+
// ---------------------------------------------------------------------------
|
|
1968
|
+
/** Regex to match `// ::ignore-file` directive. */
|
|
1969
|
+
const IGNORE_FILE_PATTERN = /^[\s*]*::ignore-file\s*$/m;
|
|
1970
|
+
/** Regex to match `// ::ignore` directive. */
|
|
1971
|
+
const IGNORE_LINE_PATTERN = /^[\s*]*::ignore\s*$/m;
|
|
1972
|
+
/**
|
|
1973
|
+
* Check whether the source contains an `// ::ignore-file` directive.
|
|
1974
|
+
* When present, all diagnostics for the file should be suppressed.
|
|
1975
|
+
*/
|
|
1976
|
+
function hasIgnoreFileDirective(source) {
|
|
1977
|
+
const parsed = parseWithComments(source);
|
|
1978
|
+
if (!parsed) {
|
|
1979
|
+
// Fallback: regex on raw source
|
|
1980
|
+
return /\/\/\s*::ignore-file\s*$/m.test(source) ||
|
|
1981
|
+
/\/\*[\s*]*::ignore-file\s*\*\//m.test(source);
|
|
1982
|
+
}
|
|
1983
|
+
for (const comment of parsed.comments) {
|
|
1984
|
+
if (IGNORE_FILE_PATTERN.test(comment.value)) {
|
|
1985
|
+
return true;
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
return false;
|
|
1989
|
+
}
|
|
1990
|
+
/**
|
|
1991
|
+
* Extract 0-based line numbers that should be ignored due to `// ::ignore`
|
|
1992
|
+
* directives. The directive suppresses diagnostics on the **next** line.
|
|
1993
|
+
*/
|
|
1994
|
+
function extractIgnoreLineDirectives(source) {
|
|
1995
|
+
const ignoredLines = new Set();
|
|
1996
|
+
const parsed = parseWithComments(source);
|
|
1997
|
+
if (!parsed) {
|
|
1998
|
+
// Fallback: regex on raw source
|
|
1999
|
+
const lines = source.split('\n');
|
|
2000
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2001
|
+
if (/\/\/\s*::ignore\s*$/.test(lines[i]) ||
|
|
2002
|
+
/\/\*[\s*]*::ignore\s*\*\//.test(lines[i])) {
|
|
2003
|
+
ignoredLines.add(i + 1); // next line (0-based)
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
return ignoredLines;
|
|
2007
|
+
}
|
|
2008
|
+
for (const comment of parsed.comments) {
|
|
2009
|
+
if (IGNORE_LINE_PATTERN.test(comment.value)) {
|
|
2010
|
+
// The directive is on the comment's line; ignore the NEXT line.
|
|
2011
|
+
const loc = comment.loc;
|
|
2012
|
+
if (loc) {
|
|
2013
|
+
// loc.end.line is 1-based; the next line in 0-based is loc.end.line
|
|
2014
|
+
ignoredLines.add(loc.end.line); // 0-based next line
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
return ignoredLines;
|
|
2019
|
+
}
|
|
2020
|
+
/** Regex to match `// ::ignore-function` directive. */
|
|
2021
|
+
const IGNORE_FUNCTION_PATTERN = /^[\s*]*::ignore-function\s*$/m;
|
|
2022
|
+
/**
|
|
2023
|
+
* Extract 0-based line numbers that should be ignored due to `// ::ignore-function`
|
|
2024
|
+
* directives. The directive suppresses diagnostics on the entire function body
|
|
2025
|
+
* following the comment.
|
|
2026
|
+
*/
|
|
2027
|
+
function extractIgnoreFunctionDirectives(source) {
|
|
2028
|
+
const ignoredLines = new Set();
|
|
2029
|
+
const parsed = parseWithComments(source);
|
|
2030
|
+
if (!parsed) {
|
|
2031
|
+
// Can't parse AST — fall back to ignoring just the next line
|
|
2032
|
+
const lines = source.split('\n');
|
|
2033
|
+
for (let i = 0; i < lines.length; i++) {
|
|
2034
|
+
if (/\/\/\s*::ignore-function\s*$/.test(lines[i]) ||
|
|
2035
|
+
/\/\*[\s*]*::ignore-function\s*\*\//m.test(lines[i])) {
|
|
2036
|
+
ignoredLines.add(i + 1);
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
return ignoredLines;
|
|
2040
|
+
}
|
|
2041
|
+
const { ast, comments } = parsed;
|
|
2042
|
+
// Collect directive comment positions (1-based line numbers)
|
|
2043
|
+
const directiveLines = new Set();
|
|
2044
|
+
for (const comment of comments) {
|
|
2045
|
+
if (IGNORE_FUNCTION_PATTERN.test(comment.value)) {
|
|
2046
|
+
const loc = comment.loc;
|
|
2047
|
+
if (loc) {
|
|
2048
|
+
directiveLines.add(loc.end.line); // 1-based line of the comment
|
|
2049
|
+
}
|
|
2050
|
+
}
|
|
2051
|
+
}
|
|
2052
|
+
if (directiveLines.size === 0)
|
|
2053
|
+
return ignoredLines;
|
|
2054
|
+
// Walk the AST to find function declarations/expressions on the line(s)
|
|
2055
|
+
// after each directive comment
|
|
2056
|
+
const addIgnoredRange = (loc) => {
|
|
2057
|
+
for (const dirLine of directiveLines) {
|
|
2058
|
+
if (loc.start.line > dirLine && loc.start.line <= dirLine + 3) {
|
|
2059
|
+
for (let line = loc.start.line - 1; line < loc.end.line; line++) {
|
|
2060
|
+
ignoredLines.add(line); // 0-based
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
};
|
|
2065
|
+
walk.simple(ast, {
|
|
2066
|
+
FunctionDeclaration(node) { if (node.loc)
|
|
2067
|
+
addIgnoredRange(node.loc); },
|
|
2068
|
+
FunctionExpression(node) { if (node.loc)
|
|
2069
|
+
addIgnoredRange(node.loc); },
|
|
2070
|
+
ArrowFunctionExpression(node) { if (node.loc)
|
|
2071
|
+
addIgnoredRange(node.loc); },
|
|
2072
|
+
VariableDeclaration(node) { if (node.loc)
|
|
2073
|
+
addIgnoredRange(node.loc); },
|
|
2074
|
+
});
|
|
2075
|
+
return ignoredLines;
|
|
2076
|
+
}
|
|
2077
|
+
/**
|
|
2078
|
+
* Find a variable declaration that ends on the SAME LINE right before a
|
|
2079
|
+
* trailing annotation comment and that binds exactly `annotationName`
|
|
2080
|
+
* (identifier or destructuring pattern). Used so that
|
|
2081
|
+
* `const [filter, setFilter] = useState('x'); // filter :: String`
|
|
2082
|
+
* attaches backward to its own statement instead of leaking forward.
|
|
2083
|
+
* Returns null when the comment is not trailing (only whitespace before it
|
|
2084
|
+
* on its line) or no same-line declaration binds the name.
|
|
2085
|
+
*/
|
|
2086
|
+
function findSameLineDeclaration(ast, commentStart, source, annotationName) {
|
|
2087
|
+
const lineStart = source.lastIndexOf('\n', commentStart - 1) + 1;
|
|
2088
|
+
if (/^\s*$/.test(source.slice(lineStart, commentStart)))
|
|
2089
|
+
return null;
|
|
2090
|
+
let found = null;
|
|
2091
|
+
walk.simple(ast, {
|
|
2092
|
+
VariableDeclaration(node) {
|
|
2093
|
+
if (found)
|
|
2094
|
+
return;
|
|
2095
|
+
if (node.end > commentStart)
|
|
2096
|
+
return;
|
|
2097
|
+
if (source.slice(node.end, commentStart).includes('\n'))
|
|
2098
|
+
return;
|
|
2099
|
+
for (const decl of node.declarations) {
|
|
2100
|
+
if (decl.id?.type === 'Identifier' && decl.id.name === annotationName) {
|
|
2101
|
+
found = { name: annotationName, nodeStart: node.start, nameStart: decl.id.start, nameEnd: decl.id.end };
|
|
2102
|
+
return;
|
|
2103
|
+
}
|
|
2104
|
+
const b = collectPatternBindings(decl.id)
|
|
2105
|
+
.find(p => p.name === annotationName);
|
|
2106
|
+
if (b) {
|
|
2107
|
+
found = { name: annotationName, nodeStart: node.start, nameStart: b.start, nameEnd: b.end };
|
|
2108
|
+
return;
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
},
|
|
2112
|
+
});
|
|
2113
|
+
return found;
|
|
2114
|
+
}
|
|
2115
|
+
/**
|
|
2116
|
+
* Find the nearest declaration node that starts after `afterOffset`.
|
|
2117
|
+
* Searches the top-level body of the program and inside class bodies.
|
|
2118
|
+
*/
|
|
2119
|
+
function findNextDeclaration(ast, afterOffset, source, annotationName) {
|
|
2120
|
+
for (const node of ast.body) {
|
|
2121
|
+
// Comment might be inside this node — check class bodies
|
|
2122
|
+
if (node.start < afterOffset) {
|
|
2123
|
+
if ((node.type === 'ClassDeclaration' || (node.type === 'ExportNamedDeclaration' && node.declaration?.type === 'ClassDeclaration') || (node.type === 'ExportDefaultDeclaration' && node.declaration?.type === 'ClassDeclaration'))
|
|
2124
|
+
&& node.end > afterOffset) {
|
|
2125
|
+
const classNode = (node.type === 'ClassDeclaration' ? node : node.declaration);
|
|
2126
|
+
const className = classNode?.id?.name;
|
|
2127
|
+
if (className && classNode?.body?.body) {
|
|
2128
|
+
// If the comment is inside a member's body (e.g. a property
|
|
2129
|
+
// annotation inside the constructor), search for inline
|
|
2130
|
+
// declarations (this.prop = ...) inside that member first.
|
|
2131
|
+
for (const member of classNode.body.body) {
|
|
2132
|
+
if (member.start <= afterOffset && member.end > afterOffset) {
|
|
2133
|
+
const inline = findNextFunctionExpressionNode(member, afterOffset, source);
|
|
2134
|
+
if (inline) {
|
|
2135
|
+
return inline;
|
|
2136
|
+
}
|
|
2137
|
+
break;
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
for (const member of classNode.body.body) {
|
|
2141
|
+
if (member.start < afterOffset)
|
|
2142
|
+
continue;
|
|
2143
|
+
const gap = member.start - afterOffset;
|
|
2144
|
+
if (gap > 200)
|
|
2145
|
+
break;
|
|
2146
|
+
if (member.type === 'MethodDefinition' && member.key?.type === 'Identifier') {
|
|
2147
|
+
const methodName = member.key.name;
|
|
2148
|
+
if (methodName !== 'constructor') {
|
|
2149
|
+
return {
|
|
2150
|
+
name: `${className}#${methodName}`,
|
|
2151
|
+
nodeStart: member.value?.start ?? /* istanbul ignore next */ member.start,
|
|
2152
|
+
nameStart: member.key.start,
|
|
2153
|
+
nameEnd: member.key.end,
|
|
2154
|
+
};
|
|
2155
|
+
}
|
|
2156
|
+
}
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
}
|
|
2160
|
+
// Inline annotation inside an expression/call argument list.
|
|
2161
|
+
// Example:
|
|
2162
|
+
// ex(
|
|
2163
|
+
// // :: Number -> String
|
|
2164
|
+
// x => x + "!"
|
|
2165
|
+
// )
|
|
2166
|
+
const inline = findNextFunctionExpressionNode(node, afterOffset, source);
|
|
2167
|
+
if (inline) {
|
|
2168
|
+
return inline;
|
|
2169
|
+
}
|
|
2170
|
+
continue;
|
|
2171
|
+
}
|
|
2172
|
+
// Skip nodes that are too far away (allow some whitespace but not other statements)
|
|
2173
|
+
const gap = node.start - afterOffset;
|
|
2174
|
+
if (gap > 200)
|
|
2175
|
+
break; // heuristic: annotation should be close to declaration
|
|
2176
|
+
const result = extractDeclName(node, annotationName);
|
|
2177
|
+
if (result) {
|
|
2178
|
+
return { name: result.name, nodeStart: result.nodeStart ?? node.start, nameStart: result.nameStart, nameEnd: result.nameEnd };
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
2181
|
+
return null;
|
|
2182
|
+
}
|
|
2183
|
+
/**
|
|
2184
|
+
* Find the nearest function expression/arrow function that starts after
|
|
2185
|
+
* `afterOffset` inside a given subtree.
|
|
2186
|
+
*/
|
|
2187
|
+
function findNextFunctionExpressionNode(root, afterOffset, source) {
|
|
2188
|
+
let bestStart = null;
|
|
2189
|
+
let bestName;
|
|
2190
|
+
// When the best match is a variable declaration (`const map = fn => ...`),
|
|
2191
|
+
// store the declaration start separately for the gap check — the nodeStart
|
|
2192
|
+
// should still point to the function expression init.
|
|
2193
|
+
let bestDeclStart = null;
|
|
2194
|
+
let bestNameStart;
|
|
2195
|
+
let bestNameEnd;
|
|
2196
|
+
const checkNode = (node) => {
|
|
2197
|
+
if (node.start >= afterOffset && (bestStart === null || node.start < bestStart)) {
|
|
2198
|
+
bestStart = node.start;
|
|
2199
|
+
bestName = undefined;
|
|
2200
|
+
bestDeclStart = null;
|
|
2201
|
+
}
|
|
2202
|
+
};
|
|
2203
|
+
// Also look for variable declarations inside function bodies. This allows
|
|
2204
|
+
// annotations like
|
|
2205
|
+
// // Either2#map :: Either2 e a ~> (a -> b) -> Either2 e b
|
|
2206
|
+
// const map = fn => ...
|
|
2207
|
+
// to be properly attached with the binding name. The init may be ANY
|
|
2208
|
+
// expression — not just a function — so nested value bindings like
|
|
2209
|
+
// // test :: Applicative m => m z
|
|
2210
|
+
// const test = reduce (reducer) (seed) (xs);
|
|
2211
|
+
// attach here too (mirroring top-level `extractDeclName` semantics)
|
|
2212
|
+
// instead of leaking through to the next top-level statement.
|
|
2213
|
+
const checkVarDecl = (node) => {
|
|
2214
|
+
if (node.start < afterOffset)
|
|
2215
|
+
return;
|
|
2216
|
+
for (const decl of node.declarations) {
|
|
2217
|
+
if (decl.init && decl.id?.type === 'Identifier') {
|
|
2218
|
+
if (bestStart === null || decl.init.start <= bestStart) {
|
|
2219
|
+
bestStart = decl.init.start;
|
|
2220
|
+
bestName = decl.id.name;
|
|
2221
|
+
bestDeclStart = node.start;
|
|
2222
|
+
bestNameStart = decl.id.start;
|
|
2223
|
+
bestNameEnd = decl.id.end;
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
};
|
|
2228
|
+
// Also look for nested function declarations:
|
|
2229
|
+
// // Either2#map :: Either2 e a ~> (a -> b) -> Either2 e b
|
|
2230
|
+
// function map(fn) { ... }
|
|
2231
|
+
const checkFuncDecl = (node) => {
|
|
2232
|
+
if (node.start < afterOffset)
|
|
2233
|
+
return;
|
|
2234
|
+
if (!node.id?.name)
|
|
2235
|
+
return;
|
|
2236
|
+
if (bestStart === null || node.start <= bestStart) {
|
|
2237
|
+
bestStart = node.start;
|
|
2238
|
+
bestName = node.id.name;
|
|
2239
|
+
bestDeclStart = null;
|
|
2240
|
+
bestNameStart = node.id.start;
|
|
2241
|
+
bestNameEnd = node.id.end;
|
|
2242
|
+
}
|
|
2243
|
+
};
|
|
2244
|
+
// Also look for `this.<prop> = <expr>` assignments inside constructor bodies.
|
|
2245
|
+
// This allows annotations like:
|
|
2246
|
+
// // RTask#fork :: RTask r e a ~> (e -> (), a -> (), r) -> ()
|
|
2247
|
+
// this.fork = fork;
|
|
2248
|
+
// to be properly attached with the property name.
|
|
2249
|
+
const checkThisAssignment = (node) => {
|
|
2250
|
+
if (node.start < afterOffset)
|
|
2251
|
+
return;
|
|
2252
|
+
const expr = node.expression;
|
|
2253
|
+
if (expr?.type !== 'AssignmentExpression')
|
|
2254
|
+
return;
|
|
2255
|
+
const left = expr.left;
|
|
2256
|
+
if (left?.type !== 'MemberExpression' || left.computed)
|
|
2257
|
+
return;
|
|
2258
|
+
if (left.object?.type !== 'ThisExpression')
|
|
2259
|
+
return;
|
|
2260
|
+
if (left.property?.type !== 'Identifier')
|
|
2261
|
+
return;
|
|
2262
|
+
const propName = left.property.name;
|
|
2263
|
+
if (bestStart === null || node.start <= bestStart) {
|
|
2264
|
+
bestStart = node.start;
|
|
2265
|
+
bestName = propName;
|
|
2266
|
+
bestDeclStart = null;
|
|
2267
|
+
bestNameStart = left.property.start;
|
|
2268
|
+
bestNameEnd = left.property.end;
|
|
2269
|
+
}
|
|
2270
|
+
};
|
|
2271
|
+
// Look for object literal property/method shorthand:
|
|
2272
|
+
// // Box#map :: Box a ~> (a -> b) -> Box b
|
|
2273
|
+
// map(fn) { return Box(fn(this.value)); },
|
|
2274
|
+
// or shorthand property:
|
|
2275
|
+
// // Box#value :: Box a ~> a
|
|
2276
|
+
// value,
|
|
2277
|
+
const checkProperty = (node) => {
|
|
2278
|
+
if (node.type !== 'Property')
|
|
2279
|
+
return;
|
|
2280
|
+
if (node.start < afterOffset)
|
|
2281
|
+
return;
|
|
2282
|
+
if (node.key?.type !== 'Identifier')
|
|
2283
|
+
return;
|
|
2284
|
+
const propName = node.key.name;
|
|
2285
|
+
const valueStart = node.method ? node.value.start : node.start;
|
|
2286
|
+
if (bestStart === null || valueStart <= bestStart) {
|
|
2287
|
+
bestStart = valueStart;
|
|
2288
|
+
bestName = propName;
|
|
2289
|
+
bestDeclStart = node.start;
|
|
2290
|
+
bestNameStart = node.key.start;
|
|
2291
|
+
bestNameEnd = node.key.end;
|
|
2292
|
+
}
|
|
2293
|
+
};
|
|
2294
|
+
walk.simple(root, {
|
|
2295
|
+
ArrowFunctionExpression: checkNode,
|
|
2296
|
+
FunctionExpression: checkNode,
|
|
2297
|
+
VariableDeclaration: checkVarDecl,
|
|
2298
|
+
FunctionDeclaration: checkFuncDecl,
|
|
2299
|
+
ExpressionStatement: checkThisAssignment,
|
|
2300
|
+
Property: checkProperty,
|
|
2301
|
+
});
|
|
2302
|
+
if (bestStart === null)
|
|
2303
|
+
return null;
|
|
2304
|
+
// For variable declarations, check gap to the `const`/`let`/`var` keyword,
|
|
2305
|
+
// not to the function expression init (which would include `const name = `).
|
|
2306
|
+
const gapTarget = bestDeclStart ?? bestStart;
|
|
2307
|
+
const gap = source.slice(afterOffset, gapTarget);
|
|
2308
|
+
if (!/^\s*$/.test(gap)) {
|
|
2309
|
+
return null;
|
|
2310
|
+
}
|
|
2311
|
+
// Keep the same proximity heuristic used for declarations.
|
|
2312
|
+
if ((gapTarget - afterOffset) > 200) {
|
|
2313
|
+
return null;
|
|
2314
|
+
}
|
|
2315
|
+
return { nodeStart: bestStart, name: bestName, nameStart: bestNameStart, nameEnd: bestNameEnd };
|
|
2316
|
+
}
|
|
2317
|
+
/**
|
|
2318
|
+
* Walk an `ObjectPattern` / `ArrayPattern` (and the rest patterns nested
|
|
2319
|
+
* inside them) and return every locally-bound identifier with its source
|
|
2320
|
+
* range. Used by `extractDeclName` so an annotation above
|
|
2321
|
+
* `const { x } = ...` attaches to `x` instead of being pushed forward to
|
|
2322
|
+
* the next declaration in the file.
|
|
2323
|
+
*/
|
|
2324
|
+
function collectPatternBindings(pat) {
|
|
2325
|
+
const out = [];
|
|
2326
|
+
const walk = (p) => {
|
|
2327
|
+
if (!p)
|
|
2328
|
+
return;
|
|
2329
|
+
switch (p.type) {
|
|
2330
|
+
case 'Identifier':
|
|
2331
|
+
out.push({ name: p.name, start: p.start, end: p.end });
|
|
2332
|
+
return;
|
|
2333
|
+
case 'ObjectPattern':
|
|
2334
|
+
for (const prop of p.properties) {
|
|
2335
|
+
if (prop.type === 'Property') {
|
|
2336
|
+
walk(prop.value);
|
|
2337
|
+
}
|
|
2338
|
+
else if (prop.type === 'RestElement') {
|
|
2339
|
+
walk(prop.argument);
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
return;
|
|
2343
|
+
case 'ArrayPattern':
|
|
2344
|
+
for (const el of p.elements)
|
|
2345
|
+
walk(el);
|
|
2346
|
+
return;
|
|
2347
|
+
case 'AssignmentPattern':
|
|
2348
|
+
walk(p.left);
|
|
2349
|
+
return;
|
|
2350
|
+
case 'RestElement':
|
|
2351
|
+
walk(p.argument);
|
|
2352
|
+
return;
|
|
2353
|
+
default:
|
|
2354
|
+
return;
|
|
2355
|
+
}
|
|
2356
|
+
};
|
|
2357
|
+
walk(pat);
|
|
2358
|
+
return out;
|
|
2359
|
+
}
|
|
2360
|
+
/**
|
|
2361
|
+
* Extract the declared name from a statement node.
|
|
2362
|
+
* Returns the name and optionally a custom nodeStart offset.
|
|
2363
|
+
*/
|
|
2364
|
+
function extractDeclName(node, annotationName) {
|
|
2365
|
+
switch (node.type) {
|
|
2366
|
+
case 'FunctionDeclaration':
|
|
2367
|
+
/* istanbul ignore next — anonymous FunctionDeclaration is a syntax error */
|
|
2368
|
+
return node.id?.name ? { name: node.id.name, nameStart: node.id.start, nameEnd: node.id.end } : null;
|
|
2369
|
+
case 'VariableDeclaration': {
|
|
2370
|
+
// Take the first declarator's name
|
|
2371
|
+
if (node.declarations.length === 0)
|
|
2372
|
+
return null;
|
|
2373
|
+
const id0 = node.declarations[0].id;
|
|
2374
|
+
if (id0?.type === 'Identifier' && id0.name) {
|
|
2375
|
+
const id = id0;
|
|
2376
|
+
return { name: id.name, nameStart: id.start, nameEnd: id.end };
|
|
2377
|
+
}
|
|
2378
|
+
// Destructuring patterns: `const { x } = ...` / `const [x] = ...`.
|
|
2379
|
+
// Walk the bindings and prefer the one matching the annotation name
|
|
2380
|
+
// so a destructuring assignment doesn't push the annotation through
|
|
2381
|
+
// to a later, unrelated declaration.
|
|
2382
|
+
const bindings = collectPatternBindings(id0);
|
|
2383
|
+
if (bindings.length === 0)
|
|
2384
|
+
return null;
|
|
2385
|
+
const matched = annotationName
|
|
2386
|
+
? bindings.find(b => b.name === annotationName)
|
|
2387
|
+
: undefined;
|
|
2388
|
+
const chosen = matched ?? bindings[0];
|
|
2389
|
+
return { name: chosen.name, nameStart: chosen.start, nameEnd: chosen.end };
|
|
2390
|
+
}
|
|
2391
|
+
case 'ExportNamedDeclaration':
|
|
2392
|
+
if (node.declaration) {
|
|
2393
|
+
const inner = extractDeclName(node.declaration, annotationName);
|
|
2394
|
+
// Use the inner declaration's start so the nodeStart aligns with
|
|
2395
|
+
// the range check in inferNamedBinding (which uses the
|
|
2396
|
+
// VariableDeclaration's start, not the outer export's start).
|
|
2397
|
+
if (inner && inner.nodeStart === undefined) {
|
|
2398
|
+
inner.nodeStart = node.declaration.start;
|
|
2399
|
+
}
|
|
2400
|
+
return inner;
|
|
2401
|
+
}
|
|
2402
|
+
return null;
|
|
2403
|
+
case 'ExportDefaultDeclaration':
|
|
2404
|
+
if (node.declaration) {
|
|
2405
|
+
const inner = extractDeclName(node.declaration, annotationName);
|
|
2406
|
+
if (inner && inner.nodeStart === undefined) {
|
|
2407
|
+
inner.nodeStart = node.declaration.start;
|
|
2408
|
+
}
|
|
2409
|
+
return inner;
|
|
2410
|
+
}
|
|
2411
|
+
return null;
|
|
2412
|
+
case 'ClassDeclaration':
|
|
2413
|
+
/* istanbul ignore next — anonymous ClassDeclaration is a syntax error */
|
|
2414
|
+
return node.id?.name ? { name: node.id.name, nameStart: node.id.start, nameEnd: node.id.end } : null;
|
|
2415
|
+
case 'ExpressionStatement': {
|
|
2416
|
+
// Handle: Box.fromPair = pair => ...
|
|
2417
|
+
const expr = node.expression;
|
|
2418
|
+
if (expr?.type === 'AssignmentExpression' && expr.left?.type === 'MemberExpression') {
|
|
2419
|
+
const obj = expr.left.object;
|
|
2420
|
+
const prop = expr.left.property;
|
|
2421
|
+
if (obj?.type === 'Identifier' && prop?.type === 'Identifier') {
|
|
2422
|
+
return { name: `${obj.name}.${prop.name}`, nameStart: prop.start, nameEnd: prop.end };
|
|
2423
|
+
}
|
|
2424
|
+
// Handle: Right.prototype.map = function() {...} → Right#map
|
|
2425
|
+
// nodeStart points to the RHS expression so hover on Right/prototype
|
|
2426
|
+
// does not pick up the method annotation.
|
|
2427
|
+
const proto = extractPrototypeMethod(expr.left);
|
|
2428
|
+
if (proto) {
|
|
2429
|
+
const methodKey = expr.left.property;
|
|
2430
|
+
return {
|
|
2431
|
+
name: `${proto.typeName}#${proto.methodName}`,
|
|
2432
|
+
nodeStart: expr.right?.start,
|
|
2433
|
+
nameStart: methodKey?.type === 'Identifier' ? methodKey.start : undefined,
|
|
2434
|
+
nameEnd: methodKey?.type === 'Identifier' ? methodKey.end : undefined,
|
|
2435
|
+
};
|
|
2436
|
+
}
|
|
2437
|
+
}
|
|
2438
|
+
return null;
|
|
2439
|
+
}
|
|
2440
|
+
default:
|
|
2441
|
+
return null;
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
// ---------------------------------------------------------------------------
|
|
2445
|
+
// Import name extraction
|
|
2446
|
+
// ---------------------------------------------------------------------------
|
|
2447
|
+
/**
|
|
2448
|
+
* Extract uppercase-initial names from ES module import / require declarations
|
|
2449
|
+
* in JS source. Used to recognise locally-imported type constructors so the
|
|
2450
|
+
* type validator doesn't flag them as unknown.
|
|
2451
|
+
*/
|
|
2452
|
+
function extractImportedNames(source) {
|
|
2453
|
+
const names = [];
|
|
2454
|
+
const importRegex = /import\s+(\w+)\s+from\s+['"]|import\s+\{([^}]+)\}\s+from\s+['"]|const\s+\{([^}]+)\}\s*=\s*require\s*\(/g;
|
|
2455
|
+
let match;
|
|
2456
|
+
while ((match = importRegex.exec(source)) !== null) {
|
|
2457
|
+
if (match[1] && /^[A-Z]/.test(match[1])) {
|
|
2458
|
+
names.push(match[1]);
|
|
2459
|
+
}
|
|
2460
|
+
const namedImports = match[2] || match[3];
|
|
2461
|
+
if (namedImports) {
|
|
2462
|
+
for (const part of namedImports.split(',')) {
|
|
2463
|
+
const name = part.trim().split(/\s+as\s+/).pop()?.trim();
|
|
2464
|
+
if (name && /^[A-Z]/.test(name)) {
|
|
2465
|
+
names.push(name);
|
|
2466
|
+
}
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
}
|
|
2470
|
+
return names;
|
|
2471
|
+
}
|
|
2472
|
+
/**
|
|
2473
|
+
* Extract unique module specifier paths from import/require declarations.
|
|
2474
|
+
* Returns paths like `'./Either2'`, `'./demo'`, etc.
|
|
2475
|
+
*/
|
|
2476
|
+
function extractImportModuleSpecifiers(source) {
|
|
2477
|
+
const specifiers = new Set();
|
|
2478
|
+
const importRegex = /import\s+(?:\w+|\{[^}]+\}|\*\s+as\s+\w+)\s+from\s+['"]([^'"]+)['"]|(?:const|let|var)\s+(?:\w+|\{[^}]+\})\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
|
|
2479
|
+
let match;
|
|
2480
|
+
while ((match = importRegex.exec(source)) !== null) {
|
|
2481
|
+
const specifier = match[1] || match[2];
|
|
2482
|
+
if (specifier)
|
|
2483
|
+
specifiers.add(specifier);
|
|
2484
|
+
}
|
|
2485
|
+
return [...specifiers];
|
|
2486
|
+
}
|
|
2487
|
+
//# sourceMappingURL=commentParser.js.map
|