@prisma/orm-toolchain 8.0.0-rc.2-dev.3 → 8.0.0-rc.20
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/README.md +1 -5
- package/dist/{aggregate-DLUJLq5Y.d.mts → aggregate-BpcQdygS.d.mts} +83 -36
- package/dist/aggregate-BpcQdygS.d.mts.map +1 -0
- package/dist/{aggregate-CPZB020V.mjs → aggregate-T_HG6gq6.mjs} +118 -57
- package/dist/aggregate-T_HG6gq6.mjs.map +1 -0
- package/dist/caught-errors-Bmbi1dBu-DKO5X2tN.mjs +1026 -0
- package/dist/caught-errors-Bmbi1dBu-DKO5X2tN.mjs.map +1 -0
- package/dist/cli-telemetry.d.mts +9 -8
- package/dist/cli-telemetry.d.mts.map +1 -1
- package/dist/cli-telemetry.mjs +30 -27
- package/dist/cli-telemetry.mjs.map +1 -1
- package/dist/cli.d.mts +7 -14
- package/dist/cli.d.mts.map +1 -1
- package/dist/cli.mjs +3769 -1506
- package/dist/cli.mjs.map +1 -1
- package/dist/cli__control-api.d.mts +233 -93
- package/dist/cli__control-api.d.mts.map +1 -1
- package/dist/cli__control-api.mjs +3 -2
- package/dist/cli__control-api__testing.d.mts +5 -4
- package/dist/cli__control-api__testing.d.mts.map +1 -1
- package/dist/cli__control-api__testing.mjs +21 -16
- package/dist/cli__control-api__testing.mjs.map +1 -1
- package/dist/cli__init-output.d.mts +11 -1
- package/dist/cli__init-output.d.mts.map +1 -1
- package/dist/cli__init-output.mjs +1 -1
- package/dist/cli__migration-cli.d.mts +1 -1
- package/dist/cli__migration-cli.mjs +65 -19
- package/dist/cli__migration-cli.mjs.map +1 -1
- package/dist/config-loader.d.mts +2 -2
- package/dist/config-loader.mjs +2 -2
- package/dist/{contract-snapshot-store-B0G1Fw_F-CHc4QfKb.mjs → contract-snapshot-store-6gIBcUeb-DJK3OM0j.mjs} +44 -16
- package/dist/contract-snapshot-store-6gIBcUeb-DJK3OM0j.mjs.map +1 -0
- package/dist/contract-snapshot-store-Bok5nQYi-D3g_P7im.d.mts +59 -0
- package/dist/contract-snapshot-store-Bok5nQYi-D3g_P7im.d.mts.map +1 -0
- package/dist/contract-snapshot-store-DrIwu5pn.d.mts +2 -0
- package/dist/{db-verify-BwgNK50T-DGvKgFCK.d.mts → db-sign-gvrl0kFE-D-nTGx88.d.mts} +330 -230
- package/dist/db-sign-gvrl0kFE-D-nTGx88.d.mts.map +1 -0
- package/dist/{domain-type-generation-bpSO3Y0L-jo2C7LlH.mjs → domain-type-generation-B4m774CV-WAjyhZHw.mjs} +144 -154
- package/dist/domain-type-generation-B4m774CV-WAjyhZHw.mjs.map +1 -0
- package/dist/domain-type-generation-DZjtzrbE-BpOOD3YV.d.mts +78 -0
- package/dist/domain-type-generation-DZjtzrbE-BpOOD3YV.d.mts.map +1 -0
- package/dist/emitter.d.mts +3 -3
- package/dist/emitter.mjs +3 -3
- package/dist/emitter__domain-type-generation.d.mts +2 -2
- package/dist/emitter__domain-type-generation.mjs +2 -2
- package/dist/{errors-D59OCpoI.d.mts → errors-CLwhWJiz.d.mts} +14 -3
- package/dist/errors-CLwhWJiz.d.mts.map +1 -0
- package/dist/{errors-CXbGUWGu-CstQHPh6.mjs → errors-DXha_4l--relAaiI4.mjs} +37 -42
- package/dist/errors-DXha_4l--relAaiI4.mjs.map +1 -0
- package/dist/exports-BCIlMjIW-DkUBVDzl.mjs +421 -0
- package/dist/exports-BCIlMjIW-DkUBVDzl.mjs.map +1 -0
- package/dist/exports-BlYTE3-J.mjs +539 -0
- package/dist/exports-BlYTE3-J.mjs.map +1 -0
- package/dist/exports-CKgwcXbp.mjs +3973 -0
- package/dist/exports-CKgwcXbp.mjs.map +1 -0
- package/dist/graph-membership-DxpNgxfZ-BfqA-H7V.mjs +19 -0
- package/dist/graph-membership-DxpNgxfZ-BfqA-H7V.mjs.map +1 -0
- package/dist/{hash-DH8hl5Rq-BpM2t3Nu.mjs → hash-BAZVWU4a-BQovI7hF.mjs} +24 -3
- package/dist/hash-BAZVWU4a-BQovI7hF.mjs.map +1 -0
- package/dist/hash-CwWGlFWV.d.mts +1 -0
- package/dist/{hash-XZYYKJ-i.d.mts → hash-DclMqd7S-WBvXJ_4C.d.mts} +17 -4
- package/dist/hash-DclMqd7S-WBvXJ_4C.d.mts.map +1 -0
- package/dist/{import-roots-CfoYgejL.d.mts → import-roots-ARK1wjzc.d.mts} +3 -3
- package/dist/{import-roots-CfoYgejL.d.mts.map → import-roots-ARK1wjzc.d.mts.map} +1 -1
- package/dist/{import-roots-CNFBPAT1.mjs → import-roots-BPn2s_fq.mjs} +6 -6
- package/dist/import-roots-BPn2s_fq.mjs.map +1 -0
- package/dist/index-CWPFeYyi.d.mts +204 -0
- package/dist/index-CWPFeYyi.d.mts.map +1 -0
- package/dist/{index-Dgwl8Tzs.d.mts → index-tAySVPvZ.d.mts} +16 -4
- package/dist/index-tAySVPvZ.d.mts.map +1 -0
- package/dist/{invariants-CTHy88OP-CYI2a8IO.mjs → invariants-DrF9p5Gd-BF70vGl1.mjs} +3 -3
- package/dist/{invariants-CTHy88OP-CYI2a8IO.mjs.map → invariants-DrF9p5Gd-BF70vGl1.mjs.map} +1 -1
- package/dist/{io-635GlNx1-D3zrw2qu.mjs → io-BNxFm3eg-DYD82QeZ.mjs} +8 -8
- package/dist/io-BNxFm3eg-DYD82QeZ.mjs.map +1 -0
- package/dist/io-D8Epu7iY.d.mts +1 -0
- package/dist/{io-sr4CO9_t-C3eV_kn-.d.mts → io-DZfMV51z-BKlH5Dhb.d.mts} +9 -2
- package/dist/io-DZfMV51z-BKlH5Dhb.d.mts.map +1 -0
- package/dist/{migration-B2ljMJim.d.mts → migration-Bjz05034.d.mts} +12 -5
- package/dist/migration-Bjz05034.d.mts.map +1 -0
- package/dist/{migration-hspPIEeV.mjs → migration-CWyjX9vz.mjs} +18 -6
- package/dist/migration-CWyjX9vz.mjs.map +1 -0
- package/dist/{migration-graph-_SJImD5V-BURyY1KM.mjs → migration-graph-BoiiZAaU-DLht12k7.mjs} +6 -89
- package/dist/migration-graph-BoiiZAaU-DLht12k7.mjs.map +1 -0
- package/dist/{migration-graph-tarTxJ99-BrGBANeE.d.mts → migration-graph-D8IuOkZb-pSI7-k4_.d.mts} +7 -29
- package/dist/migration-graph-D8IuOkZb-pSI7-k4_.d.mts.map +1 -0
- package/dist/migration-graph-Dra4CcyN.d.mts +14 -0
- package/dist/migration-graph-Dra4CcyN.d.mts.map +1 -0
- package/dist/migration-tools.d.mts +17 -15
- package/dist/migration-tools.mjs +15 -15
- package/dist/migration-tools__aggregate.d.mts +2 -2
- package/dist/migration-tools__aggregate.mjs +2 -2
- package/dist/migration-tools__contract-snapshot-store.d.mts +4 -2
- package/dist/migration-tools__contract-snapshot-store.mjs +2 -2
- package/dist/migration-tools__errors.d.mts +2 -2
- package/dist/migration-tools__errors.mjs +1 -1
- package/dist/migration-tools__hash.d.mts +2 -1
- package/dist/migration-tools__hash.mjs +1 -1
- package/dist/migration-tools__invariants.mjs +1 -1
- package/dist/migration-tools__io.d.mts +2 -2
- package/dist/migration-tools__io.mjs +1 -1
- package/dist/migration-tools__migration-graph.d.mts +3 -3
- package/dist/migration-tools__migration-graph.mjs +3 -3
- package/dist/migration-tools__migration-ts.d.mts +2 -2
- package/dist/migration-tools__migration-ts.mjs +2 -2
- package/dist/migration-tools__migration.d.mts +1 -1
- package/dist/migration-tools__migration.mjs +1 -1
- package/dist/migration-tools__ref-resolution.d.mts +2 -2
- package/dist/migration-tools__ref-resolution.mjs +2 -2
- package/dist/migration-tools__refs.mjs +1 -1
- package/dist/migration-tools__spaces.d.mts +1 -1
- package/dist/migration-tools__spaces.mjs +2 -2
- package/dist/{migration-ts-DdVm0rws.mjs → migration-ts-DDgjsR1O.mjs} +6 -5
- package/dist/migration-ts-DDgjsR1O.mjs.map +1 -0
- package/dist/{migration-ts-CNaAtK8C.d.mts → migration-ts-SGer0PXq.d.mts} +4 -2
- package/dist/migration-ts-SGer0PXq.d.mts.map +1 -0
- package/dist/op-schema-3tXg0LTS-DqpOKDEa.mjs +23 -0
- package/dist/op-schema-3tXg0LTS-DqpOKDEa.mjs.map +1 -0
- package/dist/output-BcC8eB0h-C5bRd-aC.mjs +129 -0
- package/dist/output-BcC8eB0h-C5bRd-aC.mjs.map +1 -0
- package/dist/publish-surface.d.mts +1 -1
- package/dist/publish-surface.mjs +2 -2
- package/dist/publish-surface__import-roots.d.mts +1 -1
- package/dist/publish-surface__import-roots.mjs +1 -1
- package/dist/publish-surface__shells.mjs +1 -1
- package/dist/quick-reference-mongo.md +12 -12
- package/dist/quick-reference-postgres.md +10 -10
- package/dist/quick-reference-prisma7.md +80 -0
- package/dist/readme-mongo.md +6 -6
- package/dist/readme-postgres.md +6 -6
- package/dist/ref-DEiY2Cbd-1ZImpUEN.mjs +6663 -0
- package/dist/ref-DEiY2Cbd-1ZImpUEN.mjs.map +1 -0
- package/dist/{ref-resolution-COGOSL57.d.mts → ref-resolution-BPhR-kta.d.mts} +29 -11
- package/dist/ref-resolution-BPhR-kta.d.mts.map +1 -0
- package/dist/{ref-resolution-HeNBXW53.mjs → ref-resolution-Eo0QHp4f.mjs} +30 -6
- package/dist/ref-resolution-Eo0QHp4f.mjs.map +1 -0
- package/dist/{refs-WK86uYYp-gM8tvWQP.mjs → refs-DM3q3IZC-BC6H6P0X.mjs} +9 -9
- package/dist/refs-DM3q3IZC-BC6H6P0X.mjs.map +1 -0
- package/dist/{shells-C4HbRAr5.mjs → shells-w_yEDhe8.mjs} +98 -31
- package/dist/shells-w_yEDhe8.mjs.map +1 -0
- package/dist/{spaces-Dj65JrwZ.d.mts → spaces-BWULKO54.d.mts} +3 -3
- package/dist/{spaces-Dj65JrwZ.d.mts.map → spaces-BWULKO54.d.mts.map} +1 -1
- package/dist/{spaces-4qMOAYE9.mjs → spaces-c9xdiXW8.mjs} +14 -13
- package/dist/spaces-c9xdiXW8.mjs.map +1 -0
- package/dist/{verify-contract-spaces-DhJTb0zM-B62maCfE.mjs → verify-contract-spaces-YzEHF9zj-DGZgox_3.mjs} +7 -7
- package/dist/{verify-contract-spaces-DhJTb0zM-B62maCfE.mjs.map → verify-contract-spaces-YzEHF9zj-DGZgox_3.mjs.map} +1 -1
- package/dist/vite-plugin-contract-emit.d.mts +1 -1
- package/dist/vite-plugin-contract-emit.mjs +10 -10
- package/dist/vite-plugin-contract-emit.mjs.map +1 -1
- package/package.json +16 -15
- package/dist/aggregate-CPZB020V.mjs.map +0 -1
- package/dist/aggregate-DLUJLq5Y.d.mts.map +0 -1
- package/dist/contract-snapshot-store-B0G1Fw_F-CHc4QfKb.mjs.map +0 -1
- package/dist/contract-snapshot-store-CbqynbtE.d.mts +0 -28
- package/dist/contract-snapshot-store-CbqynbtE.d.mts.map +0 -1
- package/dist/db-verify-BwgNK50T-DGvKgFCK.d.mts.map +0 -1
- package/dist/domain-type-generation-PkAb39ob-Ct8AGqow.d.mts +0 -63
- package/dist/domain-type-generation-PkAb39ob-Ct8AGqow.d.mts.map +0 -1
- package/dist/domain-type-generation-bpSO3Y0L-jo2C7LlH.mjs.map +0 -1
- package/dist/errors-CXbGUWGu-CstQHPh6.mjs.map +0 -1
- package/dist/errors-D59OCpoI.d.mts.map +0 -1
- package/dist/exports-8ZUN43ve.mjs +0 -1734
- package/dist/exports-8ZUN43ve.mjs.map +0 -1
- package/dist/exports-BCLg4CiV-05kuwcb0.mjs +0 -160
- package/dist/exports-BCLg4CiV-05kuwcb0.mjs.map +0 -1
- package/dist/exports-BZaG8_w_.mjs +0 -243
- package/dist/exports-BZaG8_w_.mjs.map +0 -1
- package/dist/graph-membership-BViWUMpP-C4lYYJdU.mjs +0 -14
- package/dist/graph-membership-BViWUMpP-C4lYYJdU.mjs.map +0 -1
- package/dist/hash-DH8hl5Rq-BpM2t3Nu.mjs.map +0 -1
- package/dist/hash-XZYYKJ-i.d.mts.map +0 -1
- package/dist/import-roots-CNFBPAT1.mjs.map +0 -1
- package/dist/index-DRs7L6N0.d.mts +0 -57
- package/dist/index-DRs7L6N0.d.mts.map +0 -1
- package/dist/index-Dgwl8Tzs.d.mts.map +0 -1
- package/dist/io-635GlNx1-D3zrw2qu.mjs.map +0 -1
- package/dist/io-DYfeLJxR.d.mts +0 -1
- package/dist/io-sr4CO9_t-C3eV_kn-.d.mts.map +0 -1
- package/dist/migration-B2ljMJim.d.mts.map +0 -1
- package/dist/migration-graph-Dqndu0i5.d.mts +0 -9
- package/dist/migration-graph-Dqndu0i5.d.mts.map +0 -1
- package/dist/migration-graph-_SJImD5V-BURyY1KM.mjs.map +0 -1
- package/dist/migration-graph-tarTxJ99-BrGBANeE.d.mts.map +0 -1
- package/dist/migration-hspPIEeV.mjs.map +0 -1
- package/dist/migration-ts-CNaAtK8C.d.mts.map +0 -1
- package/dist/migration-ts-DdVm0rws.mjs.map +0 -1
- package/dist/op-schema-BSVHzEQN-DIWt28D8.mjs +0 -13
- package/dist/op-schema-BSVHzEQN-DIWt28D8.mjs.map +0 -1
- package/dist/output-CovTDY14-CUoAqLML.mjs +0 -77
- package/dist/output-CovTDY14-CUoAqLML.mjs.map +0 -1
- package/dist/ref-h6InR6dO-rGfl18Jv.mjs +0 -4686
- package/dist/ref-h6InR6dO-rGfl18Jv.mjs.map +0 -1
- package/dist/ref-resolution-COGOSL57.d.mts.map +0 -1
- package/dist/ref-resolution-HeNBXW53.mjs.map +0 -1
- package/dist/refs-WK86uYYp-gM8tvWQP.mjs.map +0 -1
- package/dist/shells-C4HbRAr5.mjs.map +0 -1
- package/dist/spaces-4qMOAYE9.mjs.map +0 -1
|
@@ -0,0 +1,3973 @@
|
|
|
1
|
+
import { a as expandContractInputs, g as requireConfigSections, s as findNearestConfigPathForFile, u as loadConfig } from "./exports-BlYTE3-J.mjs";
|
|
2
|
+
import { ifDefined } from "@prisma/orm-framework/utils/defined";
|
|
3
|
+
import { CliStructuredError } from "@prisma/orm-framework/errors/control";
|
|
4
|
+
import { createControlStack } from "@prisma/orm-framework/components/control";
|
|
5
|
+
import { InternalError } from "@prisma/orm-framework/utils/internal-error";
|
|
6
|
+
import { join } from "pathe";
|
|
7
|
+
import { randomUUID } from "node:crypto";
|
|
8
|
+
import { blindCast } from "@prisma/orm-framework/utils/casts";
|
|
9
|
+
import { readFileSync, statSync } from "node:fs";
|
|
10
|
+
import { UNBOUND_NAMESPACE_ID } from "@prisma/orm-framework/components/ir";
|
|
11
|
+
import { EMPTY_GENERATOR_FUNCTIONS } from "@prisma/orm-framework/components/components";
|
|
12
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
13
|
+
import { normalize as normalize$1 } from "node:path";
|
|
14
|
+
import { format, resolveFormatOptions } from "@prisma/orm-framework/psl-parser/format";
|
|
15
|
+
import { EMPTY_DATA_TYPES, assembleAttributeSpecs, blockSpecContext, blockSpecFactoryOf, buildSymbolTable, contributedTypeOf, createBinder, entityReference, findBlockDescriptor, isNamespaceLike, isPrismaNextSchema, isPslIdentifier, matchesSelector, memberEntries, renameLegacyDirective, typeReferenceNode } from "@prisma/orm-framework/psl-parser";
|
|
16
|
+
import { CompletionItemKind, CompletionItemTag, ConnectionError, ConnectionErrors, DiagnosticSeverity, DidChangeWatchedFilesNotification, DocumentDiagnosticReportKind, FoldingRangeKind, InsertTextFormat, LSPErrorCodes, MarkupKind, ProposedFeatures, RegistrationRequest, ResponseError, SemanticTokenModifiers, SemanticTokenTypes, TextDocumentSyncKind, UnregistrationRequest, createConnection } from "vscode-languageserver";
|
|
17
|
+
import { TextDocument } from "vscode-languageserver-textdocument";
|
|
18
|
+
import { ArrayLiteralAst, AttributeArgAst, AttributeArgListAst, BooleanLiteralExprAst, CompositeTypeDeclarationAst, FieldAttributeAst, FieldDeclarationAst, FunctionCallAst, GenericBlockDeclarationAst, IdentifierAst, KeyValuePairAst, MixinDeclarationAst, MixinInclusionAst, ModelAttributeAst, ModelDeclarationAst, NamespaceDeclarationAst, NumberLiteralExprAst, ObjectLiteralExprAst, PathExprAst, PslSources, StringLiteralExprAst, SyntaxNode, SyntaxToken, TaggedLiteralExprAst, TypesBlockAst, any, filterChildren, isTrivia, nonTriviaSibling, parse, skipTriviaToken } from "@prisma/orm-framework/psl-parser/syntax";
|
|
19
|
+
import { hasPslInterpreter } from "@prisma/orm-framework/psl-parser/interpret";
|
|
20
|
+
import { admittedTags, describeAdmittedForms, isAuthoringPslBlockDescriptor } from "@prisma/orm-framework/components/authoring";
|
|
21
|
+
import { dataTypeId } from "@prisma/orm-framework/components/codec";
|
|
22
|
+
import { ProposedFeatures as ProposedFeatures$1, StreamMessageReader, StreamMessageWriter, createConnection as createConnection$1, createProtocolConnection } from "vscode-languageserver/node";
|
|
23
|
+
import { Console } from "node:console";
|
|
24
|
+
import { Readable, Writable } from "node:stream";
|
|
25
|
+
import { StringDecoder } from "node:string_decoder";
|
|
26
|
+
//#region ../../../1-framework/3-tooling/language-server/dist/exports/index.mjs
|
|
27
|
+
const ParseDiagnosticSeverity = {
|
|
28
|
+
Error: 1,
|
|
29
|
+
Warning: 2,
|
|
30
|
+
Information: 3,
|
|
31
|
+
Hint: 4
|
|
32
|
+
};
|
|
33
|
+
function mapParseDiagnostics(diagnostics) {
|
|
34
|
+
return diagnostics.map((diagnostic) => ({
|
|
35
|
+
range: diagnostic.range,
|
|
36
|
+
message: diagnostic.message,
|
|
37
|
+
code: diagnostic.code,
|
|
38
|
+
severity: ParseDiagnosticSeverity.Error
|
|
39
|
+
}));
|
|
40
|
+
}
|
|
41
|
+
const documentStartRange = {
|
|
42
|
+
start: {
|
|
43
|
+
line: 0,
|
|
44
|
+
character: 0
|
|
45
|
+
},
|
|
46
|
+
end: {
|
|
47
|
+
line: 0,
|
|
48
|
+
character: 1
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
function mapInterpreterDiagnostic(diagnostic, sourceFile) {
|
|
52
|
+
return {
|
|
53
|
+
range: diagnostic.span === void 0 ? documentStartRange : sourceFile.pslSpanToRange(diagnostic.span),
|
|
54
|
+
message: diagnostic.message,
|
|
55
|
+
code: diagnostic.code,
|
|
56
|
+
severity: diagnostic.severity === "warning" ? ParseDiagnosticSeverity.Warning : ParseDiagnosticSeverity.Error
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
function hasPslInputs(config) {
|
|
60
|
+
const source = config.contract?.source;
|
|
61
|
+
return source?.format === "psl" && source.inputs !== void 0;
|
|
62
|
+
}
|
|
63
|
+
async function resolveSchemaInputs(config, readText) {
|
|
64
|
+
const patterns = (hasPslInputs(config) ? config.contract?.source.inputs : void 0)?.map(toExpandablePath);
|
|
65
|
+
const expanded = await expandContractInputs(patterns);
|
|
66
|
+
const windows = isWindowsPlatform();
|
|
67
|
+
const candidates = expanded.map((path) => normalizeFileUri(pathToFileURL(path, { windows }).toString()));
|
|
68
|
+
const identities = new Set(candidates.map(canonicalFileIdentity));
|
|
69
|
+
function isMember(uri) {
|
|
70
|
+
if (!identities.has(canonicalFileIdentity(uri))) return false;
|
|
71
|
+
const text = readText(uri);
|
|
72
|
+
return text !== void 0 && isPrismaNextSchema(text);
|
|
73
|
+
}
|
|
74
|
+
return {
|
|
75
|
+
includes: isMember,
|
|
76
|
+
uris: () => candidates.filter(isMember)
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function toExpandablePath(input) {
|
|
80
|
+
return isFileUri(input) ? fileURLToPath(new URL(input), { windows: isWindowsPlatform() }) : input;
|
|
81
|
+
}
|
|
82
|
+
function isWatcherCacheEligible(config) {
|
|
83
|
+
const patterns = config.contract?.source.inputs;
|
|
84
|
+
return hasPslInputs(config) && patterns !== void 0 && patterns.length > 0 && patterns.every((pattern) => /^[A-Za-z0-9_./: *?-]+$/.test(pattern) && !isFileUri(pattern) && pattern.split("/").every((segment) => !segment.includes("**") || segment === "**"));
|
|
85
|
+
}
|
|
86
|
+
function toWatcherGlobPattern(pattern) {
|
|
87
|
+
return isWindowsPlatform() ? pattern.replaceAll("\\", "/") : pattern;
|
|
88
|
+
}
|
|
89
|
+
function isFileUri(input) {
|
|
90
|
+
try {
|
|
91
|
+
return new URL(input).protocol === "file:";
|
|
92
|
+
} catch {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
function canonicalFileIdentity(uri) {
|
|
97
|
+
let url;
|
|
98
|
+
try {
|
|
99
|
+
url = new URL(uri);
|
|
100
|
+
} catch {
|
|
101
|
+
return uri;
|
|
102
|
+
}
|
|
103
|
+
if (url.protocol !== "file:") return uri;
|
|
104
|
+
try {
|
|
105
|
+
const windows = isWindowsPlatform();
|
|
106
|
+
const filePath = normalize$1(fileURLToPath(url, { windows }));
|
|
107
|
+
return windows ? filePath.toLowerCase() : filePath;
|
|
108
|
+
} catch {
|
|
109
|
+
return uri;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function normalizeFileUri(uri) {
|
|
113
|
+
const identity = canonicalFileIdentity(uri);
|
|
114
|
+
return identity === uri ? uri : pathToFileURL(identity, { windows: isWindowsPlatform() }).toString();
|
|
115
|
+
}
|
|
116
|
+
function isWindowsPlatform() {
|
|
117
|
+
return process.platform === "win32";
|
|
118
|
+
}
|
|
119
|
+
var DocumentSnapshot = class {
|
|
120
|
+
uri;
|
|
121
|
+
text;
|
|
122
|
+
parserOptions;
|
|
123
|
+
#parsed;
|
|
124
|
+
constructor(uri, text, parserOptions = {}) {
|
|
125
|
+
this.uri = normalizeFileUri(uri);
|
|
126
|
+
this.text = text;
|
|
127
|
+
this.parserOptions = parserOptions;
|
|
128
|
+
Object.freeze(this);
|
|
129
|
+
}
|
|
130
|
+
parse() {
|
|
131
|
+
this.#parsed ??= parse(this.text, this.uri, this.parserOptions);
|
|
132
|
+
return this.#parsed;
|
|
133
|
+
}
|
|
134
|
+
get sourceFile() {
|
|
135
|
+
const { document, sources } = this.parse();
|
|
136
|
+
return sources.sourceFileFor(document.syntax);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
function statSafe(path) {
|
|
140
|
+
try {
|
|
141
|
+
const stats = statSync(path);
|
|
142
|
+
return {
|
|
143
|
+
mtime: stats.mtimeMs,
|
|
144
|
+
size: stats.size
|
|
145
|
+
};
|
|
146
|
+
} catch {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function readDiskEntry(path, uri) {
|
|
151
|
+
const stats = statSafe(path);
|
|
152
|
+
if (stats === void 0) return void 0;
|
|
153
|
+
try {
|
|
154
|
+
return {
|
|
155
|
+
origin: "disk",
|
|
156
|
+
snapshot: new DocumentSnapshot(uri, readFileSync(path, "utf8")),
|
|
157
|
+
mtime: stats.mtime,
|
|
158
|
+
size: stats.size
|
|
159
|
+
};
|
|
160
|
+
} catch {
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
var DocumentStore = class {
|
|
165
|
+
entries = /* @__PURE__ */ new Map();
|
|
166
|
+
watchCoverage = /* @__PURE__ */ new Map();
|
|
167
|
+
watchedIdentities = /* @__PURE__ */ new Set();
|
|
168
|
+
setWatchCoverage(owner, uris) {
|
|
169
|
+
const identities = new Set(Array.from(uris, canonicalFileIdentity));
|
|
170
|
+
if (identities.size === 0) this.watchCoverage.delete(owner);
|
|
171
|
+
else this.watchCoverage.set(owner, identities);
|
|
172
|
+
const next = /* @__PURE__ */ new Set();
|
|
173
|
+
for (const coverage of this.watchCoverage.values()) for (const identity of coverage) next.add(identity);
|
|
174
|
+
for (const identity of this.watchedIdentities) if (!next.has(identity)) this.invalidate(identity);
|
|
175
|
+
for (const identity of next) if (!this.watchedIdentities.has(identity)) this.invalidate(identity);
|
|
176
|
+
this.watchedIdentities = next;
|
|
177
|
+
}
|
|
178
|
+
getOpenDocument = (uri) => {
|
|
179
|
+
const entry = this.entries.get(canonicalFileIdentity(uri));
|
|
180
|
+
return entry?.origin === "overlay" ? entry.document : void 0;
|
|
181
|
+
};
|
|
182
|
+
openDocuments() {
|
|
183
|
+
const documents = [];
|
|
184
|
+
for (const entry of this.entries.values()) if (entry.origin === "overlay") documents.push(entry.document);
|
|
185
|
+
return documents;
|
|
186
|
+
}
|
|
187
|
+
text(uri) {
|
|
188
|
+
return this.readSnapshot(uri)?.text;
|
|
189
|
+
}
|
|
190
|
+
readSnapshot = (uri) => {
|
|
191
|
+
const identity = canonicalFileIdentity(uri);
|
|
192
|
+
const entry = this.entries.get(identity);
|
|
193
|
+
if (entry?.origin === "overlay") return entry.snapshot;
|
|
194
|
+
if (entry?.origin === "disk") {
|
|
195
|
+
if (this.watchedIdentities.has(identity)) return entry.snapshot;
|
|
196
|
+
const stats = statSafe(identity);
|
|
197
|
+
if (stats !== void 0 && stats.mtime === entry.mtime && stats.size === entry.size) return entry.snapshot;
|
|
198
|
+
}
|
|
199
|
+
const fresh = readDiskEntry(identity, normalizeFileUri(uri));
|
|
200
|
+
if (fresh === void 0) {
|
|
201
|
+
this.entries.delete(identity);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
this.entries.set(identity, fresh);
|
|
205
|
+
return fresh.snapshot;
|
|
206
|
+
};
|
|
207
|
+
invalidate(uri) {
|
|
208
|
+
const identity = canonicalFileIdentity(uri);
|
|
209
|
+
if (this.entries.get(identity)?.origin === "disk") this.entries.delete(identity);
|
|
210
|
+
}
|
|
211
|
+
open(item) {
|
|
212
|
+
const uri = normalizeFileUri(item.uri);
|
|
213
|
+
const document = TextDocument.create(uri, item.languageId, item.version, item.text);
|
|
214
|
+
this.entries.set(canonicalFileIdentity(item.uri), {
|
|
215
|
+
origin: "overlay",
|
|
216
|
+
document,
|
|
217
|
+
snapshot: new DocumentSnapshot(uri, item.text)
|
|
218
|
+
});
|
|
219
|
+
return document;
|
|
220
|
+
}
|
|
221
|
+
change(identifier, changes) {
|
|
222
|
+
if (changes.length === 0) return void 0;
|
|
223
|
+
const { uri, version } = identifier;
|
|
224
|
+
if (version === null || version === void 0) throw new InternalError(`Received document change event for ${uri} without valid version identifier`);
|
|
225
|
+
const document = this.getOpenDocument(uri);
|
|
226
|
+
if (document === void 0) return void 0;
|
|
227
|
+
const updated = TextDocument.update(document, changes, version);
|
|
228
|
+
this.entries.set(canonicalFileIdentity(uri), {
|
|
229
|
+
origin: "overlay",
|
|
230
|
+
document: updated,
|
|
231
|
+
snapshot: new DocumentSnapshot(updated.uri, updated.getText())
|
|
232
|
+
});
|
|
233
|
+
return updated;
|
|
234
|
+
}
|
|
235
|
+
close(uri) {
|
|
236
|
+
const document = this.getOpenDocument(uri);
|
|
237
|
+
this.entries.delete(canonicalFileIdentity(uri));
|
|
238
|
+
return document;
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
/**
|
|
242
|
+
* Wraps a connection so that an outbound call the client is no longer there to
|
|
243
|
+
* receive does nothing, instead of throwing at whoever made it.
|
|
244
|
+
*
|
|
245
|
+
* `vscode-jsonrpc` marks the connection closed the moment the input stream
|
|
246
|
+
* ends, and every send after that throws synchronously. A throw that escapes a
|
|
247
|
+
* notification handler ends the process: jsonrpc reports it through its logger,
|
|
248
|
+
* which is the connection's own remote console, so the report is another send —
|
|
249
|
+
* it throws again inside a `.catch()`, and the unhandled rejection is fatal.
|
|
250
|
+
*
|
|
251
|
+
* The wrapper carries the check so no individual send site has to: reads walk
|
|
252
|
+
* the connection's features (`console`, `languages`, …) and hand back guarded
|
|
253
|
+
* functions, so a send added later is guarded by construction. Only the
|
|
254
|
+
* connection's departure is swallowed — any other synchronous failure is a bug
|
|
255
|
+
* in the caller and still reaches it.
|
|
256
|
+
*/
|
|
257
|
+
function guardedConnection(connection) {
|
|
258
|
+
return guardCalls(connection);
|
|
259
|
+
}
|
|
260
|
+
function guardCalls(target) {
|
|
261
|
+
const guarded = /* @__PURE__ */ new Map();
|
|
262
|
+
return new Proxy(target, { get: (source, property) => {
|
|
263
|
+
const cached = guarded.get(property);
|
|
264
|
+
if (cached !== void 0) return cached;
|
|
265
|
+
const value = Reflect.get(source, property);
|
|
266
|
+
if (typeof value === "function") {
|
|
267
|
+
const call = (...args) => whileConnected(() => Reflect.apply(value, source, args));
|
|
268
|
+
guarded.set(property, call);
|
|
269
|
+
return call;
|
|
270
|
+
}
|
|
271
|
+
if (typeof value === "object" && value !== null) {
|
|
272
|
+
const feature = guardCalls(value);
|
|
273
|
+
guarded.set(property, feature);
|
|
274
|
+
return feature;
|
|
275
|
+
}
|
|
276
|
+
return value;
|
|
277
|
+
} });
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Whether an error says the connection is gone.
|
|
281
|
+
*
|
|
282
|
+
* The identity check is the fast path. It misses when the error comes from a
|
|
283
|
+
* second copy of `vscode-jsonrpc` in the dependency tree, whose
|
|
284
|
+
* `ConnectionError` is a different class carrying the same shape, so the code
|
|
285
|
+
* is what decides: `Closed`, `Disposed` and `AlreadyListening` are the whole
|
|
286
|
+
* range, and no other error jsonrpc throws carries a numeric `code` in it.
|
|
287
|
+
*/
|
|
288
|
+
function isConnectionGone(error) {
|
|
289
|
+
if (error instanceof ConnectionError) return true;
|
|
290
|
+
if (!(error instanceof Error) || !("code" in error)) return false;
|
|
291
|
+
const { code } = error;
|
|
292
|
+
return code === ConnectionErrors.Closed || code === ConnectionErrors.Disposed || code === ConnectionErrors.AlreadyListening;
|
|
293
|
+
}
|
|
294
|
+
function whileConnected(send) {
|
|
295
|
+
let sent;
|
|
296
|
+
try {
|
|
297
|
+
sent = send();
|
|
298
|
+
} catch (error) {
|
|
299
|
+
if (isConnectionGone(error)) return Promise.resolve(void 0);
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
return isThenable(sent) ? sent.then(void 0, () => void 0) : sent;
|
|
303
|
+
}
|
|
304
|
+
function isThenable(value) {
|
|
305
|
+
return typeof value === "object" && value !== null && "then" in value && typeof Reflect.get(value, "then") === "function";
|
|
306
|
+
}
|
|
307
|
+
const CONFIG_FILENAME = "prisma.config.ts";
|
|
308
|
+
const emptyLspControlStack = {
|
|
309
|
+
scalarTypes: [],
|
|
310
|
+
defaultNamespaceId: UNBOUND_NAMESPACE_ID,
|
|
311
|
+
pslBlockDescriptors: {},
|
|
312
|
+
generatorFunctions: EMPTY_GENERATOR_FUNCTIONS
|
|
313
|
+
};
|
|
314
|
+
async function resolveConfigInputs(configPath, readText) {
|
|
315
|
+
const loaded = await loadConfig(configPath);
|
|
316
|
+
if (!loaded.ok) throw loaded.failure;
|
|
317
|
+
const projectSections = requireConfigSections(loaded.value, ["contract", "formatter"]);
|
|
318
|
+
if (!projectSections.ok) throw projectSections.failure;
|
|
319
|
+
const config = projectSections.value;
|
|
320
|
+
const inputs = await resolveSchemaInputs(config, readText);
|
|
321
|
+
const schemaInputConfig = config.contract === void 0 ? {} : { contract: config.contract };
|
|
322
|
+
if (!hasPslInputs(config)) return {
|
|
323
|
+
inputs,
|
|
324
|
+
schemaInputConfig,
|
|
325
|
+
controlStack: emptyLspControlStack,
|
|
326
|
+
...config.formatter === void 0 ? {} : { formatter: config.formatter }
|
|
327
|
+
};
|
|
328
|
+
const controlSections = requireConfigSections(loaded.value, [
|
|
329
|
+
"family",
|
|
330
|
+
"target",
|
|
331
|
+
"adapter",
|
|
332
|
+
"driver",
|
|
333
|
+
"extensions"
|
|
334
|
+
]);
|
|
335
|
+
if (!controlSections.ok) throw controlSections.failure;
|
|
336
|
+
const stack = createControlStack(config);
|
|
337
|
+
const interpretation = resolveInterpretation(config, stack, inputs);
|
|
338
|
+
const parserOptions = config.contract?.source.format === "psl" ? config.contract.source.parserOptions : void 0;
|
|
339
|
+
return {
|
|
340
|
+
inputs,
|
|
341
|
+
schemaInputConfig,
|
|
342
|
+
controlStack: lspControlStackFromStack(stack),
|
|
343
|
+
...config.formatter === void 0 ? {} : { formatter: config.formatter },
|
|
344
|
+
...parserOptions === void 0 ? {} : { parserOptions },
|
|
345
|
+
...interpretation === void 0 ? {} : { interpretation }
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
function lspControlStackFromStack(stack) {
|
|
349
|
+
return {
|
|
350
|
+
scalarTypes: [...stack.scalarTypes],
|
|
351
|
+
defaultNamespaceId: stack.target.defaultNamespaceId,
|
|
352
|
+
pslBlockDescriptors: stack.authoringContributions.pslBlockDescriptors,
|
|
353
|
+
authoringContributions: stack.authoringContributions,
|
|
354
|
+
dataTypes: stack.dataTypes,
|
|
355
|
+
...stack.controlMutationDefaults === void 0 ? {} : { controlMutationDefaults: stack.controlMutationDefaults },
|
|
356
|
+
generatorFunctions: stack.generatorFunctions,
|
|
357
|
+
...ifDefined("pslDiagnostics", stack.family?.pslDiagnostics)
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
function resolveInterpretation(config, stack, inputs) {
|
|
361
|
+
const source = config.contract?.source;
|
|
362
|
+
if (source === void 0 || !hasPslInterpreter(source)) return;
|
|
363
|
+
return {
|
|
364
|
+
source,
|
|
365
|
+
context: {
|
|
366
|
+
composedExtensions: stack.extensions.map((p) => p.id),
|
|
367
|
+
composedExtensionContracts: stack.extensionContracts,
|
|
368
|
+
authoringContributions: stack.authoringContributions,
|
|
369
|
+
...ifDefined("pslDiagnostics", stack.family?.pslDiagnostics),
|
|
370
|
+
codecLookup: stack.codecLookup,
|
|
371
|
+
dataTypes: stack.dataTypes,
|
|
372
|
+
controlMutationDefaults: stack.controlMutationDefaults,
|
|
373
|
+
generatorFunctions: stack.generatorFunctions,
|
|
374
|
+
resolvedInputs: [...inputs.uris()],
|
|
375
|
+
capabilities: stack.capabilities,
|
|
376
|
+
defaultNamespaceId: stack.target.defaultNamespaceId
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
const FIELD_BLOCK_KEYWORDS$1 = /* @__PURE__ */ new Set(["model", "type"]);
|
|
381
|
+
function castModelBlock(node) {
|
|
382
|
+
const model = ModelDeclarationAst.cast(node);
|
|
383
|
+
if (model !== void 0) return model;
|
|
384
|
+
const mixin = MixinDeclarationAst.cast(node);
|
|
385
|
+
return mixin?.keyword()?.text === "model" ? mixin : void 0;
|
|
386
|
+
}
|
|
387
|
+
function castFieldBlock(node) {
|
|
388
|
+
const block = ModelDeclarationAst.cast(node) ?? CompositeTypeDeclarationAst.cast(node);
|
|
389
|
+
if (block !== void 0) return block;
|
|
390
|
+
const mixin = MixinDeclarationAst.cast(node);
|
|
391
|
+
return FIELD_BLOCK_KEYWORDS$1.has(mixin?.keyword()?.text ?? "") ? mixin : void 0;
|
|
392
|
+
}
|
|
393
|
+
function castEntryBlock(node) {
|
|
394
|
+
const block = GenericBlockDeclarationAst.cast(node);
|
|
395
|
+
if (block !== void 0) return block;
|
|
396
|
+
const mixin = MixinDeclarationAst.cast(node);
|
|
397
|
+
const keyword = mixin?.keyword()?.text;
|
|
398
|
+
return keyword !== void 0 && !FIELD_BLOCK_KEYWORDS$1.has(keyword) ? mixin : void 0;
|
|
399
|
+
}
|
|
400
|
+
function argumentRootGrammar(owner, source) {
|
|
401
|
+
switch (owner.ownerKind) {
|
|
402
|
+
case "field":
|
|
403
|
+
case "model":
|
|
404
|
+
case "block": return attributeSpecResolver(owner, source)(owner.attributeName);
|
|
405
|
+
case "blockValue": return blockValueGrammar(owner, source);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
function blockValueGrammar(owner, source) {
|
|
409
|
+
const descriptor = findBlockDescriptor(source.pslBlockDescriptors, owner.blockKeyword);
|
|
410
|
+
if (descriptor === void 0) return void 0;
|
|
411
|
+
const spec = blockSpecFactoryOf(descriptor)(blockSpecContext({
|
|
412
|
+
symbols: source.symbolTable,
|
|
413
|
+
dataTypes: source.dataTypes ?? EMPTY_DATA_TYPES
|
|
414
|
+
}));
|
|
415
|
+
if (spec.mode === "map") return spec.value.type;
|
|
416
|
+
return Object.hasOwn(spec.parameters, owner.key) ? spec.parameters[owner.key]?.type : void 0;
|
|
417
|
+
}
|
|
418
|
+
function attributeSpecResolver(context, source) {
|
|
419
|
+
switch (context.ownerKind) {
|
|
420
|
+
case "block": {
|
|
421
|
+
const descriptor = findBlockDescriptor(source.pslBlockDescriptors, context.blockKeyword);
|
|
422
|
+
return (name) => {
|
|
423
|
+
const factory = descriptor?.attributes?.[name];
|
|
424
|
+
if (factory === void 0) return void 0;
|
|
425
|
+
return blindCast(factory)(blockSpecContext({
|
|
426
|
+
symbols: source.symbolTable,
|
|
427
|
+
dataTypes: source.dataTypes ?? EMPTY_DATA_TYPES
|
|
428
|
+
}));
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
case "model": {
|
|
432
|
+
if (source.authoringContributions === void 0) return () => void 0;
|
|
433
|
+
const model = fieldSpecModel(source.binder.declaredSymbol(context.model.syntax));
|
|
434
|
+
if (model === void 0 || source.controlMutationDefaults === void 0) return () => void 0;
|
|
435
|
+
const specs = assembleAttributeSpecs(source.authoringContributions);
|
|
436
|
+
const specContext = {
|
|
437
|
+
symbols: source.symbolTable,
|
|
438
|
+
model,
|
|
439
|
+
defaultFunctionRegistry: source.controlMutationDefaults.defaultFunctionRegistry,
|
|
440
|
+
generatorFunctions: source.generatorFunctions,
|
|
441
|
+
dataTypes: source.dataTypes ?? EMPTY_DATA_TYPES
|
|
442
|
+
};
|
|
443
|
+
return (name) => specs.model[name]?.(specContext);
|
|
444
|
+
}
|
|
445
|
+
case "field": {
|
|
446
|
+
if (source.authoringContributions === void 0) return () => void 0;
|
|
447
|
+
const model = fieldSpecModel(source.binder.declaredSymbol(context.model.syntax));
|
|
448
|
+
if (model === void 0 || source.controlMutationDefaults === void 0) return () => void 0;
|
|
449
|
+
const field = source.binder.declaredSymbol(context.field.syntax);
|
|
450
|
+
if (field?.kind !== "field") return () => void 0;
|
|
451
|
+
const specs = assembleAttributeSpecs(source.authoringContributions);
|
|
452
|
+
const specContext = {
|
|
453
|
+
symbols: source.symbolTable,
|
|
454
|
+
model,
|
|
455
|
+
defaultFunctionRegistry: source.controlMutationDefaults.defaultFunctionRegistry,
|
|
456
|
+
generatorFunctions: source.generatorFunctions,
|
|
457
|
+
dataTypes: source.dataTypes ?? EMPTY_DATA_TYPES
|
|
458
|
+
};
|
|
459
|
+
const node = typeReferenceNode(field);
|
|
460
|
+
const typeResolution = node === void 0 ? void 0 : source.binder.symbolForNode(node);
|
|
461
|
+
const typeConstructor = contributedTypeOf(typeResolution, source.binder);
|
|
462
|
+
return (name) => specs.field[name]?.({
|
|
463
|
+
...specContext,
|
|
464
|
+
field,
|
|
465
|
+
typeResolution,
|
|
466
|
+
typeConstructor
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
function fieldSpecModel(symbol) {
|
|
472
|
+
if (symbol?.kind === "model") return symbol;
|
|
473
|
+
return symbol?.kind === "mixin" && symbol.keyword === "model" ? symbol : void 0;
|
|
474
|
+
}
|
|
475
|
+
function locateAttributeSyntax(input) {
|
|
476
|
+
const offset = input.sourceFile.offsetAt(input.position);
|
|
477
|
+
const at = input.document.syntax.tokenAtOffset(offset);
|
|
478
|
+
if (at.leftBiased()?.kind === "Comment") return void 0;
|
|
479
|
+
const token = at.leftBiased() ?? at.rightBiased();
|
|
480
|
+
const attribute = token === void 0 ? void 0 : skipTriviaToken(token, "prev")?.parent.findAncestor(any(FieldAttributeAst.cast, ModelAttributeAst.cast));
|
|
481
|
+
if (attribute === void 0 || !isWithinAttributeOrOpenArguments(attribute, offset)) return void 0;
|
|
482
|
+
return {
|
|
483
|
+
attribute,
|
|
484
|
+
...attributeCursor(attribute, offset)
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
function isWithinAttributeOrOpenArguments(attribute, offset) {
|
|
488
|
+
if (attribute.syntax.isInside(offset)) return true;
|
|
489
|
+
const args = attribute.argList();
|
|
490
|
+
return args !== void 0 && args.rparen() === void 0 && offset >= args.syntax.endOffset;
|
|
491
|
+
}
|
|
492
|
+
function attributeCursor(attribute, offset) {
|
|
493
|
+
const anchor = attribute.syntax.tokenAtOffset(offset).leftBiased() ?? attribute.syntax.lastToken;
|
|
494
|
+
return {
|
|
495
|
+
offset,
|
|
496
|
+
preceding: anchor === void 0 ? void 0 : skipTriviaToken(anchor, "prev")
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
function argumentSiblings(node, selected, offset) {
|
|
500
|
+
let precedingPositionalCount = 0;
|
|
501
|
+
const otherNamedKeys = [];
|
|
502
|
+
let beforeSelected = true;
|
|
503
|
+
for (const arg of node.args()) {
|
|
504
|
+
if (arg.syntax.offset === selected?.syntax.offset) {
|
|
505
|
+
beforeSelected = false;
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
const name = arg.name()?.name();
|
|
509
|
+
if (name !== void 0) otherNamedKeys.push(name);
|
|
510
|
+
else if (beforeSelected && arg.syntax.offset <= offset) precedingPositionalCount += 1;
|
|
511
|
+
}
|
|
512
|
+
return {
|
|
513
|
+
precedingPositionalCount,
|
|
514
|
+
otherNamedKeys
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
function argumentAtCursor(cursor, node) {
|
|
518
|
+
for (const arg of node.args()) if (arg.syntax.offset <= cursor.offset && (containsCursor(arg.syntax, cursor) || recoveredContainerContainsCursor(arg.value(), cursor.offset))) return arg;
|
|
519
|
+
}
|
|
520
|
+
function listElementAtCursor(cursor, node) {
|
|
521
|
+
for (const element of node.elements()) if (containsCursor(element.syntax, cursor) || recoveredContainerContainsCursor(element, cursor.offset)) return element;
|
|
522
|
+
}
|
|
523
|
+
function recordFieldAtCursor(cursor, node) {
|
|
524
|
+
for (const field of node.fields()) {
|
|
525
|
+
const colon = field.colon();
|
|
526
|
+
if (colon !== void 0 && cursor.offset > colon.offset && (containsCursor(field.syntax, cursor) || recoveredContainerContainsCursor(field.value(), cursor.offset))) return field;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
function betweenDelimiters(offset, opening, closing) {
|
|
530
|
+
return opening !== void 0 && offset > opening.offset && (closing === void 0 || offset < closing.endOffset);
|
|
531
|
+
}
|
|
532
|
+
function recoveredContainerContainsCursor(expression, offset) {
|
|
533
|
+
if (expression === void 0 || expression.syntax.endOffset > offset) return false;
|
|
534
|
+
if (!(expression instanceof ArrayLiteralAst ? expression.rbracket() === void 0 : expression instanceof ObjectLiteralExprAst ? expression.rbrace() === void 0 : expression instanceof FunctionCallAst && expression.rparen() === void 0)) return false;
|
|
535
|
+
for (let token = expression.syntax.lastToken?.nextToken; token !== void 0; token = token.nextToken) {
|
|
536
|
+
if (token.offset >= offset) return true;
|
|
537
|
+
if (!isTrivia(token) && token.kind !== "Comma") return false;
|
|
538
|
+
}
|
|
539
|
+
return true;
|
|
540
|
+
}
|
|
541
|
+
function containsCursor(node, cursor) {
|
|
542
|
+
if (node.isInside(cursor.offset)) return true;
|
|
543
|
+
const preceding = cursor.preceding;
|
|
544
|
+
return preceding !== void 0 && preceding.endOffset <= cursor.offset && preceding.offset >= node.offset && preceding.offset < node.endOffset;
|
|
545
|
+
}
|
|
546
|
+
const UNSUPPORTED = { kind: "unsupported" };
|
|
547
|
+
function classifyPslCompletionContext(input) {
|
|
548
|
+
const root = input.document.syntax;
|
|
549
|
+
const offset = input.sourceFile.offsetAt(input.position);
|
|
550
|
+
const at = root.tokenAtOffset(offset);
|
|
551
|
+
if (at.leftBiased()?.kind === "Comment") return UNSUPPORTED;
|
|
552
|
+
const edit = cursorIdentifier(at, offset);
|
|
553
|
+
const preceding = precedingToken(at, edit);
|
|
554
|
+
const precedingNode = preceding?.parent;
|
|
555
|
+
const replacementStartOffset = edit?.offset ?? offset;
|
|
556
|
+
const attributeClassifierInput = {
|
|
557
|
+
offset,
|
|
558
|
+
node: attributeAnchor(at),
|
|
559
|
+
replacementStartOffset
|
|
560
|
+
};
|
|
561
|
+
const attributeContext = classifyFieldAttribute(attributeClassifierInput) ?? classifyGenericBlockAttribute(attributeClassifierInput) ?? classifyModelAttribute(attributeClassifierInput);
|
|
562
|
+
if (attributeContext !== void 0) return attributeContext;
|
|
563
|
+
const inclusionContext = classifyMixinInclusion({
|
|
564
|
+
node: precedingNode,
|
|
565
|
+
offset,
|
|
566
|
+
replacementStartOffset
|
|
567
|
+
});
|
|
568
|
+
if (inclusionContext !== void 0) return inclusionContext;
|
|
569
|
+
const declarationKeywordContext = classifyDeclarationKeyword({
|
|
570
|
+
node: precedingNode,
|
|
571
|
+
offset,
|
|
572
|
+
replacementStartOffset
|
|
573
|
+
});
|
|
574
|
+
if (declarationKeywordContext !== void 0) return declarationKeywordContext;
|
|
575
|
+
const genericBlockContext = classifyGenericBlockParameter({
|
|
576
|
+
offset,
|
|
577
|
+
at,
|
|
578
|
+
precedingToken: preceding,
|
|
579
|
+
replacementStartOffset
|
|
580
|
+
});
|
|
581
|
+
if (genericBlockContext !== void 0) return genericBlockContext;
|
|
582
|
+
const field = fieldForTypeSlot(precedingNode);
|
|
583
|
+
if (field === void 0) return UNSUPPORTED;
|
|
584
|
+
if (field.syntax.findAncestor(castFieldBlock) === void 0) return UNSUPPORTED;
|
|
585
|
+
return classifyModelFieldType({
|
|
586
|
+
field,
|
|
587
|
+
offset,
|
|
588
|
+
replacementStartOffset,
|
|
589
|
+
precedingToken: preceding
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
/**
|
|
593
|
+
* Locates the field whose type position the cursor occupies. The preceding token
|
|
594
|
+
* climbs to the field whether the cursor sits inside a present type (the type
|
|
595
|
+
* identifier's predecessor still belongs to the field) or in the empty type slot
|
|
596
|
+
* of a typeless field (whose trailing trivia lives in the enclosing block, so
|
|
597
|
+
* the nearest significant token to the left is the field's own name).
|
|
598
|
+
*/
|
|
599
|
+
function fieldForTypeSlot(precedingNode) {
|
|
600
|
+
return precedingNode?.findAncestor(FieldDeclarationAst.cast);
|
|
601
|
+
}
|
|
602
|
+
function classifyModelFieldType(input) {
|
|
603
|
+
const fieldName = input.field.name();
|
|
604
|
+
if (fieldName === void 0) return UNSUPPORTED;
|
|
605
|
+
const fieldNameText = fieldName.name();
|
|
606
|
+
if (fieldNameText === void 0) return UNSUPPORTED;
|
|
607
|
+
if (fieldName.syntax.isInside(input.offset)) return UNSUPPORTED;
|
|
608
|
+
const typeAnnotation = input.field.typeAnnotation();
|
|
609
|
+
if (typeAnnotation === void 0) {
|
|
610
|
+
if (input.precedingToken !== void 0 && fieldName.syntax.isInside(input.precedingToken.offset)) return {
|
|
611
|
+
kind: "modelType",
|
|
612
|
+
field: input.field,
|
|
613
|
+
offset: input.offset,
|
|
614
|
+
fieldName: fieldNameText,
|
|
615
|
+
replacementStartOffset: input.offset
|
|
616
|
+
};
|
|
617
|
+
return UNSUPPORTED;
|
|
618
|
+
}
|
|
619
|
+
if (typeAnnotation.syntax.isOutside(input.offset)) return UNSUPPORTED;
|
|
620
|
+
if (typeAnnotation.argList()?.syntax.isInside(input.offset)) return UNSUPPORTED;
|
|
621
|
+
const name = typeAnnotation.name();
|
|
622
|
+
if (name === void 0) return UNSUPPORTED;
|
|
623
|
+
if (name.syntax.isOutside(input.offset)) return UNSUPPORTED;
|
|
624
|
+
if (name.isOverQualified()) return UNSUPPORTED;
|
|
625
|
+
return classifyTypePosition(name, input.field, input.offset, fieldNameText, input.replacementStartOffset);
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Builds the type-completion context for a qualified name. Roles are read
|
|
629
|
+
* straight off the separator-positional accessors: a populated namespace
|
|
630
|
+
* segment is a `.`-qualified name, a populated space segment is a `:`-qualified
|
|
631
|
+
* name, and the absence of both is a bare model type.
|
|
632
|
+
*
|
|
633
|
+
* Behaviour change: a `:`-qualified name with no `.` (e.g. `supabase:`,
|
|
634
|
+
* `supabase:U`) is a `spaceMember` position rather than falling through to bare
|
|
635
|
+
* model-type completions. A malformed leading-separator name (`:User`, `.User`)
|
|
636
|
+
* carries no populated segment and resolves to `modelType` rather than
|
|
637
|
+
* `unsupported`.
|
|
638
|
+
*/
|
|
639
|
+
function classifyTypePosition(name, field, offset, fieldName, replacementStartOffset) {
|
|
640
|
+
const namespace = name.namespace()?.name();
|
|
641
|
+
if (namespace !== void 0 && namespace.length > 0) {
|
|
642
|
+
const namespaceSpace = name.space()?.name();
|
|
643
|
+
return {
|
|
644
|
+
kind: "namespaceMember",
|
|
645
|
+
field,
|
|
646
|
+
offset,
|
|
647
|
+
fieldName,
|
|
648
|
+
replacementStartOffset,
|
|
649
|
+
namespace,
|
|
650
|
+
...namespaceSpace !== void 0 && namespaceSpace.length > 0 ? { space: namespaceSpace } : {}
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
const space = name.space()?.name();
|
|
654
|
+
if (space !== void 0 && space.length > 0) return {
|
|
655
|
+
kind: "spaceMember",
|
|
656
|
+
offset,
|
|
657
|
+
fieldName,
|
|
658
|
+
replacementStartOffset,
|
|
659
|
+
space
|
|
660
|
+
};
|
|
661
|
+
return {
|
|
662
|
+
kind: "modelType",
|
|
663
|
+
field,
|
|
664
|
+
offset,
|
|
665
|
+
fieldName,
|
|
666
|
+
replacementStartOffset
|
|
667
|
+
};
|
|
668
|
+
}
|
|
669
|
+
const declarationCast = any(ModelDeclarationAst.cast, CompositeTypeDeclarationAst.cast, TypesBlockAst.cast, GenericBlockDeclarationAst.cast, MixinDeclarationAst.cast, NamespaceDeclarationAst.cast);
|
|
670
|
+
function classifyDeclarationKeyword(input) {
|
|
671
|
+
const precedingDeclaration = input.node?.findAncestor(declarationCast);
|
|
672
|
+
const namespace = input.node?.findAncestor(NamespaceDeclarationAst.cast);
|
|
673
|
+
const inNamespaceBody = blockBodyContainsOffset(namespace, input.offset);
|
|
674
|
+
if (precedingDeclaration !== void 0 && !canCompleteDeclaration(precedingDeclaration, input.offset, inNamespaceBody)) return;
|
|
675
|
+
return {
|
|
676
|
+
kind: "declarationKeyword",
|
|
677
|
+
offset: input.offset,
|
|
678
|
+
scope: inNamespaceBody ? "namespace" : "document",
|
|
679
|
+
replacementStartOffset: input.replacementStartOffset
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
/**
|
|
683
|
+
* Whether a new declaration can begin at the cursor, given the nearest enclosing
|
|
684
|
+
* declaration. Allowed when that declaration is still nascent (only its keyword
|
|
685
|
+
* typed, no name or body yet), when it is a namespace whose body holds further
|
|
686
|
+
* declarations, or when the cursor sits past its closing `}`.
|
|
687
|
+
*/
|
|
688
|
+
function canCompleteDeclaration(precedingDeclaration, offset, inNamespaceBody) {
|
|
689
|
+
if (precedingDeclaration.lbrace() === void 0 && !(precedingDeclaration instanceof MixinDeclarationAst) && (precedingDeclaration instanceof TypesBlockAst || precedingDeclaration.name() === void 0)) return true;
|
|
690
|
+
if (precedingDeclaration instanceof NamespaceDeclarationAst && inNamespaceBody) return true;
|
|
691
|
+
const rbrace = precedingDeclaration.rbrace();
|
|
692
|
+
return rbrace !== void 0 && offset >= rbrace.endOffset;
|
|
693
|
+
}
|
|
694
|
+
function blockBodyContainsOffset(block, offset) {
|
|
695
|
+
if (block === void 0) return false;
|
|
696
|
+
const lbrace = block.lbrace();
|
|
697
|
+
if (lbrace === void 0) return false;
|
|
698
|
+
const bodyStart = lbrace.endOffset;
|
|
699
|
+
const bodyEnd = block.rbrace()?.offset ?? block.syntax.endOffset;
|
|
700
|
+
return offset >= bodyStart && offset <= bodyEnd;
|
|
701
|
+
}
|
|
702
|
+
function classifyFieldAttribute(input) {
|
|
703
|
+
const attribute = input.node?.findAncestor(FieldAttributeAst.cast);
|
|
704
|
+
if (attribute === void 0 || !isWithinAttributeOrOpenArguments(attribute, input.offset)) return;
|
|
705
|
+
const field = attribute.syntax.findAncestor(FieldDeclarationAst.cast);
|
|
706
|
+
const model = attribute.syntax.findAncestor(castModelBlock);
|
|
707
|
+
if (field === void 0 || model === void 0) return UNSUPPORTED;
|
|
708
|
+
const owner = {
|
|
709
|
+
ownerKind: "field",
|
|
710
|
+
field,
|
|
711
|
+
model
|
|
712
|
+
};
|
|
713
|
+
return classifyAttributePosition(attribute, input, {
|
|
714
|
+
name: (position) => ({
|
|
715
|
+
kind: "fieldAttributeName",
|
|
716
|
+
...position,
|
|
717
|
+
...owner
|
|
718
|
+
}),
|
|
719
|
+
arguments: (attributeName) => ({
|
|
720
|
+
namedKey: (position) => ({
|
|
721
|
+
kind: "fieldAttributeNamedKey",
|
|
722
|
+
...position,
|
|
723
|
+
...owner,
|
|
724
|
+
attributeName
|
|
725
|
+
}),
|
|
726
|
+
argumentSlot: (position) => ({
|
|
727
|
+
kind: "fieldAttributeArgumentSlot",
|
|
728
|
+
...position,
|
|
729
|
+
...owner,
|
|
730
|
+
attributeName
|
|
731
|
+
}),
|
|
732
|
+
value: (position) => ({
|
|
733
|
+
kind: "fieldAttributeValue",
|
|
734
|
+
...position,
|
|
735
|
+
...owner,
|
|
736
|
+
attributeName
|
|
737
|
+
})
|
|
738
|
+
})
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
function classifyGenericBlockAttribute(input) {
|
|
742
|
+
const attribute = activeModelAttribute(input);
|
|
743
|
+
const block = attribute?.syntax.findAncestor(castEntryBlock);
|
|
744
|
+
if (attribute === void 0 || block === void 0) return;
|
|
745
|
+
const blockKeyword = block.keyword()?.text;
|
|
746
|
+
if (blockKeyword === void 0 || blockKeyword.length === 0) return UNSUPPORTED;
|
|
747
|
+
const owner = {
|
|
748
|
+
ownerKind: "block",
|
|
749
|
+
block,
|
|
750
|
+
blockKeyword
|
|
751
|
+
};
|
|
752
|
+
return classifyAttributePosition(attribute, input, {
|
|
753
|
+
name: (position) => ({
|
|
754
|
+
kind: "blockAttributeName",
|
|
755
|
+
...position,
|
|
756
|
+
...owner
|
|
757
|
+
}),
|
|
758
|
+
arguments: (attributeName) => ({
|
|
759
|
+
namedKey: (position) => ({
|
|
760
|
+
kind: "blockAttributeNamedKey",
|
|
761
|
+
...position,
|
|
762
|
+
...owner,
|
|
763
|
+
attributeName
|
|
764
|
+
}),
|
|
765
|
+
argumentSlot: (position) => ({
|
|
766
|
+
kind: "blockAttributeArgumentSlot",
|
|
767
|
+
...position,
|
|
768
|
+
...owner,
|
|
769
|
+
attributeName
|
|
770
|
+
}),
|
|
771
|
+
value: (position) => ({
|
|
772
|
+
kind: "blockAttributeValue",
|
|
773
|
+
...position,
|
|
774
|
+
...owner,
|
|
775
|
+
attributeName
|
|
776
|
+
})
|
|
777
|
+
})
|
|
778
|
+
});
|
|
779
|
+
}
|
|
780
|
+
function classifyModelAttribute(input) {
|
|
781
|
+
const attribute = activeModelAttribute(input);
|
|
782
|
+
if (attribute === void 0) return;
|
|
783
|
+
const model = attribute.syntax.findAncestor(castModelBlock);
|
|
784
|
+
if (model === void 0) return;
|
|
785
|
+
const owner = {
|
|
786
|
+
ownerKind: "model",
|
|
787
|
+
model
|
|
788
|
+
};
|
|
789
|
+
return classifyAttributePosition(attribute, input, {
|
|
790
|
+
name: (position) => ({
|
|
791
|
+
kind: "modelAttributeName",
|
|
792
|
+
...position,
|
|
793
|
+
...owner
|
|
794
|
+
}),
|
|
795
|
+
arguments: (attributeName) => ({
|
|
796
|
+
namedKey: (position) => ({
|
|
797
|
+
kind: "modelAttributeNamedKey",
|
|
798
|
+
...position,
|
|
799
|
+
...owner,
|
|
800
|
+
attributeName
|
|
801
|
+
}),
|
|
802
|
+
argumentSlot: (position) => ({
|
|
803
|
+
kind: "modelAttributeArgumentSlot",
|
|
804
|
+
...position,
|
|
805
|
+
...owner,
|
|
806
|
+
attributeName
|
|
807
|
+
}),
|
|
808
|
+
value: (position) => ({
|
|
809
|
+
kind: "modelAttributeValue",
|
|
810
|
+
...position,
|
|
811
|
+
...owner,
|
|
812
|
+
attributeName
|
|
813
|
+
})
|
|
814
|
+
})
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
function activeModelAttribute(input) {
|
|
818
|
+
const attribute = input.node?.findAncestor(ModelAttributeAst.cast);
|
|
819
|
+
if (attribute === void 0 || !isWithinAttributeOrOpenArguments(attribute, input.offset)) return;
|
|
820
|
+
return attribute;
|
|
821
|
+
}
|
|
822
|
+
function attributeAnchor(at) {
|
|
823
|
+
const token = at.leftBiased() ?? at.rightBiased();
|
|
824
|
+
return token === void 0 ? void 0 : skipTriviaToken(token, "prev")?.parent;
|
|
825
|
+
}
|
|
826
|
+
function classifyAttributePosition(attribute, input, factory) {
|
|
827
|
+
const args = attribute.argList();
|
|
828
|
+
if (args === void 0 || input.offset < args.syntax.offset) return factory.name({
|
|
829
|
+
offset: input.offset,
|
|
830
|
+
replacementStartOffset: input.replacementStartOffset,
|
|
831
|
+
replacementEndOffset: attribute.name()?.syntax.endOffset ?? input.offset,
|
|
832
|
+
hasArgumentList: args !== void 0
|
|
833
|
+
});
|
|
834
|
+
const attributeName = attribute.name()?.identifier()?.name();
|
|
835
|
+
if (attributeName === void 0) return UNSUPPORTED;
|
|
836
|
+
return classifyAttributeArguments({
|
|
837
|
+
...valueReplacement(attribute.syntax.tokenAtOffset(input.offset), input.offset),
|
|
838
|
+
preceding: attributeCursor(attribute, input.offset).preceding,
|
|
839
|
+
factory: factory.arguments(attributeName)
|
|
840
|
+
}, args, []);
|
|
841
|
+
}
|
|
842
|
+
function valueReplacement(at, offset) {
|
|
843
|
+
const right = at.rightBiased();
|
|
844
|
+
const token = isValueToken(right) ? right : at.leftBiased();
|
|
845
|
+
const replaceToken = isValueToken(token);
|
|
846
|
+
return {
|
|
847
|
+
offset,
|
|
848
|
+
replacementStartOffset: replaceToken ? token.offset : offset,
|
|
849
|
+
replacementEndOffset: replaceToken ? token.endOffset : offset
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
function argumentPosition(cursor, path) {
|
|
853
|
+
return {
|
|
854
|
+
offset: cursor.offset,
|
|
855
|
+
replacementStartOffset: cursor.replacementStartOffset,
|
|
856
|
+
replacementEndOffset: cursor.replacementEndOffset,
|
|
857
|
+
path
|
|
858
|
+
};
|
|
859
|
+
}
|
|
860
|
+
function classifyAttributeArguments(cursor, args, path) {
|
|
861
|
+
if (!betweenDelimiters(cursor.offset, args.lparen(), args.rparen())) return UNSUPPORTED;
|
|
862
|
+
const active = argumentAtCursor(cursor, args);
|
|
863
|
+
const { precedingPositionalCount: positionalIndex, otherNamedKeys: existingNamedKeys } = argumentSiblings(args, active, cursor.offset);
|
|
864
|
+
const position = argumentPosition(cursor, path);
|
|
865
|
+
if (active === void 0) return followsSeparator(cursor, ["LParen", "Comma"]) ? cursor.factory.argumentSlot({
|
|
866
|
+
...position,
|
|
867
|
+
positionalIndex,
|
|
868
|
+
existingNamedKeys,
|
|
869
|
+
hasColon: false
|
|
870
|
+
}) : UNSUPPORTED;
|
|
871
|
+
const colon = active.colon();
|
|
872
|
+
if (colon !== void 0) {
|
|
873
|
+
if (cursor.offset <= colon.offset) return cursor.factory.namedKey({
|
|
874
|
+
...position,
|
|
875
|
+
existingNamedKeys,
|
|
876
|
+
hasColon: true
|
|
877
|
+
});
|
|
878
|
+
const name = active.name()?.name();
|
|
879
|
+
return name === void 0 ? UNSUPPORTED : classifyAttributeExpression(cursor, active.value(), [...path, {
|
|
880
|
+
kind: "namedArgument",
|
|
881
|
+
name
|
|
882
|
+
}]);
|
|
883
|
+
}
|
|
884
|
+
const value = active.value();
|
|
885
|
+
if (value === void 0 || value instanceof IdentifierAst && value.syntax.isInside(cursor.offset)) return cursor.factory.argumentSlot({
|
|
886
|
+
...position,
|
|
887
|
+
positionalIndex,
|
|
888
|
+
existingNamedKeys,
|
|
889
|
+
hasColon: false
|
|
890
|
+
});
|
|
891
|
+
return classifyAttributeExpression(cursor, value, [...path, {
|
|
892
|
+
kind: "positionalArgument",
|
|
893
|
+
index: positionalIndex
|
|
894
|
+
}]);
|
|
895
|
+
}
|
|
896
|
+
function classifyAttributeExpression(cursor, expression, path) {
|
|
897
|
+
if (expression === void 0) return cursor.factory.value({
|
|
898
|
+
...argumentPosition(cursor, path),
|
|
899
|
+
syntax: "scalar",
|
|
900
|
+
qualifier: void 0
|
|
901
|
+
});
|
|
902
|
+
if (expression instanceof ArrayLiteralAst) {
|
|
903
|
+
if (!betweenDelimiters(cursor.offset, expression.lbracket(), expression.rbracket())) return UNSUPPORTED;
|
|
904
|
+
const element = listElementAtCursor(cursor, expression);
|
|
905
|
+
return element !== void 0 || followsSeparator(cursor, ["LBracket", "Comma"]) ? classifyAttributeExpression(cursor, element, [...path, { kind: "listElement" }]) : UNSUPPORTED;
|
|
906
|
+
}
|
|
907
|
+
if (expression instanceof ObjectLiteralExprAst) {
|
|
908
|
+
const closing = expression.rbrace();
|
|
909
|
+
if (closing !== void 0 && cursor.offset >= closing.endOffset) return UNSUPPORTED;
|
|
910
|
+
const field = recordFieldAtCursor(cursor, expression);
|
|
911
|
+
return field !== void 0 ? classifyAttributeExpression(cursor, field.value(), [...path, { kind: "recordValue" }]) : UNSUPPORTED;
|
|
912
|
+
}
|
|
913
|
+
if (expression instanceof FunctionCallAst) {
|
|
914
|
+
const opening = expression.lparen();
|
|
915
|
+
if (opening !== void 0 && cursor.offset > opening.offset) {
|
|
916
|
+
const name = expression.name();
|
|
917
|
+
const identifier = name?.identifier()?.name();
|
|
918
|
+
return identifier !== void 0 && name?.isSimpleName(identifier) === true ? classifyAttributeArguments(cursor, expression, [...path, {
|
|
919
|
+
kind: "functionCall",
|
|
920
|
+
name: identifier
|
|
921
|
+
}]) : UNSUPPORTED;
|
|
922
|
+
}
|
|
923
|
+
return expression.name()?.syntax.isInside(cursor.offset) === true ? cursor.factory.value({
|
|
924
|
+
...argumentPosition(cursor, path),
|
|
925
|
+
syntax: "functionName",
|
|
926
|
+
qualifier: void 0
|
|
927
|
+
}) : UNSUPPORTED;
|
|
928
|
+
}
|
|
929
|
+
if (expression.syntax.isOutside(cursor.offset)) return UNSUPPORTED;
|
|
930
|
+
if (expression instanceof PathExprAst) return classifyQualifiedValue(cursor, expression, path);
|
|
931
|
+
return cursor.factory.value({
|
|
932
|
+
...argumentPosition(cursor, path),
|
|
933
|
+
syntax: "scalar",
|
|
934
|
+
qualifier: void 0
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
function classifyQualifiedValue(cursor, expression, path) {
|
|
938
|
+
const qualifier = [...expression.segments()].filter((segment) => segment.syntax.endOffset < cursor.replacementStartOffset);
|
|
939
|
+
if (qualifier.length > 1) return UNSUPPORTED;
|
|
940
|
+
return cursor.factory.value({
|
|
941
|
+
...argumentPosition(cursor, path),
|
|
942
|
+
syntax: "scalar",
|
|
943
|
+
qualifier: qualifier[0]?.name()
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
function isValueToken(token) {
|
|
947
|
+
return token !== void 0 && (token.kind === "Ident" || token.kind === "StringLiteral" || token.kind === "NumberLiteral");
|
|
948
|
+
}
|
|
949
|
+
function followsSeparator(cursor, kinds) {
|
|
950
|
+
return kinds.includes(cursor.preceding?.kind ?? "");
|
|
951
|
+
}
|
|
952
|
+
function classifyGenericBlockParameter(input) {
|
|
953
|
+
const node = input.at.leftBiased()?.parent;
|
|
954
|
+
const block = node?.findAncestor(castEntryBlock);
|
|
955
|
+
if (block === void 0) return;
|
|
956
|
+
if (hasUnsupportedAncestor(node)) return UNSUPPORTED;
|
|
957
|
+
if (!blockBodyContainsOffset(block, input.offset)) return UNSUPPORTED;
|
|
958
|
+
if ((node?.findAncestor(FieldDeclarationAst.cast))?.syntax.isInside(input.offset)) return UNSUPPORTED;
|
|
959
|
+
const keyword = block.keyword()?.text;
|
|
960
|
+
if (keyword === void 0 || keyword.length === 0) return UNSUPPORTED;
|
|
961
|
+
const valuePair = valuePairAtCursor(node, input.precedingToken, input.offset);
|
|
962
|
+
if (valuePair !== void 0) return classifyBlockValue(valuePair, block, keyword, input);
|
|
963
|
+
return {
|
|
964
|
+
kind: "genericBlockKey",
|
|
965
|
+
offset: input.offset,
|
|
966
|
+
blockKeyword: keyword,
|
|
967
|
+
replacementStartOffset: input.replacementStartOffset,
|
|
968
|
+
block
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
function valuePairAtCursor(node, preceding, offset) {
|
|
972
|
+
if (preceding?.kind === "Equals") return preceding.parent.findAncestor(KeyValuePairAst.cast);
|
|
973
|
+
const pair = activeKeyValuePair(node, offset);
|
|
974
|
+
return pair !== void 0 && isAfterEquals(pair, offset) ? pair : void 0;
|
|
975
|
+
}
|
|
976
|
+
function classifyBlockValue(pair, block, blockKeyword, input) {
|
|
977
|
+
const key = pair.key()?.name();
|
|
978
|
+
if (key === void 0) return UNSUPPORTED;
|
|
979
|
+
const owner = {
|
|
980
|
+
ownerKind: "blockValue",
|
|
981
|
+
block,
|
|
982
|
+
blockKeyword,
|
|
983
|
+
key
|
|
984
|
+
};
|
|
985
|
+
const anchor = input.at.leftBiased();
|
|
986
|
+
return classifyAttributeExpression({
|
|
987
|
+
...valueReplacement(input.at, input.offset),
|
|
988
|
+
preceding: anchor === void 0 ? void 0 : skipTriviaToken(anchor, "prev"),
|
|
989
|
+
factory: {
|
|
990
|
+
namedKey: (position) => ({
|
|
991
|
+
kind: "blockValueNamedKey",
|
|
992
|
+
...position,
|
|
993
|
+
...owner
|
|
994
|
+
}),
|
|
995
|
+
argumentSlot: (position) => ({
|
|
996
|
+
kind: "blockValueArgumentSlot",
|
|
997
|
+
...position,
|
|
998
|
+
...owner
|
|
999
|
+
}),
|
|
1000
|
+
value: (position) => ({
|
|
1001
|
+
kind: "blockValue",
|
|
1002
|
+
...position,
|
|
1003
|
+
...owner
|
|
1004
|
+
})
|
|
1005
|
+
}
|
|
1006
|
+
}, pair.value(), []);
|
|
1007
|
+
}
|
|
1008
|
+
function activeKeyValuePair(node, offset) {
|
|
1009
|
+
const pair = node?.findAncestor(KeyValuePairAst.cast);
|
|
1010
|
+
if (pair === void 0 || pair.syntax.isOutside(offset)) return;
|
|
1011
|
+
return pair;
|
|
1012
|
+
}
|
|
1013
|
+
function isAfterEquals(pair, offset) {
|
|
1014
|
+
const equals = pair.equals();
|
|
1015
|
+
return equals !== void 0 && offset > equals.offset;
|
|
1016
|
+
}
|
|
1017
|
+
function hasUnsupportedAncestor(node) {
|
|
1018
|
+
return node?.findAncestor(any(AttributeArgListAst.cast, FieldAttributeAst.cast, ModelAttributeAst.cast)) !== void 0;
|
|
1019
|
+
}
|
|
1020
|
+
function classifyMixinInclusion(input) {
|
|
1021
|
+
const { offset, replacementStartOffset } = input;
|
|
1022
|
+
const inclusion = input.node?.findAncestor(MixinInclusionAst.cast);
|
|
1023
|
+
if (inclusion === void 0 || inclusion.syntax.isOutside(offset)) return void 0;
|
|
1024
|
+
const name = inclusion.name();
|
|
1025
|
+
if (name?.colon() !== void 0) return void 0;
|
|
1026
|
+
const position = {
|
|
1027
|
+
kind: "mixinInclusion",
|
|
1028
|
+
offset,
|
|
1029
|
+
replacementStartOffset,
|
|
1030
|
+
inclusion
|
|
1031
|
+
};
|
|
1032
|
+
const dot = name?.dot();
|
|
1033
|
+
if (name === void 0 || dot === void 0 || offset <= dot.offset) return position;
|
|
1034
|
+
const namespace = name.namespace()?.name();
|
|
1035
|
+
return namespace === void 0 || name.isOverQualified() ? UNSUPPORTED : {
|
|
1036
|
+
...position,
|
|
1037
|
+
namespace
|
|
1038
|
+
};
|
|
1039
|
+
}
|
|
1040
|
+
/** The significant token preceding the cursor — the in-progress edit identifier
|
|
1041
|
+
* is skipped, so the result is the token the classifier anchors on. */
|
|
1042
|
+
function precedingToken(at, edit) {
|
|
1043
|
+
const start = edit !== void 0 ? edit.prevToken : at.leftBiased();
|
|
1044
|
+
return start === void 0 ? void 0 : skipTriviaToken(start, "prev");
|
|
1045
|
+
}
|
|
1046
|
+
/** The identifier token the cursor is editing, if any. */
|
|
1047
|
+
function cursorIdentifier(at, offset) {
|
|
1048
|
+
const right = at.rightBiased();
|
|
1049
|
+
if (right?.kind === "Ident" && offset < right.endOffset) return right;
|
|
1050
|
+
const left = at.leftBiased();
|
|
1051
|
+
if (left?.kind === "Ident" && left.endOffset === offset) return left;
|
|
1052
|
+
}
|
|
1053
|
+
function requiredArgumentsSnippet(signature) {
|
|
1054
|
+
return requiredArguments(signature).map((argument, index) => requiredArgumentSnippet(argument, index + 1)).join(", ");
|
|
1055
|
+
}
|
|
1056
|
+
function typeConstructorSnippet(name, descriptor, dataTypes) {
|
|
1057
|
+
const args = descriptor.kind === "typeAlias" ? [] : descriptor.args ?? [];
|
|
1058
|
+
const reference = descriptor.kind === "typeConstructor" ? descriptor.entityRefArg : void 0;
|
|
1059
|
+
const count = Math.max(args.length, (reference?.index ?? -1) + 1);
|
|
1060
|
+
const values = [];
|
|
1061
|
+
for (let index = 0; index < count; index++) {
|
|
1062
|
+
const arg = args[index];
|
|
1063
|
+
if (index === reference?.index) values.push(argSnippetPlaceholder("identifier", values.length + 1, reference.entityKind));
|
|
1064
|
+
else if (arg !== void 0 && arg.optional !== true) {
|
|
1065
|
+
const key = arg.name ?? `arg${index + 1}`;
|
|
1066
|
+
const tabStop = values.length + 1;
|
|
1067
|
+
const [tag] = arg.kind === "value" ? admittedTags(dataTypes, dataTypeId(arg.dataType)) : [];
|
|
1068
|
+
values.push(tag !== void 0 ? taggedPlaceholder(tag, tabStop, key) : argSnippetPlaceholder(arg.kind === "object" ? "record" : "identifier", tabStop, key));
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
return `${name}(${values.join(", ") || (count > 0 ? "${1:}" : "")})`;
|
|
1072
|
+
}
|
|
1073
|
+
function requiredArguments(signature) {
|
|
1074
|
+
const positional = signature.positional ?? [];
|
|
1075
|
+
const positionalKeys = new Set(positional.map((argument) => argument.key));
|
|
1076
|
+
return [...positional.flatMap((argument) => isOptionalParam(argument.type) ? [] : [{
|
|
1077
|
+
kind: "positional",
|
|
1078
|
+
argument
|
|
1079
|
+
}]), ...Object.entries(signature.named ?? {}).flatMap(([key, { type }]) => positionalKeys.has(key) || isOptionalParam(type) ? [] : [{
|
|
1080
|
+
kind: "named",
|
|
1081
|
+
key,
|
|
1082
|
+
type
|
|
1083
|
+
}])];
|
|
1084
|
+
}
|
|
1085
|
+
function requiredArgumentSnippet(argument, tabStop) {
|
|
1086
|
+
if (argument.kind === "positional") return argumentPlaceholder(argument.argument.type, tabStop, argument.argument.key);
|
|
1087
|
+
return `${argument.key}: ${argumentPlaceholder(argument.type, tabStop, argument.key)}`;
|
|
1088
|
+
}
|
|
1089
|
+
function argumentPlaceholder(type, tabStop, key) {
|
|
1090
|
+
const tag = type.kind === "dataTypeValue" ? type.tags[0] : void 0;
|
|
1091
|
+
if (tag !== void 0) return taggedPlaceholder(tag, tabStop, key);
|
|
1092
|
+
return argSnippetPlaceholder(type.kind, tabStop, key);
|
|
1093
|
+
}
|
|
1094
|
+
function taggedPlaceholder(tag, tabStop, key) {
|
|
1095
|
+
return `${tag}\`\${${tabStop.toString()}:${key}}\``;
|
|
1096
|
+
}
|
|
1097
|
+
function argSnippetPlaceholder(kind, tabStop, key) {
|
|
1098
|
+
const placeholder = `\${${tabStop.toString()}:${key}}`;
|
|
1099
|
+
if (kind === "str") return `"${placeholder}"`;
|
|
1100
|
+
if (kind === "list") return `[${placeholder}]`;
|
|
1101
|
+
if (kind === "record") return `{ ${placeholder} }`;
|
|
1102
|
+
return placeholder;
|
|
1103
|
+
}
|
|
1104
|
+
function isOptionalParam(param) {
|
|
1105
|
+
return "optional" in param && param.optional === true;
|
|
1106
|
+
}
|
|
1107
|
+
function refinesScalarType(symbol, binder) {
|
|
1108
|
+
const node = typeReferenceNode(symbol);
|
|
1109
|
+
return !symbol.isConstructor && symbol.node.typeAnnotation()?.name()?.namespace() === void 0 && node !== void 0 && binder.symbolForNode(node)?.kind === "contributedType";
|
|
1110
|
+
}
|
|
1111
|
+
function scopeCompletionItems(entries, binder, dataTypes, range, capabilities, selection) {
|
|
1112
|
+
const items = [];
|
|
1113
|
+
for (const [name, resolution] of entries) {
|
|
1114
|
+
if (selection !== void 0 && "offers" in selection) {
|
|
1115
|
+
if (!offersMixin(resolution, selection)) continue;
|
|
1116
|
+
} else if (selection !== void 0) {
|
|
1117
|
+
if (!offersEntity(resolution, selection)) continue;
|
|
1118
|
+
} else if (resolution.kind === "block" || resolution.kind === "mixin") continue;
|
|
1119
|
+
const item = {
|
|
1120
|
+
label: name,
|
|
1121
|
+
filterText: name,
|
|
1122
|
+
textEdit: {
|
|
1123
|
+
range,
|
|
1124
|
+
newText: name
|
|
1125
|
+
}
|
|
1126
|
+
};
|
|
1127
|
+
switch (resolution.kind) {
|
|
1128
|
+
case "model":
|
|
1129
|
+
item.kind = CompletionItemKind.Class;
|
|
1130
|
+
item.detail = "Model";
|
|
1131
|
+
break;
|
|
1132
|
+
case "compositeType":
|
|
1133
|
+
item.kind = CompletionItemKind.Struct;
|
|
1134
|
+
item.detail = "Composite type";
|
|
1135
|
+
break;
|
|
1136
|
+
case "namedType": {
|
|
1137
|
+
const scalar = refinesScalarType(resolution.symbol, binder);
|
|
1138
|
+
item.kind = scalar ? CompletionItemKind.Unit : CompletionItemKind.Reference;
|
|
1139
|
+
item.detail = scalar ? "Scalar type" : "Type alias";
|
|
1140
|
+
break;
|
|
1141
|
+
}
|
|
1142
|
+
case "namespace":
|
|
1143
|
+
case "contributedNamespace":
|
|
1144
|
+
item.kind = CompletionItemKind.Module;
|
|
1145
|
+
item.detail = "Namespace";
|
|
1146
|
+
item.textEdit = {
|
|
1147
|
+
range,
|
|
1148
|
+
newText: `${name}.`
|
|
1149
|
+
};
|
|
1150
|
+
if (capabilities.clientSupportsTriggerSuggestCommand === true) item.command = {
|
|
1151
|
+
title: "Suggest namespace members",
|
|
1152
|
+
command: "editor.action.triggerSuggest"
|
|
1153
|
+
};
|
|
1154
|
+
break;
|
|
1155
|
+
case "contributedType": {
|
|
1156
|
+
const descriptor = resolution.symbol.descriptor;
|
|
1157
|
+
if (descriptor.kind === "typeAlias") {
|
|
1158
|
+
item.kind = CompletionItemKind.Class;
|
|
1159
|
+
item.detail = descriptor.documentation || "Type alias";
|
|
1160
|
+
break;
|
|
1161
|
+
}
|
|
1162
|
+
const callable = descriptor.kind === "fieldPreset" || descriptor.args !== void 0 || descriptor.entityRefArg !== void 0;
|
|
1163
|
+
item.kind = callable ? CompletionItemKind.Function : CompletionItemKind.Class;
|
|
1164
|
+
if (callable) {
|
|
1165
|
+
item.textEdit = {
|
|
1166
|
+
range,
|
|
1167
|
+
newText: capabilities.clientSupportsSnippets ? typeConstructorSnippet(name, descriptor, dataTypes) : `${name}()`
|
|
1168
|
+
};
|
|
1169
|
+
if (capabilities.clientSupportsSnippets) item.insertTextFormat = InsertTextFormat.Snippet;
|
|
1170
|
+
}
|
|
1171
|
+
if (descriptor.kind === "fieldPreset") {
|
|
1172
|
+
item.detail = "Field preset";
|
|
1173
|
+
break;
|
|
1174
|
+
}
|
|
1175
|
+
item.detail = descriptor.deprecated === void 0 ? descriptor.documentation || "Configured scalar type" : `Deprecated: use ${descriptor.deprecated.replacement}.`;
|
|
1176
|
+
if (descriptor.deprecated !== void 0) item.tags = [CompletionItemTag.Deprecated];
|
|
1177
|
+
break;
|
|
1178
|
+
}
|
|
1179
|
+
case "block":
|
|
1180
|
+
item.kind = resolution.symbol.keyword === "enum" ? CompletionItemKind.Enum : CompletionItemKind.Keyword;
|
|
1181
|
+
item.detail = resolution.symbol.keyword;
|
|
1182
|
+
break;
|
|
1183
|
+
case "mixin":
|
|
1184
|
+
item.kind = CompletionItemKind.Interface;
|
|
1185
|
+
item.detail = `${resolution.symbol.keyword} mixin`;
|
|
1186
|
+
break;
|
|
1187
|
+
}
|
|
1188
|
+
items.push(item);
|
|
1189
|
+
}
|
|
1190
|
+
return items;
|
|
1191
|
+
}
|
|
1192
|
+
function offersMixin(resolution, selection) {
|
|
1193
|
+
if (resolution.kind === "mixin") return selection.offers(resolution.symbol);
|
|
1194
|
+
if (resolution.kind !== "namespace" || !selection.namespaces) return false;
|
|
1195
|
+
for (const [, member] of memberEntries(resolution)) if (member.kind === "mixin" && selection.offers(member.symbol)) return true;
|
|
1196
|
+
return false;
|
|
1197
|
+
}
|
|
1198
|
+
function offersEntity(resolution, selection) {
|
|
1199
|
+
if (isNamespaceLike(resolution)) {
|
|
1200
|
+
if (!selection.namespaces) return false;
|
|
1201
|
+
for (const [, member] of memberEntries(resolution)) if (matchesEntity(member, selection.selector)) return true;
|
|
1202
|
+
return false;
|
|
1203
|
+
}
|
|
1204
|
+
return matchesEntity(resolution, selection.selector);
|
|
1205
|
+
}
|
|
1206
|
+
function matchesEntity(resolution, selector) {
|
|
1207
|
+
const reference = entityReference(resolution);
|
|
1208
|
+
return reference !== void 0 && matchesSelector(reference, selector);
|
|
1209
|
+
}
|
|
1210
|
+
function localFieldNames(context, binder) {
|
|
1211
|
+
if (context.ownerKind === "block" || context.ownerKind === "blockValue") return [];
|
|
1212
|
+
const owner = binder.declaredSymbol(context.model.syntax);
|
|
1213
|
+
return scalarFieldNames(owner?.kind === "model" || owner?.kind === "mixin" && owner.keyword === "model" ? owner : void 0, binder);
|
|
1214
|
+
}
|
|
1215
|
+
function referencedFieldNames(context, binder) {
|
|
1216
|
+
if (context.ownerKind !== "field") return [];
|
|
1217
|
+
const field = binder.declaredSymbol(context.field.syntax);
|
|
1218
|
+
if (field?.kind !== "field") return [];
|
|
1219
|
+
const node = typeReferenceNode(field);
|
|
1220
|
+
const target = node === void 0 ? void 0 : binder.symbolForNode(node);
|
|
1221
|
+
return scalarFieldNames(target?.kind === "model" ? target.symbol : void 0, binder);
|
|
1222
|
+
}
|
|
1223
|
+
function scalarFieldNames(model, binder) {
|
|
1224
|
+
if (model === void 0) return [];
|
|
1225
|
+
return Object.values(model.fields).filter((field) => {
|
|
1226
|
+
const node = typeReferenceNode(field);
|
|
1227
|
+
const resolution = node === void 0 ? void 0 : binder.symbolForNode(node);
|
|
1228
|
+
return resolution?.kind === "namedType" ? field.node.typeAnnotation()?.isConstructor() !== true && isScalarReference(resolution.symbol, binder) : isScalarReference(field, binder);
|
|
1229
|
+
}).map((field) => field.name);
|
|
1230
|
+
}
|
|
1231
|
+
function isScalarReference(symbol, binder) {
|
|
1232
|
+
const annotation = symbol.node.typeAnnotation();
|
|
1233
|
+
const name = annotation?.name();
|
|
1234
|
+
return name !== void 0 && binder.symbolForNode(name.syntax)?.kind === "contributedType" && (annotation?.isConstructor() === true || name.namespace() === void 0);
|
|
1235
|
+
}
|
|
1236
|
+
function resolveGrammar(root, path) {
|
|
1237
|
+
let grammars = [root];
|
|
1238
|
+
for (const step of path) grammars = grammars.flatMap((grammar) => advanceGrammar(grammar, step));
|
|
1239
|
+
return grammars;
|
|
1240
|
+
}
|
|
1241
|
+
function advanceGrammar(grammar, step) {
|
|
1242
|
+
const type = "kind" in grammar ? grammar : void 0;
|
|
1243
|
+
if (type?.kind === "oneOf") return type.alternatives.flatMap((alternative) => advanceGrammar(alternative, step));
|
|
1244
|
+
switch (step.kind) {
|
|
1245
|
+
case "positionalArgument": {
|
|
1246
|
+
if ("kind" in grammar) return [];
|
|
1247
|
+
const param = grammar.positional?.[step.index]?.type;
|
|
1248
|
+
return param === void 0 ? [] : [param];
|
|
1249
|
+
}
|
|
1250
|
+
case "namedArgument": {
|
|
1251
|
+
if ("kind" in grammar) return [];
|
|
1252
|
+
const param = grammar.named?.[step.name]?.type;
|
|
1253
|
+
return param === void 0 ? [] : [param];
|
|
1254
|
+
}
|
|
1255
|
+
case "listElement": return type?.kind === "list" ? [type.of] : [];
|
|
1256
|
+
case "recordValue": return type?.kind === "record" ? [type.of] : [];
|
|
1257
|
+
case "functionCall": return type?.kind === "funcCall" && type.name === step.name ? [type.signature] : [];
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
function provideAttributeNamedKeyCompletionItems(input, root) {
|
|
1261
|
+
return orderedItems(resolveGrammar(root, input.context.path).flatMap((grammar) => "kind" in grammar ? [] : namedKeyItems(input, grammar)));
|
|
1262
|
+
}
|
|
1263
|
+
function provideAttributeArgumentSlotCompletionItems(input, root) {
|
|
1264
|
+
return orderedItems(resolveGrammar(root, input.context.path).flatMap((grammar) => {
|
|
1265
|
+
if ("kind" in grammar) return [];
|
|
1266
|
+
const param = grammar.positional?.[input.context.positionalIndex]?.type;
|
|
1267
|
+
return [...valueItems(input, param, "scalar", void 0), ...namedKeyItems(input, grammar)];
|
|
1268
|
+
}));
|
|
1269
|
+
}
|
|
1270
|
+
function provideAttributeValueCompletionItems(input, root) {
|
|
1271
|
+
return orderedItems(resolveGrammar(root, input.context.path).flatMap((grammar) => "kind" in grammar ? valueItems(input, grammar, input.context.syntax, input.context.qualifier) : []));
|
|
1272
|
+
}
|
|
1273
|
+
function namedKeyItems(input, signature) {
|
|
1274
|
+
return Object.entries(signature.named ?? {}).filter(([name]) => !input.context.existingNamedKeys.includes(name)).map(([name, param]) => {
|
|
1275
|
+
const snippet = input.clientSupportsSnippets && !input.context.hasColon;
|
|
1276
|
+
const value = snippet ? `\${1:${name}}` : "";
|
|
1277
|
+
return {
|
|
1278
|
+
...completionItem(input, name, input.context.hasColon ? name : `${name}: ${value}`, CompletionItemKind.Property, snippet, param.documentation),
|
|
1279
|
+
...!input.context.hasColon && input.clientSupportsTriggerSuggestCommand === true ? { command: {
|
|
1280
|
+
title: "Suggest argument values",
|
|
1281
|
+
command: "editor.action.triggerSuggest"
|
|
1282
|
+
} } : {}
|
|
1283
|
+
};
|
|
1284
|
+
});
|
|
1285
|
+
}
|
|
1286
|
+
function valueItems(input, type, syntax, qualifier) {
|
|
1287
|
+
if (type === void 0) return [];
|
|
1288
|
+
if (type.kind === "oneOf") return type.alternatives.flatMap((alternative) => valueItems(input, alternative, syntax, qualifier));
|
|
1289
|
+
if (type.kind === "funcCall") {
|
|
1290
|
+
const snippet = input.clientSupportsSnippets && syntax !== "functionName";
|
|
1291
|
+
const hasParameters = (type.signature.positional?.length ?? 0) > 0 || Object.keys(type.signature.named ?? {}).length > 0;
|
|
1292
|
+
const args = requiredArgumentsSnippet(type.signature) || (hasParameters ? "${1:}" : "");
|
|
1293
|
+
const text = snippet ? `${type.name}(${args})` : type.name;
|
|
1294
|
+
return [{
|
|
1295
|
+
...completionItem(input, type.name, text, CompletionItemKind.Function, snippet, type.signature.documentation),
|
|
1296
|
+
...snippet && input.clientSupportsTriggerParameterHintsCommand === true && hasParameters ? { command: {
|
|
1297
|
+
title: "Show argument hints",
|
|
1298
|
+
command: "editor.action.triggerParameterHints"
|
|
1299
|
+
} } : {}
|
|
1300
|
+
}];
|
|
1301
|
+
}
|
|
1302
|
+
if (syntax === "functionName") return [];
|
|
1303
|
+
if (qualifier !== void 0) return qualifiedItems(input, type, qualifier);
|
|
1304
|
+
if (type.kind === "taggedLiteral" || type.kind === "dataTypeValue") {
|
|
1305
|
+
const tags = type.tags.map((tag) => ({
|
|
1306
|
+
...completionItem(input, tag, input.clientSupportsSnippets ? `${tag}\`$1\`` : tag, CompletionItemKind.Value, input.clientSupportsSnippets),
|
|
1307
|
+
detail: type.documentation
|
|
1308
|
+
}));
|
|
1309
|
+
return type.kind === "dataTypeValue" ? [...scalarItems(input, type.suggestions), ...tags] : tags;
|
|
1310
|
+
}
|
|
1311
|
+
switch (type.kind) {
|
|
1312
|
+
case "identifier": return type.name === void 0 ? [] : scalarItems(input, [type.name], type.documentation);
|
|
1313
|
+
case "str": return scalarItems(input, type.value === void 0 ? [] : [JSON.stringify(type.value)]);
|
|
1314
|
+
case "num": return scalarItems(input, type.value === void 0 ? [] : [String(type.value)]);
|
|
1315
|
+
case "bool": return scalarItems(input, ["true", "false"]);
|
|
1316
|
+
case "null": return scalarItems(input, ["null"]);
|
|
1317
|
+
case "fieldRef":
|
|
1318
|
+
case "referencedFieldRef": return scalarItems(input, input.fieldNames(type.kind));
|
|
1319
|
+
case "entityRef": return entityItems(input, input.scope.entries(), {
|
|
1320
|
+
selector: type.expected,
|
|
1321
|
+
namespaces: true
|
|
1322
|
+
});
|
|
1323
|
+
case "list":
|
|
1324
|
+
case "record":
|
|
1325
|
+
case "int":
|
|
1326
|
+
case "json":
|
|
1327
|
+
case "rejecting": return [];
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
function qualifiedItems(input, type, qualifier) {
|
|
1331
|
+
if (type.kind !== "entityRef") return [];
|
|
1332
|
+
const namespace = input.scope.lookup(qualifier);
|
|
1333
|
+
if (namespace === void 0 || !isNamespaceLike(namespace)) return [];
|
|
1334
|
+
return entityItems(input, memberEntries(namespace), {
|
|
1335
|
+
selector: type.expected,
|
|
1336
|
+
namespaces: false
|
|
1337
|
+
});
|
|
1338
|
+
}
|
|
1339
|
+
function entityItems(input, entries, selection) {
|
|
1340
|
+
return scopeCompletionItems(entries, input.binder, EMPTY_DATA_TYPES, {
|
|
1341
|
+
start: input.sourceFile.positionAt(input.context.replacementStartOffset),
|
|
1342
|
+
end: input.sourceFile.positionAt(input.context.replacementEndOffset)
|
|
1343
|
+
}, input, selection);
|
|
1344
|
+
}
|
|
1345
|
+
function scalarItems(input, labels, documentation) {
|
|
1346
|
+
return labels.map((label) => completionItem(input, label, label, CompletionItemKind.Value, false, documentation));
|
|
1347
|
+
}
|
|
1348
|
+
function completionItem(input, label, newText, kind, snippet = false, documentation) {
|
|
1349
|
+
return {
|
|
1350
|
+
label,
|
|
1351
|
+
kind,
|
|
1352
|
+
detail: documentation ?? (kind === CompletionItemKind.Property ? "Attribute argument" : "PSL argument value"),
|
|
1353
|
+
filterText: label,
|
|
1354
|
+
textEdit: {
|
|
1355
|
+
range: {
|
|
1356
|
+
start: input.sourceFile.positionAt(input.context.replacementStartOffset),
|
|
1357
|
+
end: input.sourceFile.positionAt(input.context.replacementEndOffset)
|
|
1358
|
+
},
|
|
1359
|
+
newText
|
|
1360
|
+
},
|
|
1361
|
+
...snippet ? { insertTextFormat: InsertTextFormat.Snippet } : {}
|
|
1362
|
+
};
|
|
1363
|
+
}
|
|
1364
|
+
function orderedItems(items) {
|
|
1365
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1366
|
+
return items.filter((item) => {
|
|
1367
|
+
const key = JSON.stringify([
|
|
1368
|
+
item.label,
|
|
1369
|
+
item.textEdit,
|
|
1370
|
+
item.insertTextFormat
|
|
1371
|
+
]);
|
|
1372
|
+
if (seen.has(key)) return false;
|
|
1373
|
+
seen.add(key);
|
|
1374
|
+
return true;
|
|
1375
|
+
}).map((item, index) => ({
|
|
1376
|
+
...item,
|
|
1377
|
+
sortText: index.toString().padStart(4, "0")
|
|
1378
|
+
}));
|
|
1379
|
+
}
|
|
1380
|
+
const declarationKeywordCategoryOrder = {
|
|
1381
|
+
native: 0,
|
|
1382
|
+
genericBlock: 1
|
|
1383
|
+
};
|
|
1384
|
+
const nameSnippetPlaceholder = "${1:Name}";
|
|
1385
|
+
const namespaceSnippetPlaceholder = "${1:name}";
|
|
1386
|
+
const fieldsBodySnippet = "${0:// Fields}";
|
|
1387
|
+
const blockBodySnippet = "${0:// Block keys and attributes}";
|
|
1388
|
+
const keywordsWithoutMixins = /* @__PURE__ */ new Set(["namespace", "types"]);
|
|
1389
|
+
const namespaceNativeDeclarationKeywords = [nativeDeclarationKeyword("model", "model ", `model ${nameSnippetPlaceholder} {\n ${fieldsBodySnippet}\n}`, "Defines a data model."), nativeDeclarationKeyword("type", "type ", `type ${nameSnippetPlaceholder} {\n ${fieldsBodySnippet}\n}`, "Defines a reusable composite type.")];
|
|
1390
|
+
const documentNativeDeclarationKeywords = [
|
|
1391
|
+
...namespaceNativeDeclarationKeywords,
|
|
1392
|
+
nativeDeclarationKeyword("types", "types ", "types {\n ${0:// Type aliases}\n}", "Defines reusable type aliases."),
|
|
1393
|
+
nativeDeclarationKeyword("namespace", "namespace ", `namespace ${namespaceSnippetPlaceholder} {\n \${0:// Models and types}\n}`, "Groups declarations belonging to the same database schema or database.")
|
|
1394
|
+
];
|
|
1395
|
+
function providePslCompletionItems(input) {
|
|
1396
|
+
const { context } = input;
|
|
1397
|
+
switch (context.kind) {
|
|
1398
|
+
case "unsupported": return [];
|
|
1399
|
+
case "spaceMember": return [];
|
|
1400
|
+
case "fieldAttributeName":
|
|
1401
|
+
case "modelAttributeName":
|
|
1402
|
+
case "blockAttributeName": return provideAttributeNameCompletionItems(context, input.sourceFile, input.candidates, input.clientSupportsSnippets, input.clientSupportsTriggerParameterHintsCommand === true);
|
|
1403
|
+
case "fieldAttributeNamedKey":
|
|
1404
|
+
case "modelAttributeNamedKey":
|
|
1405
|
+
case "blockAttributeNamedKey":
|
|
1406
|
+
case "blockValueNamedKey": {
|
|
1407
|
+
const root = argumentRootGrammar(context, input.candidates);
|
|
1408
|
+
return root === void 0 ? [] : provideAttributeNamedKeyCompletionItems({
|
|
1409
|
+
context,
|
|
1410
|
+
sourceFile: input.sourceFile,
|
|
1411
|
+
clientSupportsSnippets: input.clientSupportsSnippets,
|
|
1412
|
+
clientSupportsTriggerSuggestCommand: input.clientSupportsTriggerSuggestCommand === true
|
|
1413
|
+
}, root);
|
|
1414
|
+
}
|
|
1415
|
+
case "fieldAttributeArgumentSlot":
|
|
1416
|
+
case "modelAttributeArgumentSlot":
|
|
1417
|
+
case "blockAttributeArgumentSlot":
|
|
1418
|
+
case "blockValueArgumentSlot": {
|
|
1419
|
+
const root = argumentRootGrammar(context, input.candidates);
|
|
1420
|
+
return root === void 0 ? [] : provideAttributeArgumentSlotCompletionItems({
|
|
1421
|
+
context,
|
|
1422
|
+
binder: input.candidates.binder,
|
|
1423
|
+
scope: input.candidates.binder.scopeAt(ownerSyntax(context)),
|
|
1424
|
+
sourceFile: input.sourceFile,
|
|
1425
|
+
clientSupportsSnippets: input.clientSupportsSnippets,
|
|
1426
|
+
clientSupportsTriggerSuggestCommand: input.clientSupportsTriggerSuggestCommand === true,
|
|
1427
|
+
clientSupportsTriggerParameterHintsCommand: input.clientSupportsTriggerParameterHintsCommand === true,
|
|
1428
|
+
fieldNames: (kind) => kind === "fieldRef" ? localFieldNames(context, input.candidates.binder) : referencedFieldNames(context, input.candidates.binder)
|
|
1429
|
+
}, root);
|
|
1430
|
+
}
|
|
1431
|
+
case "fieldAttributeValue":
|
|
1432
|
+
case "modelAttributeValue":
|
|
1433
|
+
case "blockAttributeValue":
|
|
1434
|
+
case "blockValue": {
|
|
1435
|
+
const root = argumentRootGrammar(context, input.candidates);
|
|
1436
|
+
return root === void 0 ? [] : provideAttributeValueCompletionItems({
|
|
1437
|
+
context,
|
|
1438
|
+
binder: input.candidates.binder,
|
|
1439
|
+
scope: input.candidates.binder.scopeAt(ownerSyntax(context)),
|
|
1440
|
+
sourceFile: input.sourceFile,
|
|
1441
|
+
clientSupportsSnippets: input.clientSupportsSnippets,
|
|
1442
|
+
clientSupportsTriggerSuggestCommand: input.clientSupportsTriggerSuggestCommand === true,
|
|
1443
|
+
clientSupportsTriggerParameterHintsCommand: input.clientSupportsTriggerParameterHintsCommand === true,
|
|
1444
|
+
fieldNames: (kind) => kind === "fieldRef" ? localFieldNames(context, input.candidates.binder) : referencedFieldNames(context, input.candidates.binder)
|
|
1445
|
+
}, root);
|
|
1446
|
+
}
|
|
1447
|
+
case "declarationKeyword": return provideDeclarationKeywordCompletionItems(context, input.sourceFile, input.candidates, input.clientSupportsSnippets);
|
|
1448
|
+
case "genericBlockKey": return provideGenericBlockKeyCompletionItems(context, input.sourceFile, input.candidates, {
|
|
1449
|
+
clientSupportsSnippets: input.clientSupportsSnippets,
|
|
1450
|
+
clientSupportsTriggerSuggestCommand: input.clientSupportsTriggerSuggestCommand === true
|
|
1451
|
+
});
|
|
1452
|
+
case "mixinInclusion": return provideMixinInclusionCompletionItems(context, input.sourceFile, input.candidates, input);
|
|
1453
|
+
case "modelType": return provideModelTypeCompletionItems(context, input.sourceFile, input.candidates, input);
|
|
1454
|
+
case "namespaceMember": return provideNamespaceMemberCompletionItems(context, input.sourceFile, input.candidates, input);
|
|
1455
|
+
}
|
|
1456
|
+
}
|
|
1457
|
+
function ownerSyntax(owner) {
|
|
1458
|
+
switch (owner.ownerKind) {
|
|
1459
|
+
case "field": return owner.field.syntax;
|
|
1460
|
+
case "model": return owner.model.syntax;
|
|
1461
|
+
case "block":
|
|
1462
|
+
case "blockValue": return owner.block.syntax;
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
function provideAttributeNameCompletionItems(context, sourceFile, source, clientSupportsSnippets, clientSupportsTriggerParameterHintsCommand) {
|
|
1466
|
+
const names = attributeNames(context, source);
|
|
1467
|
+
const replacementRange = {
|
|
1468
|
+
start: sourceFile.positionAt(context.replacementStartOffset),
|
|
1469
|
+
end: sourceFile.positionAt(context.replacementEndOffset)
|
|
1470
|
+
};
|
|
1471
|
+
const resolveSpec = attributeSpecResolver(context, source);
|
|
1472
|
+
return names.map((name) => {
|
|
1473
|
+
const spec = resolveSpec(name);
|
|
1474
|
+
const newText = attributeNameEditText({
|
|
1475
|
+
name,
|
|
1476
|
+
spec,
|
|
1477
|
+
hasArgumentList: context.hasArgumentList,
|
|
1478
|
+
clientSupportsSnippets
|
|
1479
|
+
});
|
|
1480
|
+
return {
|
|
1481
|
+
label: name,
|
|
1482
|
+
kind: CompletionItemKind.Function,
|
|
1483
|
+
detail: spec?.documentation || "PSL attribute",
|
|
1484
|
+
sortText: name,
|
|
1485
|
+
filterText: name,
|
|
1486
|
+
textEdit: {
|
|
1487
|
+
range: replacementRange,
|
|
1488
|
+
newText
|
|
1489
|
+
},
|
|
1490
|
+
...newText !== name ? { insertTextFormat: InsertTextFormat.Snippet } : {},
|
|
1491
|
+
...newText !== name && clientSupportsTriggerParameterHintsCommand ? { command: {
|
|
1492
|
+
title: "Show argument hints",
|
|
1493
|
+
command: "editor.action.triggerParameterHints"
|
|
1494
|
+
} } : {}
|
|
1495
|
+
};
|
|
1496
|
+
});
|
|
1497
|
+
}
|
|
1498
|
+
function attributeNames(context, source) {
|
|
1499
|
+
switch (context.kind) {
|
|
1500
|
+
case "blockAttributeName": {
|
|
1501
|
+
const descriptor = findBlockDescriptor(source.pslBlockDescriptors, context.blockKeyword);
|
|
1502
|
+
return sortedUnique(Object.keys(descriptor?.attributes ?? {}));
|
|
1503
|
+
}
|
|
1504
|
+
case "fieldAttributeName":
|
|
1505
|
+
if (source.authoringContributions === void 0) return [];
|
|
1506
|
+
return sortedUnique(Object.keys(assembleAttributeSpecs(source.authoringContributions).field));
|
|
1507
|
+
case "modelAttributeName":
|
|
1508
|
+
if (source.authoringContributions === void 0) return [];
|
|
1509
|
+
return sortedUnique(Object.keys(assembleAttributeSpecs(source.authoringContributions).model));
|
|
1510
|
+
}
|
|
1511
|
+
}
|
|
1512
|
+
function attributeNameEditText(input) {
|
|
1513
|
+
if (!input.clientSupportsSnippets || input.spec === void 0 || input.hasArgumentList) return input.name;
|
|
1514
|
+
const required = requiredArgumentsSnippet(input.spec);
|
|
1515
|
+
return required.length === 0 ? input.name : `${input.name}(${required})`;
|
|
1516
|
+
}
|
|
1517
|
+
function provideDeclarationKeywordCompletionItems(context, sourceFile, source, clientSupportsSnippets) {
|
|
1518
|
+
const replacementRange = {
|
|
1519
|
+
start: sourceFile.positionAt(context.replacementStartOffset),
|
|
1520
|
+
end: sourceFile.positionAt(context.offset)
|
|
1521
|
+
};
|
|
1522
|
+
return declarationKeywordCandidates(context.scope, source).map((candidate) => ({
|
|
1523
|
+
label: candidate.label,
|
|
1524
|
+
kind: candidate.kind,
|
|
1525
|
+
detail: candidate.detail,
|
|
1526
|
+
sortText: declarationKeywordSortText(candidate),
|
|
1527
|
+
filterText: candidate.label,
|
|
1528
|
+
...clientSupportsSnippets ? { insertTextFormat: InsertTextFormat.Snippet } : {},
|
|
1529
|
+
textEdit: {
|
|
1530
|
+
range: replacementRange,
|
|
1531
|
+
newText: clientSupportsSnippets ? candidate.snippetText : candidate.insertText
|
|
1532
|
+
}
|
|
1533
|
+
}));
|
|
1534
|
+
}
|
|
1535
|
+
function declarationKeywordCandidates(scope, source) {
|
|
1536
|
+
const nativeCandidates = scope === "namespace" ? namespaceNativeDeclarationKeywords : documentNativeDeclarationKeywords;
|
|
1537
|
+
const genericBlockCandidates = genericBlockDeclarationKeywordCandidates(source.pslBlockDescriptors, source.symbolTable, source.dataTypes ?? EMPTY_DATA_TYPES);
|
|
1538
|
+
return [...nativeCandidates.flatMap((candidate) => withMixinDeclaration(candidate, fieldsBodySnippet)), ...genericBlockCandidates.flatMap((candidate) => withMixinDeclaration(candidate, blockBodySnippet))];
|
|
1539
|
+
}
|
|
1540
|
+
function withMixinDeclaration(candidate, bodySnippet) {
|
|
1541
|
+
if (keywordsWithoutMixins.has(candidate.label)) return [candidate];
|
|
1542
|
+
const label = `${candidate.label} mixin`;
|
|
1543
|
+
return [candidate, {
|
|
1544
|
+
category: candidate.category,
|
|
1545
|
+
label,
|
|
1546
|
+
insertText: `${label} `,
|
|
1547
|
+
snippetText: `${label} ${nameSnippetPlaceholder} {\n ${bodySnippet}\n}`,
|
|
1548
|
+
detail: `Declares a mixin for ${candidate.label} blocks.`,
|
|
1549
|
+
kind: candidate.kind
|
|
1550
|
+
}];
|
|
1551
|
+
}
|
|
1552
|
+
function nativeDeclarationKeyword(label, insertText, snippetText, documentation) {
|
|
1553
|
+
return {
|
|
1554
|
+
category: "native",
|
|
1555
|
+
label,
|
|
1556
|
+
insertText,
|
|
1557
|
+
snippetText,
|
|
1558
|
+
detail: documentation,
|
|
1559
|
+
kind: CompletionItemKind.Keyword
|
|
1560
|
+
};
|
|
1561
|
+
}
|
|
1562
|
+
function genericBlockDeclarationKeywordCandidates(descriptors, symbols, dataTypes) {
|
|
1563
|
+
return descriptorBlockKeywords(descriptors).map((keyword) => {
|
|
1564
|
+
const descriptor = findBlockDescriptor(descriptors, keyword);
|
|
1565
|
+
return {
|
|
1566
|
+
category: "genericBlock",
|
|
1567
|
+
label: keyword,
|
|
1568
|
+
insertText: `${keyword} `,
|
|
1569
|
+
snippetText: genericBlockSnippet(keyword, descriptor === void 0 ? void 0 : blockSpecFactoryOf(descriptor)(blockSpecContext({
|
|
1570
|
+
symbols,
|
|
1571
|
+
dataTypes
|
|
1572
|
+
}))),
|
|
1573
|
+
detail: descriptor?.documentation || "Generic block keyword",
|
|
1574
|
+
kind: CompletionItemKind.Keyword
|
|
1575
|
+
};
|
|
1576
|
+
});
|
|
1577
|
+
}
|
|
1578
|
+
function genericBlockSnippet(keyword, spec) {
|
|
1579
|
+
const lines = (spec?.mode === "struct" ? Object.entries(spec.parameters).filter(([, parameter]) => !isOptionalType(parameter.type)) : []).map(([name, parameter], index) => {
|
|
1580
|
+
const placeholder = `\${${index + 2}:${name}}`;
|
|
1581
|
+
return ` ${name} = ${parameter.type.kind === "list" ? `[${placeholder}]` : placeholder}`;
|
|
1582
|
+
});
|
|
1583
|
+
const cursor = lines.length === 0 ? blockBodySnippet : "$0";
|
|
1584
|
+
return [
|
|
1585
|
+
`${keyword} ${nameSnippetPlaceholder} {`,
|
|
1586
|
+
...lines,
|
|
1587
|
+
` ${cursor}`,
|
|
1588
|
+
"}"
|
|
1589
|
+
].join("\n");
|
|
1590
|
+
}
|
|
1591
|
+
function isOptionalType(type) {
|
|
1592
|
+
return "optional" in type && type.optional === true;
|
|
1593
|
+
}
|
|
1594
|
+
function descriptorBlockKeywords(descriptors) {
|
|
1595
|
+
const keywords = [];
|
|
1596
|
+
collectDescriptorBlockKeywords(descriptors, keywords);
|
|
1597
|
+
return sortedUnique(keywords);
|
|
1598
|
+
}
|
|
1599
|
+
function collectDescriptorBlockKeywords(descriptors, keywords) {
|
|
1600
|
+
for (const value of Object.values(descriptors)) {
|
|
1601
|
+
if (isAuthoringPslBlockDescriptor(value)) {
|
|
1602
|
+
keywords.push(value.keyword);
|
|
1603
|
+
continue;
|
|
1604
|
+
}
|
|
1605
|
+
collectDescriptorBlockKeywords(value, keywords);
|
|
1606
|
+
}
|
|
1607
|
+
}
|
|
1608
|
+
function declarationKeywordSortText(candidate) {
|
|
1609
|
+
return `${declarationKeywordCategoryOrder[candidate.category]}:${candidate.label}`;
|
|
1610
|
+
}
|
|
1611
|
+
function provideGenericBlockKeyCompletionItems(context, sourceFile, source, capabilities) {
|
|
1612
|
+
const descriptor = findBlockDescriptor(source.pslBlockDescriptors, context.blockKeyword);
|
|
1613
|
+
if (descriptor === void 0) return [];
|
|
1614
|
+
const spec = blockSpecFactoryOf(descriptor)(blockSpecContext({
|
|
1615
|
+
symbols: source.symbolTable,
|
|
1616
|
+
dataTypes: source.dataTypes ?? EMPTY_DATA_TYPES
|
|
1617
|
+
}));
|
|
1618
|
+
if (spec.mode !== "struct") return [];
|
|
1619
|
+
const existing = existingGenericBlockParameterNames(context.block, context.offset, source);
|
|
1620
|
+
const hasEquals = editedKeyHasEquals(context.block, context.offset);
|
|
1621
|
+
const replacementRange = {
|
|
1622
|
+
start: sourceFile.positionAt(context.replacementStartOffset),
|
|
1623
|
+
end: sourceFile.positionAt(context.offset)
|
|
1624
|
+
};
|
|
1625
|
+
return Object.entries(spec.parameters).filter(([parameterName]) => !existing.has(parameterName)).map(([parameterName, parameter], index) => {
|
|
1626
|
+
const snippet = !hasEquals && capabilities.clientSupportsSnippets && parameter.type.kind === "list";
|
|
1627
|
+
const newText = hasEquals ? parameterName : snippet ? `${parameterName} = [$1]` : `${parameterName} = `;
|
|
1628
|
+
return {
|
|
1629
|
+
label: parameterName,
|
|
1630
|
+
kind: CompletionItemKind.Property,
|
|
1631
|
+
detail: parameter.documentation || "Generic block parameter",
|
|
1632
|
+
sortText: genericBlockParameterSortText(index, parameterName),
|
|
1633
|
+
filterText: parameterName,
|
|
1634
|
+
textEdit: {
|
|
1635
|
+
range: replacementRange,
|
|
1636
|
+
newText
|
|
1637
|
+
},
|
|
1638
|
+
...snippet ? { insertTextFormat: InsertTextFormat.Snippet } : {},
|
|
1639
|
+
...!hasEquals && capabilities.clientSupportsTriggerSuggestCommand === true ? { command: {
|
|
1640
|
+
title: "Suggest argument values",
|
|
1641
|
+
command: "editor.action.triggerSuggest"
|
|
1642
|
+
} } : {}
|
|
1643
|
+
};
|
|
1644
|
+
});
|
|
1645
|
+
}
|
|
1646
|
+
function editedKeyHasEquals(block, cursorOffset) {
|
|
1647
|
+
for (const entry of block.entries()) if (!entry.syntax.isOutside(cursorOffset)) return entry.equals() !== void 0;
|
|
1648
|
+
return false;
|
|
1649
|
+
}
|
|
1650
|
+
function existingGenericBlockParameterNames(block, cursorOffset, source) {
|
|
1651
|
+
const names = /* @__PURE__ */ new Set();
|
|
1652
|
+
const symbol = source.binder.declaredSymbol(block.syntax);
|
|
1653
|
+
const entries = symbol?.kind === "block" || symbol?.kind === "mixin" ? symbol.entries : block.entries();
|
|
1654
|
+
for (const entry of entries) {
|
|
1655
|
+
if (!entry.syntax.isOutside(cursorOffset)) continue;
|
|
1656
|
+
const name = entry.key()?.name();
|
|
1657
|
+
if (name !== void 0) names.add(name);
|
|
1658
|
+
}
|
|
1659
|
+
return names;
|
|
1660
|
+
}
|
|
1661
|
+
function provideModelTypeCompletionItems(context, sourceFile, source, capabilities) {
|
|
1662
|
+
return scopeCompletionItems(source.binder.scopeAt(context.field.syntax).entries(), source.binder, source.dataTypes ?? EMPTY_DATA_TYPES, {
|
|
1663
|
+
start: sourceFile.positionAt(context.replacementStartOffset),
|
|
1664
|
+
end: sourceFile.positionAt(context.offset)
|
|
1665
|
+
}, capabilities);
|
|
1666
|
+
}
|
|
1667
|
+
function includingBlockKeyword(block) {
|
|
1668
|
+
if (ModelDeclarationAst.cast(block) !== void 0) return "model";
|
|
1669
|
+
if (CompositeTypeDeclarationAst.cast(block) !== void 0) return "type";
|
|
1670
|
+
return GenericBlockDeclarationAst.cast(block)?.keyword()?.text;
|
|
1671
|
+
}
|
|
1672
|
+
function includedMixins(block, except, source) {
|
|
1673
|
+
const included = /* @__PURE__ */ new Set();
|
|
1674
|
+
for (const inclusion of filterChildren(block, MixinInclusionAst.cast)) {
|
|
1675
|
+
if (inclusion.syntax === except.syntax) continue;
|
|
1676
|
+
const name = inclusion.name();
|
|
1677
|
+
const resolution = name === void 0 ? void 0 : source.binder.symbolForNode(name.syntax);
|
|
1678
|
+
if (resolution?.kind === "mixin") included.add(resolution.symbol);
|
|
1679
|
+
}
|
|
1680
|
+
return included;
|
|
1681
|
+
}
|
|
1682
|
+
function provideMixinInclusionCompletionItems(context, sourceFile, source, capabilities) {
|
|
1683
|
+
const block = context.inclusion.syntax.parent;
|
|
1684
|
+
const keyword = block === void 0 ? void 0 : includingBlockKeyword(block);
|
|
1685
|
+
if (block === void 0 || keyword === void 0) return [];
|
|
1686
|
+
const scope = source.binder.scopeAt(block);
|
|
1687
|
+
const namespaceId = context.namespace;
|
|
1688
|
+
const qualifier = namespaceId === void 0 ? void 0 : scope.lookup(namespaceId);
|
|
1689
|
+
const visible = namespaceId === void 0 ? scope.entries() : qualifier !== void 0 && isNamespaceLike(qualifier) ? memberEntries(qualifier) : [];
|
|
1690
|
+
const entries = [];
|
|
1691
|
+
for (const entry of visible) if (entry[1].kind === "mixin" || entry[1].kind === "namespace") entries.push(entry);
|
|
1692
|
+
const included = includedMixins(block, context.inclusion, source);
|
|
1693
|
+
return scopeCompletionItems(entries, source.binder, source.dataTypes ?? EMPTY_DATA_TYPES, {
|
|
1694
|
+
start: sourceFile.positionAt(context.replacementStartOffset),
|
|
1695
|
+
end: sourceFile.positionAt(context.offset)
|
|
1696
|
+
}, capabilities, {
|
|
1697
|
+
offers: (mixin) => mixin.keyword === keyword && !included.has(mixin),
|
|
1698
|
+
namespaces: namespaceId === void 0
|
|
1699
|
+
});
|
|
1700
|
+
}
|
|
1701
|
+
function provideNamespaceMemberCompletionItems(context, sourceFile, source, capabilities) {
|
|
1702
|
+
if (context.space !== void 0) return [];
|
|
1703
|
+
const qualifier = source.binder.scopeAt(context.field.syntax).lookup(context.namespace);
|
|
1704
|
+
return scopeCompletionItems(qualifier !== void 0 && isNamespaceLike(qualifier) ? memberEntries(qualifier) : [], source.binder, source.dataTypes ?? EMPTY_DATA_TYPES, {
|
|
1705
|
+
start: sourceFile.positionAt(context.replacementStartOffset),
|
|
1706
|
+
end: sourceFile.positionAt(context.offset)
|
|
1707
|
+
}, capabilities);
|
|
1708
|
+
}
|
|
1709
|
+
function sortedUnique(names) {
|
|
1710
|
+
return [...new Set(names)].sort(compareNames);
|
|
1711
|
+
}
|
|
1712
|
+
function genericBlockParameterSortText(index, label) {
|
|
1713
|
+
return `${index.toString().padStart(4, "0")}:${label}`;
|
|
1714
|
+
}
|
|
1715
|
+
function compareNames(left, right) {
|
|
1716
|
+
if (left < right) return -1;
|
|
1717
|
+
if (left > right) return 1;
|
|
1718
|
+
return 0;
|
|
1719
|
+
}
|
|
1720
|
+
function identTokenAt(root, offset) {
|
|
1721
|
+
const at = root.tokenAtOffset(offset);
|
|
1722
|
+
const left = at.leftBiased();
|
|
1723
|
+
if (left?.kind === "Ident") return left;
|
|
1724
|
+
const right = at.rightBiased();
|
|
1725
|
+
return right?.kind === "Ident" ? right : void 0;
|
|
1726
|
+
}
|
|
1727
|
+
function resolvedNodeAt(token, binder) {
|
|
1728
|
+
const found = token.parent.findAncestor((node) => {
|
|
1729
|
+
const resolution = binder.symbolForNode(node);
|
|
1730
|
+
if (resolution !== void 0) return {
|
|
1731
|
+
node,
|
|
1732
|
+
resolution
|
|
1733
|
+
};
|
|
1734
|
+
return binder.declaredSymbol(node) === void 0 ? void 0 : "declaration";
|
|
1735
|
+
});
|
|
1736
|
+
return found === "declaration" ? void 0 : found;
|
|
1737
|
+
}
|
|
1738
|
+
function pslSymbolOf(resolution) {
|
|
1739
|
+
switch (resolution.kind) {
|
|
1740
|
+
case "model":
|
|
1741
|
+
case "compositeType":
|
|
1742
|
+
case "namedType":
|
|
1743
|
+
case "block":
|
|
1744
|
+
case "mixin":
|
|
1745
|
+
case "field":
|
|
1746
|
+
case "namespace": return resolution.symbol;
|
|
1747
|
+
case "contributedType":
|
|
1748
|
+
case "contributedNamespace":
|
|
1749
|
+
case "crossSpace":
|
|
1750
|
+
case "attribute":
|
|
1751
|
+
case "parameter":
|
|
1752
|
+
case "function":
|
|
1753
|
+
case "constant":
|
|
1754
|
+
case "unresolved": return;
|
|
1755
|
+
}
|
|
1756
|
+
}
|
|
1757
|
+
function provideDefinition(input) {
|
|
1758
|
+
const token = identTokenAt(input.document.syntax, input.sourceFile.offsetAt(input.position));
|
|
1759
|
+
const reference = token === void 0 ? void 0 : resolvedNodeAt(token, input.binder);
|
|
1760
|
+
const symbol = reference === void 0 ? void 0 : pslSymbolOf(reference.resolution);
|
|
1761
|
+
if (reference === void 0 || symbol === void 0) return null;
|
|
1762
|
+
const declarations = declarationsOf(symbol);
|
|
1763
|
+
if (!input.linkSupport) return declarations.map((declaration) => {
|
|
1764
|
+
const target = input.sources.sourceFileFor(declaration.node);
|
|
1765
|
+
return {
|
|
1766
|
+
uri: target.filename,
|
|
1767
|
+
range: rangeOf(target, nameNode(declaration))
|
|
1768
|
+
};
|
|
1769
|
+
});
|
|
1770
|
+
const originSelectionRange = rangeOf(input.sourceFile, reference.node);
|
|
1771
|
+
return declarations.map((declaration) => {
|
|
1772
|
+
const target = input.sources.sourceFileFor(declaration.node);
|
|
1773
|
+
return {
|
|
1774
|
+
originSelectionRange,
|
|
1775
|
+
targetUri: target.filename,
|
|
1776
|
+
targetRange: rangeOf(target, declaration.node),
|
|
1777
|
+
targetSelectionRange: rangeOf(target, nameNode(declaration))
|
|
1778
|
+
};
|
|
1779
|
+
});
|
|
1780
|
+
}
|
|
1781
|
+
function declarationsOf(symbol) {
|
|
1782
|
+
if (symbol.kind === "namespace") return symbol.declarations.map(({ node }) => ({
|
|
1783
|
+
node: node.syntax,
|
|
1784
|
+
name: node.name()
|
|
1785
|
+
}));
|
|
1786
|
+
return [{
|
|
1787
|
+
node: symbol.node.syntax,
|
|
1788
|
+
name: symbol.node.name()
|
|
1789
|
+
}];
|
|
1790
|
+
}
|
|
1791
|
+
function nameNode(declaration) {
|
|
1792
|
+
return declaration.name?.syntax ?? declaration.node;
|
|
1793
|
+
}
|
|
1794
|
+
function rangeOf(sourceFile, node) {
|
|
1795
|
+
return {
|
|
1796
|
+
start: sourceFile.positionAt(node.offset),
|
|
1797
|
+
end: sourceFile.positionAt(node.endOffset)
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
/**
|
|
1801
|
+
* Computes folding ranges for block declarations in a PSL document.
|
|
1802
|
+
*
|
|
1803
|
+
* Block types that produce folding ranges:
|
|
1804
|
+
* - model (e.g., `model User { ... }`)
|
|
1805
|
+
* - composite type (e.g., `type Address { ... }`)
|
|
1806
|
+
* - namespace (e.g., `namespace billing { ... }`)
|
|
1807
|
+
* - generic blocks (generator, datasource, extension blocks)
|
|
1808
|
+
* - mixin declarations (e.g., `model mixin Timestamps { ... }`)
|
|
1809
|
+
* - types block (e.g., `types { ... }`)
|
|
1810
|
+
*
|
|
1811
|
+
* The range spans from the line containing `{` to the line containing `}`.
|
|
1812
|
+
*/
|
|
1813
|
+
function computeFoldingRanges(document, sources) {
|
|
1814
|
+
const ranges = [];
|
|
1815
|
+
collectFoldingRanges(document, sources, ranges);
|
|
1816
|
+
return ranges;
|
|
1817
|
+
}
|
|
1818
|
+
function collectFoldingRanges(document, sources, ranges) {
|
|
1819
|
+
for (const declaration of document.declarations()) {
|
|
1820
|
+
addFoldingRange(declaration, sources, ranges);
|
|
1821
|
+
const namespace = NamespaceDeclarationAst.cast(declaration.syntax);
|
|
1822
|
+
if (namespace !== void 0) for (const nested of namespace.declarations()) addFoldingRange(nested, sources, ranges);
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
function addFoldingRange(declaration, sources, ranges) {
|
|
1826
|
+
const lbrace = declaration.lbrace();
|
|
1827
|
+
const rbrace = declaration.rbrace();
|
|
1828
|
+
if (lbrace === void 0 || rbrace === void 0) return;
|
|
1829
|
+
const sourceFile = sources.sourceFileFor(declaration.syntax);
|
|
1830
|
+
const startLine = sourceFile.positionAt(lbrace.offset).line;
|
|
1831
|
+
const endLine = sourceFile.positionAt(rbrace.offset).line;
|
|
1832
|
+
ranges.push({
|
|
1833
|
+
startLine,
|
|
1834
|
+
endLine,
|
|
1835
|
+
kind: FoldingRangeKind.Region
|
|
1836
|
+
});
|
|
1837
|
+
}
|
|
1838
|
+
function classifyPslSignatureContext(input) {
|
|
1839
|
+
const syntax = locateAttributeSyntax(input);
|
|
1840
|
+
if (syntax === void 0) return blockValueSignatureContext(input);
|
|
1841
|
+
const attributeName = syntax.attribute.name()?.identifier()?.name();
|
|
1842
|
+
const args = syntax.attribute.argList();
|
|
1843
|
+
const position = args === void 0 ? void 0 : signatureArguments(syntax, args, []);
|
|
1844
|
+
const owner = signatureOwner(syntax.attribute);
|
|
1845
|
+
return attributeName === void 0 || position === void 0 || owner === void 0 ? void 0 : {
|
|
1846
|
+
...owner,
|
|
1847
|
+
...position,
|
|
1848
|
+
attributeName
|
|
1849
|
+
};
|
|
1850
|
+
}
|
|
1851
|
+
function blockValueSignatureContext(input) {
|
|
1852
|
+
const offset = input.sourceFile.offsetAt(input.position);
|
|
1853
|
+
const anchor = input.document.syntax.tokenAtOffset(offset).leftBiased();
|
|
1854
|
+
if (anchor === void 0 || anchor.kind === "Comment") return void 0;
|
|
1855
|
+
const preceding = skipTriviaToken(anchor, "prev");
|
|
1856
|
+
const pair = preceding?.parent.findAncestor(KeyValuePairAst.cast);
|
|
1857
|
+
const equals = pair?.equals();
|
|
1858
|
+
if (pair === void 0 || equals === void 0 || offset <= equals.offset) return void 0;
|
|
1859
|
+
const block = pair.syntax.findAncestor(castEntryBlock);
|
|
1860
|
+
const blockKeyword = block?.keyword()?.text;
|
|
1861
|
+
const key = pair.key()?.name();
|
|
1862
|
+
if (block === void 0 || blockKeyword === void 0 || key === void 0) return void 0;
|
|
1863
|
+
const position = signatureExpression({
|
|
1864
|
+
offset,
|
|
1865
|
+
preceding
|
|
1866
|
+
}, pair.value(), []);
|
|
1867
|
+
return position === void 0 ? void 0 : {
|
|
1868
|
+
ownerKind: "blockValue",
|
|
1869
|
+
block,
|
|
1870
|
+
blockKeyword,
|
|
1871
|
+
key,
|
|
1872
|
+
...position
|
|
1873
|
+
};
|
|
1874
|
+
}
|
|
1875
|
+
function signatureOwner(attribute) {
|
|
1876
|
+
if (attribute instanceof FieldAttributeAst) {
|
|
1877
|
+
const field = attribute.syntax.findAncestor(FieldDeclarationAst.cast);
|
|
1878
|
+
const model = attribute.syntax.findAncestor(castModelBlock);
|
|
1879
|
+
return field === void 0 || model === void 0 ? void 0 : {
|
|
1880
|
+
ownerKind: "field",
|
|
1881
|
+
field,
|
|
1882
|
+
model
|
|
1883
|
+
};
|
|
1884
|
+
}
|
|
1885
|
+
const block = attribute.syntax.findAncestor(castEntryBlock);
|
|
1886
|
+
if (block !== void 0) {
|
|
1887
|
+
const blockKeyword = block.keyword()?.text;
|
|
1888
|
+
return blockKeyword === void 0 || blockKeyword.length === 0 ? void 0 : {
|
|
1889
|
+
ownerKind: "block",
|
|
1890
|
+
block,
|
|
1891
|
+
blockKeyword
|
|
1892
|
+
};
|
|
1893
|
+
}
|
|
1894
|
+
const model = attribute.syntax.findAncestor(castModelBlock);
|
|
1895
|
+
return model === void 0 ? void 0 : {
|
|
1896
|
+
ownerKind: "model",
|
|
1897
|
+
model
|
|
1898
|
+
};
|
|
1899
|
+
}
|
|
1900
|
+
function signatureArguments(context, args, path) {
|
|
1901
|
+
if (!betweenDelimiters(context.offset, args.lparen(), args.rparen())) return void 0;
|
|
1902
|
+
const containing = argumentAtCursor(context, args);
|
|
1903
|
+
const next = context.preceding?.kind === "Comma" ? nonTriviaSibling(context.preceding, "next") : void 0;
|
|
1904
|
+
const following = next instanceof SyntaxNode && next.parent?.offset === args.syntax.offset ? AttributeArgAst.cast(next) : void 0;
|
|
1905
|
+
const active = containing ?? following;
|
|
1906
|
+
const { precedingPositionalCount: positionalIndex, otherNamedKeys: existingNamedKeys } = argumentSiblings(args, active, context.offset);
|
|
1907
|
+
if (active === void 0) return ["LParen", "Comma"].includes(context.preceding?.kind ?? "") ? {
|
|
1908
|
+
path,
|
|
1909
|
+
argumentSlot: {
|
|
1910
|
+
positionalIndex,
|
|
1911
|
+
existingNamedKeys
|
|
1912
|
+
}
|
|
1913
|
+
} : void 0;
|
|
1914
|
+
if (active.colon() !== void 0) {
|
|
1915
|
+
const name = active.name()?.name();
|
|
1916
|
+
if (name === void 0) return void 0;
|
|
1917
|
+
const valuePath = [...path, {
|
|
1918
|
+
kind: "namedArgument",
|
|
1919
|
+
name
|
|
1920
|
+
}];
|
|
1921
|
+
return active === containing ? signatureExpression(context, active.value(), valuePath) : {
|
|
1922
|
+
path: valuePath,
|
|
1923
|
+
argumentSlot: void 0
|
|
1924
|
+
};
|
|
1925
|
+
}
|
|
1926
|
+
const value = active.value();
|
|
1927
|
+
if (value === void 0 || value instanceof IdentifierAst && value.syntax.isInside(context.offset)) return {
|
|
1928
|
+
path,
|
|
1929
|
+
argumentSlot: {
|
|
1930
|
+
positionalIndex,
|
|
1931
|
+
existingNamedKeys
|
|
1932
|
+
}
|
|
1933
|
+
};
|
|
1934
|
+
const valuePath = [...path, {
|
|
1935
|
+
kind: "positionalArgument",
|
|
1936
|
+
index: positionalIndex
|
|
1937
|
+
}];
|
|
1938
|
+
return active === containing ? signatureExpression(context, value, valuePath) : {
|
|
1939
|
+
path: valuePath,
|
|
1940
|
+
argumentSlot: void 0
|
|
1941
|
+
};
|
|
1942
|
+
}
|
|
1943
|
+
function signatureExpression(context, expression, path) {
|
|
1944
|
+
const position = {
|
|
1945
|
+
path,
|
|
1946
|
+
argumentSlot: void 0
|
|
1947
|
+
};
|
|
1948
|
+
if (expression === void 0 || context.offset <= expression.syntax.offset || context.offset >= expression.syntax.endOffset && !recoveredContainerContainsCursor(expression, context.offset)) return position;
|
|
1949
|
+
if (expression instanceof ArrayLiteralAst) return betweenDelimiters(context.offset, expression.lbracket(), expression.rbracket()) ? signatureExpression(context, listElementAtCursor(context, expression), [...path, { kind: "listElement" }]) : void 0;
|
|
1950
|
+
if (expression instanceof ObjectLiteralExprAst) {
|
|
1951
|
+
const closing = expression.rbrace();
|
|
1952
|
+
if (closing !== void 0 && context.offset >= closing.endOffset) return void 0;
|
|
1953
|
+
const field = recordFieldAtCursor(context, expression);
|
|
1954
|
+
return field !== void 0 ? signatureExpression(context, field.value(), [...path, { kind: "recordValue" }]) : position;
|
|
1955
|
+
}
|
|
1956
|
+
if (expression instanceof FunctionCallAst) {
|
|
1957
|
+
const opening = expression.lparen();
|
|
1958
|
+
if (opening !== void 0 && context.offset > opening.offset) {
|
|
1959
|
+
const name = expression.name();
|
|
1960
|
+
const identifier = name?.identifier()?.name();
|
|
1961
|
+
return identifier !== void 0 && name?.isSimpleName(identifier) === true ? signatureArguments(context, expression, [...path, {
|
|
1962
|
+
kind: "functionCall",
|
|
1963
|
+
name: identifier
|
|
1964
|
+
}]) : void 0;
|
|
1965
|
+
}
|
|
1966
|
+
return expression.name()?.syntax.isInside(context.offset) === true ? position : void 0;
|
|
1967
|
+
}
|
|
1968
|
+
return position;
|
|
1969
|
+
}
|
|
1970
|
+
function providePslSignatureHelp(input) {
|
|
1971
|
+
const context = classifyPslSignatureContext(input);
|
|
1972
|
+
if (context === void 0) return null;
|
|
1973
|
+
const root = argumentRootGrammar(context, input.candidates);
|
|
1974
|
+
if (root === void 0) return null;
|
|
1975
|
+
return signatureHelp(context, root, input.clientSupportsLabelOffsets === true);
|
|
1976
|
+
}
|
|
1977
|
+
function rootSignatureName(owner) {
|
|
1978
|
+
switch (owner.ownerKind) {
|
|
1979
|
+
case "field": return `@${owner.attributeName}`;
|
|
1980
|
+
case "model":
|
|
1981
|
+
case "block": return `@@${owner.attributeName}`;
|
|
1982
|
+
case "blockValue": return;
|
|
1983
|
+
}
|
|
1984
|
+
}
|
|
1985
|
+
function signatureHelp(context, root, labelOffsets) {
|
|
1986
|
+
const callIndex = context.path.reduce((last, step, index) => step.kind === "functionCall" ? index : last, -1);
|
|
1987
|
+
const call = context.path[callIndex];
|
|
1988
|
+
const signaturePath = context.path.slice(0, callIndex + 1);
|
|
1989
|
+
const name = call?.kind === "functionCall" ? call.name : rootSignatureName(context);
|
|
1990
|
+
if (name === void 0) return null;
|
|
1991
|
+
const signatures = resolveGrammar(root, signaturePath).flatMap((grammar) => {
|
|
1992
|
+
if ("kind" in grammar) return [];
|
|
1993
|
+
const active = context.path[callIndex + 1];
|
|
1994
|
+
const params = resolveSignatureParameters(grammar, active?.kind === "namedArgument" ? active.name : void 0);
|
|
1995
|
+
const index = parameterIndex(context, active, params);
|
|
1996
|
+
return [{
|
|
1997
|
+
signature: renderSignature(name, grammar, params, labelOffsets),
|
|
1998
|
+
index
|
|
1999
|
+
}];
|
|
2000
|
+
});
|
|
2001
|
+
if (signatures.length === 0) return null;
|
|
2002
|
+
const matched = signatures.findIndex(({ signature, index }) => index >= 0 && index < (signature.parameters?.length ?? 0));
|
|
2003
|
+
const activeSignature = matched < 0 ? 0 : matched;
|
|
2004
|
+
const activeParameter = signatures[activeSignature]?.index;
|
|
2005
|
+
return {
|
|
2006
|
+
signatures: signatures.map(({ signature }) => signature),
|
|
2007
|
+
activeSignature,
|
|
2008
|
+
...matched >= 0 && activeParameter !== void 0 ? { activeParameter } : {}
|
|
2009
|
+
};
|
|
2010
|
+
}
|
|
2011
|
+
function parameterIndex(context, active, params) {
|
|
2012
|
+
if (active?.kind === "namedArgument") return params.findIndex((param) => param.key === active.name);
|
|
2013
|
+
if (active?.kind === "positionalArgument") return active.index;
|
|
2014
|
+
const slot = context.argumentSlot;
|
|
2015
|
+
if (slot !== void 0) return params.findIndex((param, index) => index >= slot.positionalIndex && !slot.existingNamedKeys.includes(param.key));
|
|
2016
|
+
return -1;
|
|
2017
|
+
}
|
|
2018
|
+
function resolveSignatureParameters(signature, activeName) {
|
|
2019
|
+
const positional = signature.positional ?? [];
|
|
2020
|
+
const keys = new Set(positional.map((param) => param.key));
|
|
2021
|
+
const namedAlias = activeName === void 0 ? void 0 : signature.named?.[activeName];
|
|
2022
|
+
return [...positional.map((param) => param.key === activeName && namedAlias !== void 0 ? {
|
|
2023
|
+
key: param.key,
|
|
2024
|
+
...namedAlias
|
|
2025
|
+
} : param), ...Object.entries(signature.named ?? {}).flatMap(([key, param]) => keys.has(key) ? [] : [{
|
|
2026
|
+
key,
|
|
2027
|
+
...param
|
|
2028
|
+
}])];
|
|
2029
|
+
}
|
|
2030
|
+
function namedParameterText(key, type) {
|
|
2031
|
+
return `${key}${"optional" in type && type.optional === true ? "?" : ""}: ${type.label}`;
|
|
2032
|
+
}
|
|
2033
|
+
function renderSignatureLabel(name, signature, params) {
|
|
2034
|
+
let label = `${name}(`;
|
|
2035
|
+
const parts = params.map((param, index) => {
|
|
2036
|
+
if (index > 0) label += ", ";
|
|
2037
|
+
const positional = index < (signature.positional?.length ?? 0);
|
|
2038
|
+
const optional = "optional" in param.type && param.type.optional === true;
|
|
2039
|
+
const typeLabel = optional && param.type.label.includes(" | ") ? `(${param.type.label})` : param.type.label;
|
|
2040
|
+
const text = positional ? `${typeLabel}${optional ? "?" : ""}` : namedParameterText(param.key, param.type);
|
|
2041
|
+
const start = label.length;
|
|
2042
|
+
label += text;
|
|
2043
|
+
return {
|
|
2044
|
+
param,
|
|
2045
|
+
text,
|
|
2046
|
+
start,
|
|
2047
|
+
end: label.length,
|
|
2048
|
+
positional
|
|
2049
|
+
};
|
|
2050
|
+
});
|
|
2051
|
+
return {
|
|
2052
|
+
label: `${label})`,
|
|
2053
|
+
parts
|
|
2054
|
+
};
|
|
2055
|
+
}
|
|
2056
|
+
function renderSignature(name, signature, params, labelOffsets) {
|
|
2057
|
+
const { label, parts } = renderSignatureLabel(name, signature, params);
|
|
2058
|
+
const rendered = parts.map(({ param, text, start, end, positional }) => {
|
|
2059
|
+
const documentation = positional ? `**${param.key}**\n\n${param.documentation}${signature.named?.[param.key] === void 0 ? "" : `\n\nAccepted positionally or by \`${param.key}:\`.`}` : param.documentation;
|
|
2060
|
+
return {
|
|
2061
|
+
label: positional && labelOffsets ? [start, end] : text,
|
|
2062
|
+
documentation: {
|
|
2063
|
+
kind: MarkupKind.Markdown,
|
|
2064
|
+
value: documentation
|
|
2065
|
+
}
|
|
2066
|
+
};
|
|
2067
|
+
});
|
|
2068
|
+
return {
|
|
2069
|
+
label,
|
|
2070
|
+
documentation: {
|
|
2071
|
+
kind: MarkupKind.Markdown,
|
|
2072
|
+
value: signature.documentation
|
|
2073
|
+
},
|
|
2074
|
+
parameters: rendered
|
|
2075
|
+
};
|
|
2076
|
+
}
|
|
2077
|
+
function providePslHover(input) {
|
|
2078
|
+
const offset = input.sourceFile.offsetAt(input.position);
|
|
2079
|
+
const token = identTokenAt(input.document.syntax, offset);
|
|
2080
|
+
if (token === void 0) return null;
|
|
2081
|
+
const value = hoverValueAt(input, token);
|
|
2082
|
+
if (value === void 0) return null;
|
|
2083
|
+
return {
|
|
2084
|
+
contents: {
|
|
2085
|
+
kind: MarkupKind.Markdown,
|
|
2086
|
+
value
|
|
2087
|
+
},
|
|
2088
|
+
range: {
|
|
2089
|
+
start: input.sourceFile.positionAt(token.offset),
|
|
2090
|
+
end: input.sourceFile.positionAt(token.endOffset)
|
|
2091
|
+
}
|
|
2092
|
+
};
|
|
2093
|
+
}
|
|
2094
|
+
function hoverValueAt(input, token) {
|
|
2095
|
+
const result = resolveHoverResult(input.binder, token);
|
|
2096
|
+
if (result !== void 0) return renderHoverResult(result, input.dataTypes);
|
|
2097
|
+
return blockKeywordDocumentationAt(token, input.pslBlockDescriptors);
|
|
2098
|
+
}
|
|
2099
|
+
function resolveHoverResult(binder, token) {
|
|
2100
|
+
const resolution = resolvedNodeAt(token, binder)?.resolution;
|
|
2101
|
+
switch (resolution?.kind) {
|
|
2102
|
+
case "model":
|
|
2103
|
+
case "compositeType":
|
|
2104
|
+
case "namedType":
|
|
2105
|
+
case "block":
|
|
2106
|
+
case "mixin":
|
|
2107
|
+
case "field": return {
|
|
2108
|
+
kind: "entity",
|
|
2109
|
+
symbol: resolution.symbol
|
|
2110
|
+
};
|
|
2111
|
+
case "namespace": return {
|
|
2112
|
+
kind: "namespace",
|
|
2113
|
+
symbol: resolution.symbol
|
|
2114
|
+
};
|
|
2115
|
+
case "attribute": return {
|
|
2116
|
+
kind: "attribute",
|
|
2117
|
+
symbol: resolution.symbol
|
|
2118
|
+
};
|
|
2119
|
+
case "contributedType": return {
|
|
2120
|
+
kind: "contributedType",
|
|
2121
|
+
symbol: resolution.symbol
|
|
2122
|
+
};
|
|
2123
|
+
case "parameter": return {
|
|
2124
|
+
kind: "parameter",
|
|
2125
|
+
symbol: resolution.symbol
|
|
2126
|
+
};
|
|
2127
|
+
case "function": return {
|
|
2128
|
+
kind: "function",
|
|
2129
|
+
symbol: resolution.symbol
|
|
2130
|
+
};
|
|
2131
|
+
case "constant": return {
|
|
2132
|
+
kind: "constant",
|
|
2133
|
+
symbol: resolution.symbol
|
|
2134
|
+
};
|
|
2135
|
+
default: return;
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
function renderHoverResult(result, dataTypes) {
|
|
2139
|
+
if (result.kind === "entity") return renderEntityContent(result.symbol);
|
|
2140
|
+
if (result.kind === "namespace") return renderNamespaceContent(result.symbol);
|
|
2141
|
+
if (result.kind === "attribute") return renderAttributeContent(result.symbol);
|
|
2142
|
+
if (result.kind === "contributedType") return renderContributedTypeContent(result.symbol, dataTypes);
|
|
2143
|
+
if (result.kind === "parameter") return renderParameterContent(result.symbol);
|
|
2144
|
+
if (result.kind === "function") return renderFunctionContent(result.symbol);
|
|
2145
|
+
return renderConstantContent(result.symbol);
|
|
2146
|
+
}
|
|
2147
|
+
function renderEntityContent(entity) {
|
|
2148
|
+
return withDocumentation([
|
|
2149
|
+
"```prisma",
|
|
2150
|
+
renderDeclarationLine(entity),
|
|
2151
|
+
"```"
|
|
2152
|
+
].join("\n"), entity.node.docComment());
|
|
2153
|
+
}
|
|
2154
|
+
function renderNamespaceContent(namespace) {
|
|
2155
|
+
return [
|
|
2156
|
+
"```prisma",
|
|
2157
|
+
`namespace ${namespace.name}`,
|
|
2158
|
+
"```"
|
|
2159
|
+
].join("\n");
|
|
2160
|
+
}
|
|
2161
|
+
function renderAttributeContent(symbol) {
|
|
2162
|
+
const name = `${symbol.level === "field" ? "@" : "@@"}${symbol.name}`;
|
|
2163
|
+
const params = resolveSignatureParameters(symbol.spec, void 0);
|
|
2164
|
+
const { label } = renderSignatureLabel(name, symbol.spec, params);
|
|
2165
|
+
return withDocumentation([
|
|
2166
|
+
"```prisma",
|
|
2167
|
+
label,
|
|
2168
|
+
"```"
|
|
2169
|
+
].join("\n"), symbol.spec.documentation);
|
|
2170
|
+
}
|
|
2171
|
+
function renderContributedTypeContent(symbol, dataTypes) {
|
|
2172
|
+
return withDocumentation([
|
|
2173
|
+
"```prisma",
|
|
2174
|
+
renderContributedTypeLabel(symbol, dataTypes),
|
|
2175
|
+
"```"
|
|
2176
|
+
].join("\n"), symbol.descriptor.kind === "fieldPreset" ? void 0 : symbol.descriptor.documentation);
|
|
2177
|
+
}
|
|
2178
|
+
function renderParameterContent(symbol) {
|
|
2179
|
+
return withDocumentation([
|
|
2180
|
+
"```prisma",
|
|
2181
|
+
namedParameterText(symbol.name, symbol.param.type),
|
|
2182
|
+
"```"
|
|
2183
|
+
].join("\n"), symbol.param.documentation);
|
|
2184
|
+
}
|
|
2185
|
+
function renderFunctionContent(symbol) {
|
|
2186
|
+
const params = resolveSignatureParameters(symbol.signature, void 0);
|
|
2187
|
+
const { label } = renderSignatureLabel(symbol.name, symbol.signature, params);
|
|
2188
|
+
return withDocumentation([
|
|
2189
|
+
"```prisma",
|
|
2190
|
+
label,
|
|
2191
|
+
"```"
|
|
2192
|
+
].join("\n"), symbol.signature.documentation);
|
|
2193
|
+
}
|
|
2194
|
+
function renderConstantContent(symbol) {
|
|
2195
|
+
return withDocumentation([
|
|
2196
|
+
"```prisma",
|
|
2197
|
+
symbol.name,
|
|
2198
|
+
"```"
|
|
2199
|
+
].join("\n"), symbol.documentation);
|
|
2200
|
+
}
|
|
2201
|
+
function withDocumentation(fence, documentation) {
|
|
2202
|
+
return documentation === void 0 || documentation === "" ? fence : `${fence}\n\n${documentation}`;
|
|
2203
|
+
}
|
|
2204
|
+
function renderContributedTypeLabel(symbol, dataTypes) {
|
|
2205
|
+
const path = symbol.path.join(".");
|
|
2206
|
+
const { descriptor } = symbol;
|
|
2207
|
+
const args = descriptor.kind === "typeAlias" ? [] : descriptor.args ?? [];
|
|
2208
|
+
if (args.length === 0) return path;
|
|
2209
|
+
return `${path}(${args.map((arg, index) => {
|
|
2210
|
+
return `${arg.name ?? `arg${index + 1}`}${arg.optional === true ? "?" : ""}: ${argumentTypeLabel(arg, dataTypes)}`;
|
|
2211
|
+
}).join(", ")})`;
|
|
2212
|
+
}
|
|
2213
|
+
function argumentTypeLabel(arg, dataTypes) {
|
|
2214
|
+
if (arg.kind === "value") return describeAdmittedForms(dataTypes, dataTypeId(arg.dataType));
|
|
2215
|
+
if (arg.kind === "number") return "number";
|
|
2216
|
+
if (arg.kind === "object") return "object";
|
|
2217
|
+
return arg.values.map((value) => `'${value}'`).join(" | ");
|
|
2218
|
+
}
|
|
2219
|
+
function blockKeywordDocumentationAt(token, pslBlockDescriptors) {
|
|
2220
|
+
const declaration = GenericBlockDeclarationAst.cast(token.parent) ?? MixinDeclarationAst.cast(token.parent);
|
|
2221
|
+
if (declaration === void 0 || declaration.keyword()?.offset !== token.offset) return void 0;
|
|
2222
|
+
return findBlockDescriptor(pslBlockDescriptors, token.text)?.documentation;
|
|
2223
|
+
}
|
|
2224
|
+
function renderDeclarationLine(entity) {
|
|
2225
|
+
if (entity.kind === "block") return `${entity.keyword} ${entity.name}`;
|
|
2226
|
+
if (entity.kind === "mixin") return `${entity.keyword} mixin ${entity.name}`;
|
|
2227
|
+
if (entity.kind === "field" || entity.kind === "namedType") return collapseWhitespace(printSyntaxWithoutComments(entity.node.syntax));
|
|
2228
|
+
return `${entity.node.keyword()?.text ?? ""} ${entity.name}`;
|
|
2229
|
+
}
|
|
2230
|
+
function printSyntaxWithoutComments(node) {
|
|
2231
|
+
let text = "";
|
|
2232
|
+
for (const token of node.tokens()) {
|
|
2233
|
+
if (token.kind === "Comment") continue;
|
|
2234
|
+
text += token.text;
|
|
2235
|
+
}
|
|
2236
|
+
return text;
|
|
2237
|
+
}
|
|
2238
|
+
function collapseWhitespace(text) {
|
|
2239
|
+
return text.replace(/\s+/g, " ").trim();
|
|
2240
|
+
}
|
|
2241
|
+
function binderContextFromStack(stack) {
|
|
2242
|
+
return {
|
|
2243
|
+
authoringContributions: stack.authoringContributions ?? {
|
|
2244
|
+
field: {},
|
|
2245
|
+
type: {},
|
|
2246
|
+
entityTypes: {},
|
|
2247
|
+
pslBlockDescriptors: stack.pslBlockDescriptors,
|
|
2248
|
+
modelAttributes: {},
|
|
2249
|
+
attributeSpecs: {
|
|
2250
|
+
model: {},
|
|
2251
|
+
field: {}
|
|
2252
|
+
},
|
|
2253
|
+
dataTypes: {}
|
|
2254
|
+
},
|
|
2255
|
+
controlMutationDefaults: { defaultFunctionRegistry: stack.controlMutationDefaults?.defaultFunctionRegistry ?? /* @__PURE__ */ new Map() },
|
|
2256
|
+
generatorFunctions: stack.generatorFunctions,
|
|
2257
|
+
dataTypes: stack.dataTypes ?? EMPTY_DATA_TYPES,
|
|
2258
|
+
...stack.pslDiagnostics === void 0 ? {} : { pslDiagnostics: stack.pslDiagnostics }
|
|
2259
|
+
};
|
|
2260
|
+
}
|
|
2261
|
+
function schemaInputIdentities(inputs) {
|
|
2262
|
+
return new Set(Array.from(inputs.uris(), canonicalFileIdentity));
|
|
2263
|
+
}
|
|
2264
|
+
var ProjectArtifacts = class {
|
|
2265
|
+
#options;
|
|
2266
|
+
#readSnapshot;
|
|
2267
|
+
#interpretation;
|
|
2268
|
+
#parserOptions;
|
|
2269
|
+
#snapshotsWithProjectOptions = /* @__PURE__ */ new WeakMap();
|
|
2270
|
+
#inputs;
|
|
2271
|
+
#documents = /* @__PURE__ */ new Map();
|
|
2272
|
+
#symbolTableResult;
|
|
2273
|
+
#binderResult;
|
|
2274
|
+
#sources;
|
|
2275
|
+
#interpretMemo;
|
|
2276
|
+
constructor(options) {
|
|
2277
|
+
this.#options = options;
|
|
2278
|
+
this.#readSnapshot = options.readSnapshot;
|
|
2279
|
+
this.#interpretation = options.interpretation;
|
|
2280
|
+
this.#parserOptions = options.parserOptions;
|
|
2281
|
+
this.#inputs = options.inputs;
|
|
2282
|
+
}
|
|
2283
|
+
get sources() {
|
|
2284
|
+
this.#sources ??= new PslSources(Array.from(this.#documents.values(), (snapshot) => [snapshot.parse().document.syntax, snapshot.sourceFile]));
|
|
2285
|
+
return this.#sources;
|
|
2286
|
+
}
|
|
2287
|
+
document = (uri) => this.#readDocument(uri);
|
|
2288
|
+
documents = () => {
|
|
2289
|
+
const snapshots = [];
|
|
2290
|
+
for (const uri of this.#inputs.uris()) {
|
|
2291
|
+
const snapshot = this.#readDocument(uri);
|
|
2292
|
+
if (snapshot !== void 0) snapshots.push(snapshot);
|
|
2293
|
+
}
|
|
2294
|
+
return snapshots;
|
|
2295
|
+
};
|
|
2296
|
+
diagnostics = (uri, projectSymbolDiagnostics) => {
|
|
2297
|
+
const snapshot = this.#readDocument(uri);
|
|
2298
|
+
if (snapshot === void 0) return [];
|
|
2299
|
+
const symbolDiagnostics = (projectSymbolDiagnostics ?? this.symbolDiagnostics()).filter((diagnostic) => diagnostic.filename === snapshot.uri);
|
|
2300
|
+
const binderDiagnostics = this.#binderDiagnostics().filter((diagnostic) => diagnostic.filename === snapshot.uri);
|
|
2301
|
+
return [
|
|
2302
|
+
...mapParseDiagnostics(snapshot.parse().diagnostics),
|
|
2303
|
+
...mapParseDiagnostics(symbolDiagnostics),
|
|
2304
|
+
...mapParseDiagnostics(binderDiagnostics),
|
|
2305
|
+
...this.#interpretDiagnostics(snapshot.uri)
|
|
2306
|
+
];
|
|
2307
|
+
};
|
|
2308
|
+
symbolTable = () => this.#readSymbolTable();
|
|
2309
|
+
symbolDiagnostics = () => this.#readSymbolTableResult().diagnostics;
|
|
2310
|
+
binder = () => this.#readBinderResult().binder;
|
|
2311
|
+
#readBinderResult() {
|
|
2312
|
+
if (this.#binderResult !== void 0) return this.#binderResult;
|
|
2313
|
+
const symbolTable = (this.#symbolTableResult ?? this.#readSymbolTableResult()).symbolTable;
|
|
2314
|
+
this.#binderResult = createBinder({
|
|
2315
|
+
symbolTable,
|
|
2316
|
+
sources: this.sources,
|
|
2317
|
+
context: this.#interpretation?.context ?? binderContextFromStack(this.#options.controlStack)
|
|
2318
|
+
});
|
|
2319
|
+
return this.#binderResult;
|
|
2320
|
+
}
|
|
2321
|
+
documentChanged = (uri) => this.#drop(uri);
|
|
2322
|
+
documentClosed = this.documentChanged;
|
|
2323
|
+
updateInputs = (next) => {
|
|
2324
|
+
this.#inputs = next;
|
|
2325
|
+
const validIdentities = schemaInputIdentities(next);
|
|
2326
|
+
let changed = false;
|
|
2327
|
+
for (const identity of this.#documents.keys()) if (!validIdentities.has(identity)) {
|
|
2328
|
+
this.#documents.delete(identity);
|
|
2329
|
+
changed = true;
|
|
2330
|
+
}
|
|
2331
|
+
if (changed) this.#refreshSources();
|
|
2332
|
+
};
|
|
2333
|
+
#refreshSources() {
|
|
2334
|
+
this.#sources = void 0;
|
|
2335
|
+
this.#symbolTableResult = void 0;
|
|
2336
|
+
this.#binderResult = void 0;
|
|
2337
|
+
this.#interpretMemo = void 0;
|
|
2338
|
+
}
|
|
2339
|
+
#projectInterpretDiagnostics() {
|
|
2340
|
+
if (this.#interpretation === void 0) return /* @__PURE__ */ new Map();
|
|
2341
|
+
this.#interpretMemo ??= this.#computeInterpretDistribution(this.#interpretation);
|
|
2342
|
+
return this.#interpretMemo;
|
|
2343
|
+
}
|
|
2344
|
+
#computeInterpretDistribution(activeInterpretation) {
|
|
2345
|
+
const currentSymbolTable = (this.#symbolTableResult ?? this.#readSymbolTableResult()).symbolTable;
|
|
2346
|
+
const allDocuments = Array.from(this.#documents.values(), (snapshot) => snapshot.parse().document);
|
|
2347
|
+
const warnings = [];
|
|
2348
|
+
const binderResult = this.#readBinderResult();
|
|
2349
|
+
const result = activeInterpretation.source.interpret({
|
|
2350
|
+
documents: allDocuments,
|
|
2351
|
+
sources: this.sources,
|
|
2352
|
+
symbolTable: currentSymbolTable,
|
|
2353
|
+
binder: binderResult.binder
|
|
2354
|
+
}, {
|
|
2355
|
+
...activeInterpretation.context,
|
|
2356
|
+
reportWarning: (diagnostic) => {
|
|
2357
|
+
warnings.push({
|
|
2358
|
+
...diagnostic,
|
|
2359
|
+
severity: "warning"
|
|
2360
|
+
});
|
|
2361
|
+
}
|
|
2362
|
+
});
|
|
2363
|
+
const diagnostics = [...warnings, ...result.ok ? [] : result.failure.diagnostics];
|
|
2364
|
+
if (diagnostics.length === 0) return /* @__PURE__ */ new Map();
|
|
2365
|
+
const sourceFileByFilename = /* @__PURE__ */ new Map();
|
|
2366
|
+
for (const snapshot of this.#documents.values()) sourceFileByFilename.set(snapshot.uri, snapshot.sourceFile);
|
|
2367
|
+
const bySourceId = /* @__PURE__ */ new Map();
|
|
2368
|
+
for (const diagnostic of diagnostics) {
|
|
2369
|
+
const sourceFile = sourceFileByFilename.get(diagnostic.sourceId);
|
|
2370
|
+
if (sourceFile === void 0) continue;
|
|
2371
|
+
const mapped = mapInterpreterDiagnostic(diagnostic, sourceFile);
|
|
2372
|
+
const group = bySourceId.get(diagnostic.sourceId);
|
|
2373
|
+
if (group === void 0) bySourceId.set(diagnostic.sourceId, [mapped]);
|
|
2374
|
+
else group.push(mapped);
|
|
2375
|
+
}
|
|
2376
|
+
return bySourceId;
|
|
2377
|
+
}
|
|
2378
|
+
#interpretDiagnostics(uri) {
|
|
2379
|
+
try {
|
|
2380
|
+
return this.#projectInterpretDiagnostics().get(uri) ?? [];
|
|
2381
|
+
} catch (error) {
|
|
2382
|
+
if (error instanceof ResponseError && (error.code === LSPErrorCodes.RequestCancelled || error.code === LSPErrorCodes.ServerCancelled || error.code === LSPErrorCodes.ContentModified)) throw error;
|
|
2383
|
+
this.#options.onInterpretationError(uri, error);
|
|
2384
|
+
return [{
|
|
2385
|
+
range: {
|
|
2386
|
+
start: {
|
|
2387
|
+
line: 0,
|
|
2388
|
+
character: 0
|
|
2389
|
+
},
|
|
2390
|
+
end: {
|
|
2391
|
+
line: 0,
|
|
2392
|
+
character: 1
|
|
2393
|
+
}
|
|
2394
|
+
},
|
|
2395
|
+
code: "PRISMA_NEXT_INTERPRETATION_FAILED",
|
|
2396
|
+
message: "Semantic diagnostics are unavailable because of an internal error. A subsequent diagnostic request or edit will retry.",
|
|
2397
|
+
severity: ParseDiagnosticSeverity.Error
|
|
2398
|
+
}];
|
|
2399
|
+
}
|
|
2400
|
+
}
|
|
2401
|
+
#drop(uri) {
|
|
2402
|
+
if (this.#documents.delete(canonicalFileIdentity(uri))) this.#refreshSources();
|
|
2403
|
+
}
|
|
2404
|
+
#readDocument(uri) {
|
|
2405
|
+
const identity = canonicalFileIdentity(uri);
|
|
2406
|
+
const readSnapshot = this.#readSnapshot;
|
|
2407
|
+
const stored = readSnapshot(uri);
|
|
2408
|
+
if (stored === void 0 || !this.#inputs.includes(uri) || !isPrismaNextSchema(stored.text)) {
|
|
2409
|
+
if (this.#documents.delete(identity)) this.#refreshSources();
|
|
2410
|
+
return;
|
|
2411
|
+
}
|
|
2412
|
+
const snapshot = this.#withProjectOptions(stored);
|
|
2413
|
+
if (this.#documents.get(identity) !== snapshot) {
|
|
2414
|
+
this.#documents.set(identity, snapshot);
|
|
2415
|
+
this.#refreshSources();
|
|
2416
|
+
}
|
|
2417
|
+
return snapshot;
|
|
2418
|
+
}
|
|
2419
|
+
#withProjectOptions(stored) {
|
|
2420
|
+
const parserOptions = this.#parserOptions;
|
|
2421
|
+
if (parserOptions === void 0) return stored;
|
|
2422
|
+
let snapshot = this.#snapshotsWithProjectOptions.get(stored);
|
|
2423
|
+
if (snapshot === void 0) {
|
|
2424
|
+
snapshot = new DocumentSnapshot(stored.uri, stored.text, parserOptions);
|
|
2425
|
+
this.#snapshotsWithProjectOptions.set(stored, snapshot);
|
|
2426
|
+
}
|
|
2427
|
+
return snapshot;
|
|
2428
|
+
}
|
|
2429
|
+
#readSymbolTableResult() {
|
|
2430
|
+
const currentDocuments = this.documents().map((snapshot) => snapshot.parse().document);
|
|
2431
|
+
this.#symbolTableResult ??= buildSymbolTable({
|
|
2432
|
+
documents: currentDocuments,
|
|
2433
|
+
sources: this.sources,
|
|
2434
|
+
defaultNamespaceId: this.#options.controlStack.defaultNamespaceId
|
|
2435
|
+
});
|
|
2436
|
+
return this.#symbolTableResult;
|
|
2437
|
+
}
|
|
2438
|
+
#readSymbolTable() {
|
|
2439
|
+
return this.#readSymbolTableResult().symbolTable;
|
|
2440
|
+
}
|
|
2441
|
+
#binderDiagnostics() {
|
|
2442
|
+
return this.#readBinderResult().diagnostics;
|
|
2443
|
+
}
|
|
2444
|
+
};
|
|
2445
|
+
function provideReferences(input) {
|
|
2446
|
+
const token = identTokenAt(input.document.syntax, input.sourceFile.offsetAt(input.position));
|
|
2447
|
+
const resolved = token === void 0 ? void 0 : resolvedNodeAt(token, input.binder);
|
|
2448
|
+
const symbol = resolved === void 0 ? void 0 : pslSymbolOf(resolved.resolution);
|
|
2449
|
+
if (symbol === void 0) return [];
|
|
2450
|
+
const declarationName = symbol.kind === "namespace" ? void 0 : symbol.node.name()?.syntax;
|
|
2451
|
+
const locations = [];
|
|
2452
|
+
for (const { document, sourceFile } of input.documents) for (const offset of occurrencesOf(symbol.name, sourceFile.text)) {
|
|
2453
|
+
const candidate = document.syntax.tokenAtOffset(offset).rightBiased();
|
|
2454
|
+
if (candidate === void 0) continue;
|
|
2455
|
+
const usage = resolvedNodeAt(candidate, input.binder);
|
|
2456
|
+
if (usage === void 0 || pslSymbolOf(usage.resolution) !== symbol) continue;
|
|
2457
|
+
if (!input.includeDeclaration && usage.node === declarationName) continue;
|
|
2458
|
+
locations.push({
|
|
2459
|
+
uri: sourceFile.filename,
|
|
2460
|
+
range: {
|
|
2461
|
+
start: sourceFile.positionAt(candidate.offset),
|
|
2462
|
+
end: sourceFile.positionAt(candidate.endOffset)
|
|
2463
|
+
}
|
|
2464
|
+
});
|
|
2465
|
+
}
|
|
2466
|
+
return locations;
|
|
2467
|
+
}
|
|
2468
|
+
function* occurrencesOf(name, text) {
|
|
2469
|
+
if (name.length === 0) return;
|
|
2470
|
+
for (let offset = text.indexOf(name); offset >= 0; offset = text.indexOf(name, offset + name.length)) yield offset;
|
|
2471
|
+
}
|
|
2472
|
+
function providePrepareRename(input) {
|
|
2473
|
+
const { sourceFile } = input;
|
|
2474
|
+
const token = identTokenAt(input.document.syntax, sourceFile.offsetAt(input.position));
|
|
2475
|
+
if (token === void 0) return null;
|
|
2476
|
+
if (renamedSymbol(input) === input.symbolTable.defaultNamespace) return null;
|
|
2477
|
+
if (provideReferences({
|
|
2478
|
+
...input,
|
|
2479
|
+
includeDeclaration: true
|
|
2480
|
+
}).length === 0) return null;
|
|
2481
|
+
return {
|
|
2482
|
+
range: {
|
|
2483
|
+
start: sourceFile.positionAt(token.offset),
|
|
2484
|
+
end: sourceFile.positionAt(token.endOffset)
|
|
2485
|
+
},
|
|
2486
|
+
placeholder: token.text
|
|
2487
|
+
};
|
|
2488
|
+
}
|
|
2489
|
+
function provideRename(input) {
|
|
2490
|
+
const { newName } = input;
|
|
2491
|
+
if (!isPslIdentifier(newName)) throw new ResponseError(LSPErrorCodes.RequestFailed, `"${newName}" is not a valid PSL identifier`);
|
|
2492
|
+
if (renamedSymbol(input) === input.symbolTable.defaultNamespace) return null;
|
|
2493
|
+
const locations = provideReferences({
|
|
2494
|
+
...input,
|
|
2495
|
+
includeDeclaration: true
|
|
2496
|
+
});
|
|
2497
|
+
if (locations.length === 0) return null;
|
|
2498
|
+
const changes = {};
|
|
2499
|
+
const editsOf = (uri) => {
|
|
2500
|
+
const edits = changes[uri] ?? [];
|
|
2501
|
+
changes[uri] = edits;
|
|
2502
|
+
return edits;
|
|
2503
|
+
};
|
|
2504
|
+
for (const { uri, range } of locations) editsOf(uri).push({
|
|
2505
|
+
range,
|
|
2506
|
+
newText: newName
|
|
2507
|
+
});
|
|
2508
|
+
const insertion = mapAttributeEdit(input);
|
|
2509
|
+
if (insertion !== void 0) editsOf(insertion.uri).push(insertion.edit);
|
|
2510
|
+
return { changes };
|
|
2511
|
+
}
|
|
2512
|
+
function mapAttributeEdit(input) {
|
|
2513
|
+
const symbol = renamedSymbol(input);
|
|
2514
|
+
if (symbol === void 0 || symbol.name === input.newName) return void 0;
|
|
2515
|
+
switch (symbol.kind) {
|
|
2516
|
+
case "model": return modelTakesMap(symbol, input) ? blockMapEdit(symbol, input) : void 0;
|
|
2517
|
+
case "field": return fieldTakesMap(symbol, input) ? fieldMapEdit(symbol, input) : void 0;
|
|
2518
|
+
case "block": return blockTakesMap(symbol, input) ? blockMapEdit(symbol, input) : void 0;
|
|
2519
|
+
case "compositeType":
|
|
2520
|
+
case "namedType":
|
|
2521
|
+
case "namespace":
|
|
2522
|
+
case "mixin": return;
|
|
2523
|
+
}
|
|
2524
|
+
}
|
|
2525
|
+
function renamedSymbol(input) {
|
|
2526
|
+
const token = identTokenAt(input.document.syntax, input.sourceFile.offsetAt(input.position));
|
|
2527
|
+
const resolved = token === void 0 ? void 0 : resolvedNodeAt(token, input.binder);
|
|
2528
|
+
return resolved === void 0 ? void 0 : pslSymbolOf(resolved.resolution);
|
|
2529
|
+
}
|
|
2530
|
+
function modelTakesMap(model, source) {
|
|
2531
|
+
if (hasAttribute(model.attributes, "map")) return false;
|
|
2532
|
+
if (hasAttribute(model.attributes, "base")) return false;
|
|
2533
|
+
return attributeSpecResolver({
|
|
2534
|
+
ownerKind: "model",
|
|
2535
|
+
model: model.node
|
|
2536
|
+
}, source)("map") !== void 0;
|
|
2537
|
+
}
|
|
2538
|
+
function fieldTakesMap(field, source) {
|
|
2539
|
+
const owner = field.node.syntax.parent;
|
|
2540
|
+
const model = owner === void 0 ? void 0 : fieldOwnerWithMap(owner);
|
|
2541
|
+
if (model === void 0) return false;
|
|
2542
|
+
if (hasAttribute(field.attributes, "map")) return false;
|
|
2543
|
+
const type = typeReferenceNode(field);
|
|
2544
|
+
const typeKind = type === void 0 ? void 0 : source.binder.symbolForNode(type)?.kind;
|
|
2545
|
+
if (typeKind === "model" || typeKind === "crossSpace") return false;
|
|
2546
|
+
return attributeSpecResolver({
|
|
2547
|
+
ownerKind: "field",
|
|
2548
|
+
field: field.node,
|
|
2549
|
+
model
|
|
2550
|
+
}, source)("map") !== void 0;
|
|
2551
|
+
}
|
|
2552
|
+
function fieldOwnerWithMap(owner) {
|
|
2553
|
+
const model = ModelDeclarationAst.cast(owner);
|
|
2554
|
+
if (model !== void 0) return model;
|
|
2555
|
+
const mixin = MixinDeclarationAst.cast(owner);
|
|
2556
|
+
return mixin?.keyword()?.text === "model" ? mixin : void 0;
|
|
2557
|
+
}
|
|
2558
|
+
function blockTakesMap(block, source) {
|
|
2559
|
+
if (hasAttribute(block.attributes, "map")) return false;
|
|
2560
|
+
return findBlockDescriptor(source.pslBlockDescriptors, block.keyword)?.nameIsStorageName === true;
|
|
2561
|
+
}
|
|
2562
|
+
function hasAttribute(attributes, name) {
|
|
2563
|
+
return attributes.some((attribute) => attribute.node.name()?.isSimpleName(name) === true);
|
|
2564
|
+
}
|
|
2565
|
+
function fieldMapEdit(field, input) {
|
|
2566
|
+
const sourceFile = sourceFileOf(field.node, input);
|
|
2567
|
+
if (sourceFile === void 0) return void 0;
|
|
2568
|
+
const end = sourceFile.positionAt(field.node.syntax.endOffset);
|
|
2569
|
+
return {
|
|
2570
|
+
uri: sourceFile.filename,
|
|
2571
|
+
edit: {
|
|
2572
|
+
range: {
|
|
2573
|
+
start: end,
|
|
2574
|
+
end
|
|
2575
|
+
},
|
|
2576
|
+
newText: ` @map("${field.name}")`
|
|
2577
|
+
}
|
|
2578
|
+
};
|
|
2579
|
+
}
|
|
2580
|
+
function blockMapEdit(symbol, input) {
|
|
2581
|
+
const sourceFile = sourceFileOf(symbol.node, input);
|
|
2582
|
+
const rbrace = symbol.node.rbrace();
|
|
2583
|
+
if (sourceFile === void 0 || rbrace === void 0) return void 0;
|
|
2584
|
+
const { indentUnit, newline } = input.formatOptions;
|
|
2585
|
+
const indent = indentUnit.repeat(enclosingBlockCount(symbol.node.syntax) + 1);
|
|
2586
|
+
const before = rbrace.prevSiblingOrToken;
|
|
2587
|
+
const anchor = before instanceof SyntaxToken && before.kind === "Whitespace" ? before : rbrace;
|
|
2588
|
+
const at = sourceFile.positionAt(anchor.offset);
|
|
2589
|
+
return {
|
|
2590
|
+
uri: sourceFile.filename,
|
|
2591
|
+
edit: {
|
|
2592
|
+
range: {
|
|
2593
|
+
start: at,
|
|
2594
|
+
end: at
|
|
2595
|
+
},
|
|
2596
|
+
newText: `${newline}${indent}@@map("${symbol.name}")${newline}`
|
|
2597
|
+
}
|
|
2598
|
+
};
|
|
2599
|
+
}
|
|
2600
|
+
function enclosingBlockCount(node) {
|
|
2601
|
+
let count = 0;
|
|
2602
|
+
for (let parent = node.parent; parent?.parent !== void 0; parent = parent.parent) count++;
|
|
2603
|
+
return count;
|
|
2604
|
+
}
|
|
2605
|
+
function sourceFileOf(node, input) {
|
|
2606
|
+
const root = node.syntax.root();
|
|
2607
|
+
return input.documents.find(({ document }) => document.syntax === root)?.sourceFile;
|
|
2608
|
+
}
|
|
2609
|
+
const semanticTokenTypes = [
|
|
2610
|
+
SemanticTokenTypes.keyword,
|
|
2611
|
+
SemanticTokenTypes.namespace,
|
|
2612
|
+
SemanticTokenTypes.class,
|
|
2613
|
+
SemanticTokenTypes.struct,
|
|
2614
|
+
SemanticTokenTypes.type,
|
|
2615
|
+
SemanticTokenTypes.property,
|
|
2616
|
+
SemanticTokenTypes.decorator,
|
|
2617
|
+
SemanticTokenTypes.string,
|
|
2618
|
+
SemanticTokenTypes.number,
|
|
2619
|
+
SemanticTokenTypes.comment
|
|
2620
|
+
];
|
|
2621
|
+
const semanticTokenModifiers = [SemanticTokenModifiers.declaration, SemanticTokenModifiers.defaultLibrary];
|
|
2622
|
+
const semanticTokenModifierIndexes = {
|
|
2623
|
+
declaration: 0,
|
|
2624
|
+
defaultLibrary: 1
|
|
2625
|
+
};
|
|
2626
|
+
const semanticTokenModifierBits = {
|
|
2627
|
+
declaration: 1 << semanticTokenModifierIndexes.declaration,
|
|
2628
|
+
defaultLibrary: 1 << semanticTokenModifierIndexes.defaultLibrary
|
|
2629
|
+
};
|
|
2630
|
+
const semanticTokensLegend = {
|
|
2631
|
+
tokenTypes: [...semanticTokenTypes],
|
|
2632
|
+
tokenModifiers: [...semanticTokenModifiers]
|
|
2633
|
+
};
|
|
2634
|
+
function buildSemanticTokens(source, range) {
|
|
2635
|
+
const builder = new SemanticTokensBuilder(source.sourceFile, range);
|
|
2636
|
+
for (const token of collectSemanticTokenEvents(source)) builder.add(token);
|
|
2637
|
+
return builder.build();
|
|
2638
|
+
}
|
|
2639
|
+
function collectSemanticTokenEvents(source) {
|
|
2640
|
+
const comments = collectCommentTokens(source.document);
|
|
2641
|
+
const tokens = [];
|
|
2642
|
+
collectDeclarations(source, tokens);
|
|
2643
|
+
return mergeSourceOrderedTokens(comments, tokens);
|
|
2644
|
+
}
|
|
2645
|
+
var SemanticTokensBuilder = class {
|
|
2646
|
+
#data = [];
|
|
2647
|
+
#sourceFile;
|
|
2648
|
+
#rangeOffsets;
|
|
2649
|
+
#previousLine = 0;
|
|
2650
|
+
#previousCharacter = 0;
|
|
2651
|
+
#first = true;
|
|
2652
|
+
constructor(sourceFile, range) {
|
|
2653
|
+
this.#sourceFile = sourceFile;
|
|
2654
|
+
if (range !== void 0) {
|
|
2655
|
+
const startOffset = sourceFile.offsetAt(range.start);
|
|
2656
|
+
const endOffset = sourceFile.offsetAt(range.end);
|
|
2657
|
+
this.#rangeOffsets = {
|
|
2658
|
+
lower: Math.min(startOffset, endOffset),
|
|
2659
|
+
upper: Math.max(startOffset, endOffset)
|
|
2660
|
+
};
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
add(token) {
|
|
2664
|
+
if (!this.#intersectsRange(token.startOffset, token.endOffset)) return;
|
|
2665
|
+
if (token.splitMultiline) {
|
|
2666
|
+
this.#addMultilineSplitToken(token);
|
|
2667
|
+
return;
|
|
2668
|
+
}
|
|
2669
|
+
this.#encode(token.startOffset, token.endOffset, token.tokenTypeIndex, token.modifierBitset);
|
|
2670
|
+
}
|
|
2671
|
+
build() {
|
|
2672
|
+
return { data: this.#data };
|
|
2673
|
+
}
|
|
2674
|
+
#intersectsRange(startOffset, endOffset) {
|
|
2675
|
+
const rangeOffsets = this.#rangeOffsets;
|
|
2676
|
+
return rangeOffsets === void 0 || startOffset < rangeOffsets.upper && endOffset > rangeOffsets.lower;
|
|
2677
|
+
}
|
|
2678
|
+
#addMultilineSplitToken(token) {
|
|
2679
|
+
const start = this.#sourceFile.positionAt(token.startOffset);
|
|
2680
|
+
const end = this.#sourceFile.positionAt(token.endOffset);
|
|
2681
|
+
if (start.line === end.line) {
|
|
2682
|
+
this.#encode(token.startOffset, token.endOffset, token.tokenTypeIndex, token.modifierBitset);
|
|
2683
|
+
return;
|
|
2684
|
+
}
|
|
2685
|
+
for (let line = start.line; line <= end.line; line++) {
|
|
2686
|
+
const startOffset = line === start.line ? token.startOffset : this.#sourceFile.lineStartOffset(line);
|
|
2687
|
+
const endOffset = line === end.line ? token.endOffset : this.#sourceFile.lineEndOffset(line);
|
|
2688
|
+
if (endOffset > startOffset && this.#intersectsRange(startOffset, endOffset)) this.#encode(startOffset, endOffset, token.tokenTypeIndex, token.modifierBitset);
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
#encode(startOffset, endOffset, tokenTypeIndex, modifierBitset) {
|
|
2692
|
+
const start = this.#sourceFile.positionAt(startOffset);
|
|
2693
|
+
const deltaLine = this.#first ? start.line : start.line - this.#previousLine;
|
|
2694
|
+
const deltaStart = this.#first || deltaLine !== 0 ? start.character : start.character - this.#previousCharacter;
|
|
2695
|
+
this.#data.push(deltaLine, deltaStart, endOffset - startOffset, tokenTypeIndex, modifierBitset);
|
|
2696
|
+
this.#previousLine = start.line;
|
|
2697
|
+
this.#previousCharacter = start.character;
|
|
2698
|
+
this.#first = false;
|
|
2699
|
+
}
|
|
2700
|
+
};
|
|
2701
|
+
function collectCommentTokens(document) {
|
|
2702
|
+
const tokens = [];
|
|
2703
|
+
for (const token of document.syntax.tokens()) if (token.kind === "Comment") tokens.push(pendingTokenForToken(token, "comment"));
|
|
2704
|
+
return tokens;
|
|
2705
|
+
}
|
|
2706
|
+
function collectDeclarations(source, tokens) {
|
|
2707
|
+
for (const declaration of source.document.declarations()) collectDeclaration(declaration, source, tokens);
|
|
2708
|
+
}
|
|
2709
|
+
function collectDeclaration(declaration, source, tokens) {
|
|
2710
|
+
if (declaration instanceof ModelDeclarationAst) {
|
|
2711
|
+
addToken(declaration.keyword(), "keyword", tokens);
|
|
2712
|
+
addIdentifier(declaration.name(), "class", tokens, semanticTokenModifierBits.declaration);
|
|
2713
|
+
collectFieldBlockMembers(declaration.members(), source, tokens);
|
|
2714
|
+
return;
|
|
2715
|
+
}
|
|
2716
|
+
if (declaration instanceof CompositeTypeDeclarationAst) {
|
|
2717
|
+
addToken(declaration.keyword(), "keyword", tokens);
|
|
2718
|
+
addIdentifier(declaration.name(), "struct", tokens, semanticTokenModifierBits.declaration);
|
|
2719
|
+
collectFieldBlockMembers(declaration.members(), source, tokens);
|
|
2720
|
+
return;
|
|
2721
|
+
}
|
|
2722
|
+
if (declaration instanceof NamespaceDeclarationAst) {
|
|
2723
|
+
addToken(declaration.keyword(), "keyword", tokens);
|
|
2724
|
+
addIdentifier(declaration.name(), "namespace", tokens, semanticTokenModifierBits.declaration);
|
|
2725
|
+
for (const nested of declaration.declarations()) collectDeclaration(nested, source, tokens);
|
|
2726
|
+
return;
|
|
2727
|
+
}
|
|
2728
|
+
if (declaration instanceof TypesBlockAst) {
|
|
2729
|
+
addToken(declaration.keyword(), "keyword", tokens);
|
|
2730
|
+
for (const namedType of declaration.declarations()) collectNamedTypeDeclaration(namedType, source, tokens);
|
|
2731
|
+
return;
|
|
2732
|
+
}
|
|
2733
|
+
if (declaration instanceof MixinDeclarationAst) {
|
|
2734
|
+
addToken(declaration.keyword(), "keyword", tokens);
|
|
2735
|
+
addToken(declaration.mixinKeyword(), "keyword", tokens);
|
|
2736
|
+
addIdentifier(declaration.name(), "type", tokens, semanticTokenModifierBits.declaration);
|
|
2737
|
+
if (FIELD_BLOCK_KEYWORDS.has(declaration.keyword()?.text ?? "")) collectFieldBlockMembers(declaration.members(), source, tokens);
|
|
2738
|
+
else collectEntryBlockMembers(declaration.members(), source, tokens);
|
|
2739
|
+
return;
|
|
2740
|
+
}
|
|
2741
|
+
addToken(declaration.keyword(), "keyword", tokens);
|
|
2742
|
+
addIdentifier(declaration.name(), "type", tokens, semanticTokenModifierBits.declaration);
|
|
2743
|
+
collectEntryBlockMembers(declaration.members(), source, tokens);
|
|
2744
|
+
}
|
|
2745
|
+
const FIELD_BLOCK_KEYWORDS = /* @__PURE__ */ new Set(["model", "type"]);
|
|
2746
|
+
function collectFieldBlockMembers(members, source, tokens) {
|
|
2747
|
+
for (const member of members) if (member instanceof MixinInclusionAst) collectInclusion(member, source, tokens);
|
|
2748
|
+
else if (member instanceof FieldDeclarationAst) collectField(member, source, tokens);
|
|
2749
|
+
else if (!(member instanceof KeyValuePairAst)) collectAttribute(member, source, tokens);
|
|
2750
|
+
}
|
|
2751
|
+
function collectEntryBlockMembers(members, source, tokens) {
|
|
2752
|
+
for (const member of members) if (member instanceof MixinInclusionAst) collectInclusion(member, source, tokens);
|
|
2753
|
+
else if (member instanceof KeyValuePairAst) {
|
|
2754
|
+
addIdentifier(member.key(), "property", tokens);
|
|
2755
|
+
collectExpression(member.value(), source, tokens);
|
|
2756
|
+
} else if (!(member instanceof FieldDeclarationAst)) collectAttribute(member, source, tokens);
|
|
2757
|
+
}
|
|
2758
|
+
function collectInclusion(inclusion, source, tokens) {
|
|
2759
|
+
const name = inclusion.name();
|
|
2760
|
+
if (name === void 0) return;
|
|
2761
|
+
const plus = inclusion.plus();
|
|
2762
|
+
const segments = identifierSegments(name);
|
|
2763
|
+
for (const [index, segment] of segments.entries()) {
|
|
2764
|
+
const isName = index === segments.length - 1;
|
|
2765
|
+
const qualifier = isName ? void 0 : source.binder.symbolForNode(segment.identifier.syntax);
|
|
2766
|
+
if (!isName && qualifier?.kind !== "namespace") continue;
|
|
2767
|
+
const range = rangeForIdentifier(segment.identifier, isName ? "type" : "namespace");
|
|
2768
|
+
tokens.push(index === 0 && plus !== void 0 && plus.offset < range.startOffset ? createPendingSemanticToken(plus.offset, range.endOffset, isName ? "type" : "namespace") : range);
|
|
2769
|
+
}
|
|
2770
|
+
}
|
|
2771
|
+
function collectNamedTypeDeclaration(declaration, source, tokens) {
|
|
2772
|
+
addIdentifier(declaration.name(), "type", tokens, semanticTokenModifierBits.declaration);
|
|
2773
|
+
collectTypeAnnotation(declaration.typeAnnotation(), source, tokens);
|
|
2774
|
+
collectAttributes(declaration.attributes(), source, tokens);
|
|
2775
|
+
}
|
|
2776
|
+
function collectField(field, source, tokens) {
|
|
2777
|
+
addIdentifier(field.name(), "property", tokens, semanticTokenModifierBits.declaration);
|
|
2778
|
+
collectTypeAnnotation(field.typeAnnotation(), source, tokens);
|
|
2779
|
+
collectAttributes(field.attributes(), source, tokens);
|
|
2780
|
+
}
|
|
2781
|
+
function collectTypeAnnotation(annotation, source, tokens) {
|
|
2782
|
+
if (annotation === void 0) return;
|
|
2783
|
+
collectTypeReference(annotation.name(), source, tokens);
|
|
2784
|
+
collectAttributeArgList(annotation.argList(), source, tokens);
|
|
2785
|
+
}
|
|
2786
|
+
function collectAttributes(attributes, source, tokens) {
|
|
2787
|
+
for (const attribute of attributes) collectAttribute(attribute, source, tokens);
|
|
2788
|
+
}
|
|
2789
|
+
function collectAttribute(attribute, source, tokens) {
|
|
2790
|
+
const marker = "at" in attribute ? attribute.at() : attribute.doubleAt();
|
|
2791
|
+
collectDecoratorName(attribute.name(), marker, tokens);
|
|
2792
|
+
collectAttributeArgList(attribute.argList(), source, tokens);
|
|
2793
|
+
}
|
|
2794
|
+
function collectDecoratorName(name, marker, tokens) {
|
|
2795
|
+
if (name === void 0) return;
|
|
2796
|
+
const segments = identifierSegments(name);
|
|
2797
|
+
for (const [index, segment] of segments.entries()) tokens.push(rangeForDecoratorIdentifier(segment.identifier, index === 0 ? marker : void 0));
|
|
2798
|
+
}
|
|
2799
|
+
function collectAttributeArgList(argList, source, tokens) {
|
|
2800
|
+
if (argList === void 0) return;
|
|
2801
|
+
for (const arg of argList.args()) collectAttributeArg(arg, source, tokens);
|
|
2802
|
+
}
|
|
2803
|
+
function collectAttributeArg(arg, source, tokens) {
|
|
2804
|
+
const name = arg.name();
|
|
2805
|
+
addIdentifier(name, "property", tokens);
|
|
2806
|
+
collectExpression(arg.value(), source, tokens, expressionContextForAttributeArg(name));
|
|
2807
|
+
}
|
|
2808
|
+
function collectExpression(expression, source, tokens, context = {}) {
|
|
2809
|
+
if (expression === void 0) return;
|
|
2810
|
+
if (expression instanceof StringLiteralExprAst) {
|
|
2811
|
+
addToken(expression.token(), "string", tokens);
|
|
2812
|
+
return;
|
|
2813
|
+
}
|
|
2814
|
+
if (expression instanceof NumberLiteralExprAst) {
|
|
2815
|
+
addToken(expression.token(), "number", tokens);
|
|
2816
|
+
return;
|
|
2817
|
+
}
|
|
2818
|
+
if (expression instanceof BooleanLiteralExprAst) {
|
|
2819
|
+
addToken(expression.token(), "keyword", tokens);
|
|
2820
|
+
return;
|
|
2821
|
+
}
|
|
2822
|
+
if (expression instanceof FunctionCallAst) {
|
|
2823
|
+
const memberPath = expression.memberPath();
|
|
2824
|
+
if (memberPath === void 0) collectTypeReference(expression.name(), source, tokens);
|
|
2825
|
+
else collectMemberPath(memberPath, source, tokens);
|
|
2826
|
+
for (const arg of expression.args()) collectAttributeArg(arg, source, tokens);
|
|
2827
|
+
return;
|
|
2828
|
+
}
|
|
2829
|
+
if (expression instanceof ArrayLiteralAst) {
|
|
2830
|
+
for (const element of expression.elements()) collectExpression(element, source, tokens, context);
|
|
2831
|
+
return;
|
|
2832
|
+
}
|
|
2833
|
+
if (expression instanceof ObjectLiteralExprAst) {
|
|
2834
|
+
for (const field of expression.fields()) {
|
|
2835
|
+
addIdentifier(field.key(), "property", tokens);
|
|
2836
|
+
collectExpression(field.value(), source, tokens);
|
|
2837
|
+
}
|
|
2838
|
+
return;
|
|
2839
|
+
}
|
|
2840
|
+
if (expression instanceof TaggedLiteralExprAst) {
|
|
2841
|
+
const tag = expression.tag();
|
|
2842
|
+
addIdentifier(tag?.namespace(), "namespace", tokens);
|
|
2843
|
+
addIdentifier(tag?.identifier(), "keyword", tokens);
|
|
2844
|
+
addToken(expression.literal()?.token(), "string", tokens);
|
|
2845
|
+
return;
|
|
2846
|
+
}
|
|
2847
|
+
if (expression instanceof PathExprAst) {
|
|
2848
|
+
collectMemberPath(expression, source, tokens);
|
|
2849
|
+
return;
|
|
2850
|
+
}
|
|
2851
|
+
collectIdentifierExpression(expression, source, tokens, context);
|
|
2852
|
+
}
|
|
2853
|
+
/** A member path such as `address.city` names fields, one per segment. */
|
|
2854
|
+
function collectMemberPath(path, source, tokens) {
|
|
2855
|
+
for (const segment of path.segments()) {
|
|
2856
|
+
const resolution = source.binder.symbolForNode(segment.syntax);
|
|
2857
|
+
addIdentifier(segment, resolution?.kind === "namespace" || resolution?.kind === "contributedNamespace" ? "namespace" : "property", tokens);
|
|
2858
|
+
}
|
|
2859
|
+
}
|
|
2860
|
+
function collectIdentifierExpression(identifier, source, tokens, context) {
|
|
2861
|
+
if (identifier.name() === void 0) return;
|
|
2862
|
+
const resolution = source.binder.symbolForNode(identifier.syntax);
|
|
2863
|
+
const bareIdentifierTokenType = context.bareIdentifierTokenType;
|
|
2864
|
+
if ((resolution === void 0 || resolution.kind === "unresolved" || resolution.kind === "crossSpace") && bareIdentifierTokenType !== void 0) {
|
|
2865
|
+
tokens.push(rangeForIdentifier(identifier, bareIdentifierTokenType));
|
|
2866
|
+
return;
|
|
2867
|
+
}
|
|
2868
|
+
const classification = classifyTypeReference(resolution, source.binder);
|
|
2869
|
+
tokens.push(rangeForIdentifier(identifier, classification.tokenType, classification.modifierBitset));
|
|
2870
|
+
}
|
|
2871
|
+
function expressionContextForAttributeArg(name) {
|
|
2872
|
+
const argName = name?.name();
|
|
2873
|
+
return argName === "fields" || argName === "references" ? { bareIdentifierTokenType: "property" } : {};
|
|
2874
|
+
}
|
|
2875
|
+
function collectTypeReference(name, source, tokens) {
|
|
2876
|
+
if (name === void 0) return;
|
|
2877
|
+
const segments = identifierSegments(name);
|
|
2878
|
+
if (segments.length === 0) return;
|
|
2879
|
+
for (const segment of segments.slice(0, -1)) {
|
|
2880
|
+
const qualifier = source.binder.symbolForNode(segment.identifier.syntax);
|
|
2881
|
+
if (qualifier?.kind === "namespace" || qualifier?.kind === "contributedNamespace") tokens.push(rangeForIdentifier(segment.identifier, "namespace"));
|
|
2882
|
+
}
|
|
2883
|
+
const finalSegment = segments[segments.length - 1];
|
|
2884
|
+
if (finalSegment === void 0) return;
|
|
2885
|
+
const classification = classifyTypeReference(source.binder.symbolForNode(name.syntax), source.binder);
|
|
2886
|
+
tokens.push(rangeForIdentifier(finalSegment.identifier, classification.tokenType, classification.modifierBitset));
|
|
2887
|
+
}
|
|
2888
|
+
function classifyTypeReference(resolution, binder) {
|
|
2889
|
+
switch (resolution?.kind) {
|
|
2890
|
+
case "model": return { tokenType: "class" };
|
|
2891
|
+
case "compositeType": return { tokenType: "struct" };
|
|
2892
|
+
case "field": return { tokenType: "property" };
|
|
2893
|
+
case "contributedType": return {
|
|
2894
|
+
tokenType: "type",
|
|
2895
|
+
modifierBitset: semanticTokenModifierBits.defaultLibrary
|
|
2896
|
+
};
|
|
2897
|
+
case "namedType": return refinesScalarType(resolution.symbol, binder) ? {
|
|
2898
|
+
tokenType: "type",
|
|
2899
|
+
modifierBitset: semanticTokenModifierBits.defaultLibrary
|
|
2900
|
+
} : { tokenType: "type" };
|
|
2901
|
+
default: return { tokenType: "type" };
|
|
2902
|
+
}
|
|
2903
|
+
}
|
|
2904
|
+
function identifierSegments(name) {
|
|
2905
|
+
const segments = [];
|
|
2906
|
+
for (const identifier of name.segments()) {
|
|
2907
|
+
const text = identifier.name();
|
|
2908
|
+
if (text !== void 0) segments.push({
|
|
2909
|
+
identifier,
|
|
2910
|
+
text
|
|
2911
|
+
});
|
|
2912
|
+
}
|
|
2913
|
+
return segments;
|
|
2914
|
+
}
|
|
2915
|
+
function addIdentifier(identifier, tokenType, tokens, modifierBitset = 0) {
|
|
2916
|
+
if (identifier === void 0) return;
|
|
2917
|
+
tokens.push(rangeForIdentifier(identifier, tokenType, modifierBitset));
|
|
2918
|
+
}
|
|
2919
|
+
function addToken(token, tokenType, tokens, modifierBitset = 0) {
|
|
2920
|
+
if (token === void 0) return;
|
|
2921
|
+
tokens.push(pendingTokenForToken(token, tokenType, modifierBitset));
|
|
2922
|
+
}
|
|
2923
|
+
function rangeForIdentifier(identifier, tokenType, modifierBitset = 0) {
|
|
2924
|
+
const token = identifier.token();
|
|
2925
|
+
if (token === void 0) return createPendingSemanticToken(identifier.syntax.offset, identifier.syntax.offset, tokenType, modifierBitset);
|
|
2926
|
+
return pendingTokenForToken(token, tokenType, modifierBitset);
|
|
2927
|
+
}
|
|
2928
|
+
function rangeForDecoratorIdentifier(identifier, marker) {
|
|
2929
|
+
const range = rangeForIdentifier(identifier, "decorator");
|
|
2930
|
+
if (marker === void 0 || marker.offset >= range.startOffset) return range;
|
|
2931
|
+
return createPendingSemanticToken(marker.offset, range.endOffset, "decorator", range.modifierBitset);
|
|
2932
|
+
}
|
|
2933
|
+
function pendingTokenForToken(token, tokenType, modifierBitset = 0) {
|
|
2934
|
+
return createPendingSemanticToken(token.offset, token.offset + token.text.length, tokenType, modifierBitset);
|
|
2935
|
+
}
|
|
2936
|
+
function mergeSourceOrderedTokens(left, right) {
|
|
2937
|
+
const result = [];
|
|
2938
|
+
let leftIndex = 0;
|
|
2939
|
+
let rightIndex = 0;
|
|
2940
|
+
while (leftIndex < left.length || rightIndex < right.length) {
|
|
2941
|
+
const leftToken = left[leftIndex];
|
|
2942
|
+
const rightToken = right[rightIndex];
|
|
2943
|
+
if (leftToken !== void 0 && (rightToken === void 0 || leftToken.startOffset <= rightToken.startOffset)) {
|
|
2944
|
+
result.push(leftToken);
|
|
2945
|
+
leftIndex++;
|
|
2946
|
+
} else if (rightToken !== void 0) {
|
|
2947
|
+
result.push(rightToken);
|
|
2948
|
+
rightIndex++;
|
|
2949
|
+
}
|
|
2950
|
+
}
|
|
2951
|
+
return result;
|
|
2952
|
+
}
|
|
2953
|
+
function createPendingSemanticToken(startOffset, endOffset, tokenType, modifierBitset = 0) {
|
|
2954
|
+
return {
|
|
2955
|
+
startOffset,
|
|
2956
|
+
endOffset,
|
|
2957
|
+
tokenTypeIndex: tokenTypeIndex(tokenType),
|
|
2958
|
+
modifierBitset,
|
|
2959
|
+
splitMultiline: tokenType === "string" || tokenType === "comment"
|
|
2960
|
+
};
|
|
2961
|
+
}
|
|
2962
|
+
function tokenTypeIndex(tokenType) {
|
|
2963
|
+
return semanticTokenTypes.indexOf(tokenType);
|
|
2964
|
+
}
|
|
2965
|
+
const CONFIG_LOAD_FAILED_CODE = "PRISMA_CONFIG_LOAD_FAILED";
|
|
2966
|
+
var Project = class {
|
|
2967
|
+
configPath;
|
|
2968
|
+
#options;
|
|
2969
|
+
#state = { status: "failed" };
|
|
2970
|
+
#membershipSequence = 0;
|
|
2971
|
+
#watcherGeneration = 0;
|
|
2972
|
+
#watcher;
|
|
2973
|
+
#reportedMembers = /* @__PURE__ */ new Set();
|
|
2974
|
+
constructor(configPath, options) {
|
|
2975
|
+
this.configPath = configPath;
|
|
2976
|
+
this.#options = options;
|
|
2977
|
+
}
|
|
2978
|
+
get artifacts() {
|
|
2979
|
+
return this.#current()?.artifacts;
|
|
2980
|
+
}
|
|
2981
|
+
async publishForDocument(uri) {
|
|
2982
|
+
const data = await this.#resolveData().catch(() => void 0);
|
|
2983
|
+
if (data === void 0) return;
|
|
2984
|
+
const member = data.inputs.includes(uri);
|
|
2985
|
+
if (!member) this.#options.unmanage(uri);
|
|
2986
|
+
if (member || this.#reportedMembers.has(normalizeFileUri(uri))) this.#publishMembers(data);
|
|
2987
|
+
}
|
|
2988
|
+
async formatDocument(uri, source) {
|
|
2989
|
+
const data = await this.#resolveMember(uri);
|
|
2990
|
+
if (data === void 0) return void 0;
|
|
2991
|
+
try {
|
|
2992
|
+
return renameLegacyDirective(format(source, data.formatter, data.parserOptions));
|
|
2993
|
+
} catch {
|
|
2994
|
+
return;
|
|
2995
|
+
}
|
|
2996
|
+
}
|
|
2997
|
+
async semanticTokens(uri, range) {
|
|
2998
|
+
const data = await this.#resolveMember(uri);
|
|
2999
|
+
const document = data?.artifacts.document(uri);
|
|
3000
|
+
if (data === void 0 || document === void 0) return { data: [] };
|
|
3001
|
+
return buildSemanticTokens({
|
|
3002
|
+
document: document.parse().document,
|
|
3003
|
+
sourceFile: document.sourceFile,
|
|
3004
|
+
binder: data.artifacts.binder()
|
|
3005
|
+
}, range);
|
|
3006
|
+
}
|
|
3007
|
+
async completions(uri, position, capabilities) {
|
|
3008
|
+
const data = await this.#resolveMember(uri);
|
|
3009
|
+
const document = data?.artifacts.document(uri);
|
|
3010
|
+
if (data === void 0 || document === void 0) return [];
|
|
3011
|
+
try {
|
|
3012
|
+
return [...providePslCompletionItems({
|
|
3013
|
+
context: classifyPslCompletionContext({
|
|
3014
|
+
document: document.parse().document,
|
|
3015
|
+
sourceFile: document.sourceFile,
|
|
3016
|
+
position
|
|
3017
|
+
}),
|
|
3018
|
+
sourceFile: document.sourceFile,
|
|
3019
|
+
candidates: {
|
|
3020
|
+
...data.controlStack,
|
|
3021
|
+
symbolTable: data.artifacts.symbolTable(),
|
|
3022
|
+
binder: data.artifacts.binder()
|
|
3023
|
+
},
|
|
3024
|
+
clientSupportsSnippets: capabilities.completionSnippets,
|
|
3025
|
+
clientSupportsTriggerSuggestCommand: capabilities.completionTriggerSuggestCommand,
|
|
3026
|
+
clientSupportsTriggerParameterHintsCommand: capabilities.completionTriggerParameterHintsCommand
|
|
3027
|
+
})];
|
|
3028
|
+
} catch {
|
|
3029
|
+
return [];
|
|
3030
|
+
}
|
|
3031
|
+
}
|
|
3032
|
+
async signatureHelp(uri, position, labelOffsets) {
|
|
3033
|
+
const data = await this.#resolveMember(uri);
|
|
3034
|
+
const document = data?.artifacts.document(uri);
|
|
3035
|
+
if (data === void 0 || document === void 0) return null;
|
|
3036
|
+
try {
|
|
3037
|
+
return providePslSignatureHelp({
|
|
3038
|
+
clientSupportsLabelOffsets: labelOffsets,
|
|
3039
|
+
document: document.parse().document,
|
|
3040
|
+
sourceFile: document.sourceFile,
|
|
3041
|
+
position,
|
|
3042
|
+
candidates: {
|
|
3043
|
+
...data.controlStack,
|
|
3044
|
+
symbolTable: data.artifacts.symbolTable(),
|
|
3045
|
+
binder: data.artifacts.binder()
|
|
3046
|
+
}
|
|
3047
|
+
});
|
|
3048
|
+
} catch {
|
|
3049
|
+
return null;
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
3052
|
+
async hover(uri, position) {
|
|
3053
|
+
const data = await this.#resolveMember(uri);
|
|
3054
|
+
const document = data?.artifacts.document(uri);
|
|
3055
|
+
if (data === void 0 || document === void 0) return null;
|
|
3056
|
+
try {
|
|
3057
|
+
return providePslHover({
|
|
3058
|
+
document: document.parse().document,
|
|
3059
|
+
sourceFile: document.sourceFile,
|
|
3060
|
+
position,
|
|
3061
|
+
binder: data.artifacts.binder(),
|
|
3062
|
+
pslBlockDescriptors: data.controlStack.pslBlockDescriptors,
|
|
3063
|
+
dataTypes: data.controlStack.dataTypes ?? EMPTY_DATA_TYPES
|
|
3064
|
+
});
|
|
3065
|
+
} catch {
|
|
3066
|
+
return null;
|
|
3067
|
+
}
|
|
3068
|
+
}
|
|
3069
|
+
async definition(uri, position, linkSupport) {
|
|
3070
|
+
const data = await this.#resolveMember(uri);
|
|
3071
|
+
const document = data?.artifacts.document(uri);
|
|
3072
|
+
if (data === void 0 || document === void 0) return null;
|
|
3073
|
+
try {
|
|
3074
|
+
return provideDefinition({
|
|
3075
|
+
document: document.parse().document,
|
|
3076
|
+
sourceFile: document.sourceFile,
|
|
3077
|
+
position,
|
|
3078
|
+
sources: data.artifacts.sources,
|
|
3079
|
+
binder: data.artifacts.binder(),
|
|
3080
|
+
linkSupport
|
|
3081
|
+
});
|
|
3082
|
+
} catch {
|
|
3083
|
+
return null;
|
|
3084
|
+
}
|
|
3085
|
+
}
|
|
3086
|
+
async references(uri, position, includeDeclaration) {
|
|
3087
|
+
const data = await this.#resolveMember(uri);
|
|
3088
|
+
const document = data?.artifacts.document(uri);
|
|
3089
|
+
if (data === void 0 || document === void 0) return [];
|
|
3090
|
+
try {
|
|
3091
|
+
const documents = data.artifacts.documents().map((snapshot) => ({
|
|
3092
|
+
document: snapshot.parse().document,
|
|
3093
|
+
sourceFile: snapshot.sourceFile
|
|
3094
|
+
}));
|
|
3095
|
+
return provideReferences({
|
|
3096
|
+
document: document.parse().document,
|
|
3097
|
+
sourceFile: document.sourceFile,
|
|
3098
|
+
position,
|
|
3099
|
+
documents,
|
|
3100
|
+
binder: data.artifacts.binder(),
|
|
3101
|
+
includeDeclaration
|
|
3102
|
+
});
|
|
3103
|
+
} catch {
|
|
3104
|
+
return [];
|
|
3105
|
+
}
|
|
3106
|
+
}
|
|
3107
|
+
async prepareRename(uri, position) {
|
|
3108
|
+
const data = await this.#resolveMember(uri);
|
|
3109
|
+
const document = data?.artifacts.document(uri);
|
|
3110
|
+
if (data === void 0 || document === void 0) return null;
|
|
3111
|
+
try {
|
|
3112
|
+
const documents = data.artifacts.documents().map((snapshot) => ({
|
|
3113
|
+
document: snapshot.parse().document,
|
|
3114
|
+
sourceFile: snapshot.sourceFile
|
|
3115
|
+
}));
|
|
3116
|
+
return providePrepareRename({
|
|
3117
|
+
document: document.parse().document,
|
|
3118
|
+
sourceFile: document.sourceFile,
|
|
3119
|
+
position,
|
|
3120
|
+
documents,
|
|
3121
|
+
binder: data.artifacts.binder(),
|
|
3122
|
+
symbolTable: data.artifacts.symbolTable()
|
|
3123
|
+
});
|
|
3124
|
+
} catch {
|
|
3125
|
+
return null;
|
|
3126
|
+
}
|
|
3127
|
+
}
|
|
3128
|
+
async rename(uri, position, newName) {
|
|
3129
|
+
const data = await this.#resolveMember(uri);
|
|
3130
|
+
const document = data?.artifacts.document(uri);
|
|
3131
|
+
if (data === void 0 || document === void 0) return null;
|
|
3132
|
+
try {
|
|
3133
|
+
const documents = data.artifacts.documents().map((snapshot) => ({
|
|
3134
|
+
document: snapshot.parse().document,
|
|
3135
|
+
sourceFile: snapshot.sourceFile
|
|
3136
|
+
}));
|
|
3137
|
+
return provideRename({
|
|
3138
|
+
document: document.parse().document,
|
|
3139
|
+
sourceFile: document.sourceFile,
|
|
3140
|
+
position,
|
|
3141
|
+
documents,
|
|
3142
|
+
binder: data.artifacts.binder(),
|
|
3143
|
+
...data.controlStack,
|
|
3144
|
+
symbolTable: data.artifacts.symbolTable(),
|
|
3145
|
+
formatOptions: resolveFormatOptions(data.formatter),
|
|
3146
|
+
newName
|
|
3147
|
+
});
|
|
3148
|
+
} catch (error) {
|
|
3149
|
+
if (error instanceof ResponseError && error.code === LSPErrorCodes.RequestFailed) throw error;
|
|
3150
|
+
return null;
|
|
3151
|
+
}
|
|
3152
|
+
}
|
|
3153
|
+
async foldingRanges(uri) {
|
|
3154
|
+
const data = await this.#resolveMember(uri);
|
|
3155
|
+
const document = data?.artifacts.document(uri);
|
|
3156
|
+
if (data === void 0 || document === void 0) return [];
|
|
3157
|
+
return computeFoldingRanges(document.parse().document, data.artifacts.sources);
|
|
3158
|
+
}
|
|
3159
|
+
#resolveData() {
|
|
3160
|
+
const entry = this.#state;
|
|
3161
|
+
if (entry.status === "failed") return this.#startLoad();
|
|
3162
|
+
return entry.status === "loaded" ? Promise.resolve(entry.data) : entry.load;
|
|
3163
|
+
}
|
|
3164
|
+
async #resolveMember(uri) {
|
|
3165
|
+
const data = await this.#resolveData().catch(() => void 0);
|
|
3166
|
+
if (data === void 0 || data.inputs.includes(uri)) return data;
|
|
3167
|
+
this.#options.unmanage(uri);
|
|
3168
|
+
}
|
|
3169
|
+
async reload() {
|
|
3170
|
+
const data = await this.#startLoad();
|
|
3171
|
+
this.#publishMembers(data);
|
|
3172
|
+
}
|
|
3173
|
+
publishMembers() {
|
|
3174
|
+
const data = this.#current();
|
|
3175
|
+
if (data !== void 0) this.#publishMembers(data);
|
|
3176
|
+
}
|
|
3177
|
+
documentChanged(uri) {
|
|
3178
|
+
this.artifacts?.documentChanged(uri);
|
|
3179
|
+
}
|
|
3180
|
+
documentClosed(uri) {
|
|
3181
|
+
this.artifacts?.documentClosed(uri);
|
|
3182
|
+
}
|
|
3183
|
+
async diagnosticReport(requestedUri) {
|
|
3184
|
+
const project = await this.#resolveData().catch(() => void 0);
|
|
3185
|
+
const uri = normalizeFileUri(requestedUri);
|
|
3186
|
+
if (project === void 0 || !project.inputs.includes(uri) && !this.#reportedMembers.has(uri)) return {
|
|
3187
|
+
kind: DocumentDiagnosticReportKind.Full,
|
|
3188
|
+
items: []
|
|
3189
|
+
};
|
|
3190
|
+
const projectSymbolDiagnostics = project.artifacts.symbolDiagnostics();
|
|
3191
|
+
const reportFor = (memberUri) => ({
|
|
3192
|
+
kind: DocumentDiagnosticReportKind.Full,
|
|
3193
|
+
items: toDiagnostics(project.artifacts.diagnostics(memberUri, projectSymbolDiagnostics))
|
|
3194
|
+
});
|
|
3195
|
+
const members = new Set(Array.from(project.inputs.uris(), normalizeFileUri));
|
|
3196
|
+
const previous = this.#reportedMembers;
|
|
3197
|
+
const relatedDocuments = {};
|
|
3198
|
+
for (const memberUri of /* @__PURE__ */ new Set([...members, ...previous])) {
|
|
3199
|
+
if (memberUri === uri) continue;
|
|
3200
|
+
relatedDocuments[memberUri] = members.has(memberUri) ? reportFor(memberUri) : {
|
|
3201
|
+
kind: DocumentDiagnosticReportKind.Full,
|
|
3202
|
+
items: []
|
|
3203
|
+
};
|
|
3204
|
+
}
|
|
3205
|
+
const report = reportFor(uri);
|
|
3206
|
+
if (previous.has(uri)) members.add(uri);
|
|
3207
|
+
this.#reportedMembers = members;
|
|
3208
|
+
return {
|
|
3209
|
+
...report,
|
|
3210
|
+
...Object.keys(relatedDocuments).length > 0 ? { relatedDocuments } : {}
|
|
3211
|
+
};
|
|
3212
|
+
}
|
|
3213
|
+
async refreshMembership(uri, sequence) {
|
|
3214
|
+
const entry = this.#state;
|
|
3215
|
+
if (entry.status === "failed" || this.#membershipSequence > sequence) return false;
|
|
3216
|
+
this.#membershipSequence = sequence;
|
|
3217
|
+
this.documentChanged(uri);
|
|
3218
|
+
const project = entry.status === "loaded" ? entry.data : await entry.load.catch(() => void 0);
|
|
3219
|
+
const isCurrent = () => this.#state.status === "loaded" && this.#state.data === project && this.#membershipSequence === sequence;
|
|
3220
|
+
if (project === void 0 || !isCurrent()) return false;
|
|
3221
|
+
const nextInputs = await resolveSchemaInputs(project.schemaInputConfig, (candidate) => this.#options.documents.text(candidate));
|
|
3222
|
+
if (!isCurrent()) return false;
|
|
3223
|
+
project.artifacts.updateInputs(nextInputs);
|
|
3224
|
+
const updated = {
|
|
3225
|
+
...project,
|
|
3226
|
+
inputs: nextInputs
|
|
3227
|
+
};
|
|
3228
|
+
this.#state = {
|
|
3229
|
+
status: "loaded",
|
|
3230
|
+
data: updated
|
|
3231
|
+
};
|
|
3232
|
+
if (this.#watcher?.schemaInputConfig === project.schemaInputConfig && isWatcherCacheEligible(project.schemaInputConfig)) this.#options.documents.setWatchCoverage(this.configPath, nextInputs.uris());
|
|
3233
|
+
this.#publishMembers(updated);
|
|
3234
|
+
return true;
|
|
3235
|
+
}
|
|
3236
|
+
#current() {
|
|
3237
|
+
if (this.#state.status === "failed") return void 0;
|
|
3238
|
+
return this.#state.status === "loaded" ? this.#state.data : this.#state.lastGood;
|
|
3239
|
+
}
|
|
3240
|
+
#startLoad() {
|
|
3241
|
+
this.#membershipSequence = this.#options.nextSequence();
|
|
3242
|
+
this.#clearWatcher();
|
|
3243
|
+
const existing = this.#state;
|
|
3244
|
+
const previousLoad = existing.status === "loading" ? existing.load : void 0;
|
|
3245
|
+
const lastGood = this.#current();
|
|
3246
|
+
const load = (previousLoad ?? Promise.resolve(void 0)).catch(() => void 0).then(() => this.#load()).then((data) => {
|
|
3247
|
+
if (this.#isCurrentLoad(load)) {
|
|
3248
|
+
this.#state = {
|
|
3249
|
+
status: "loaded",
|
|
3250
|
+
data
|
|
3251
|
+
};
|
|
3252
|
+
this.#sendDiagnostics({
|
|
3253
|
+
uri: pathToFileURL(this.configPath).toString(),
|
|
3254
|
+
diagnostics: []
|
|
3255
|
+
});
|
|
3256
|
+
this.#registerWatcher(data);
|
|
3257
|
+
}
|
|
3258
|
+
return data;
|
|
3259
|
+
}, (error) => {
|
|
3260
|
+
if (this.#isCurrentLoad(load)) {
|
|
3261
|
+
this.#publishConfigFailure(error);
|
|
3262
|
+
if (lastGood !== void 0) {
|
|
3263
|
+
this.#state = {
|
|
3264
|
+
status: "loaded",
|
|
3265
|
+
data: lastGood
|
|
3266
|
+
};
|
|
3267
|
+
this.#registerWatcher(lastGood);
|
|
3268
|
+
return lastGood;
|
|
3269
|
+
}
|
|
3270
|
+
this.#state = { status: "failed" };
|
|
3271
|
+
this.#options.unmanage();
|
|
3272
|
+
this.#clearWatcher();
|
|
3273
|
+
this.#clearPublishedMembers();
|
|
3274
|
+
}
|
|
3275
|
+
throw error;
|
|
3276
|
+
});
|
|
3277
|
+
this.#state = {
|
|
3278
|
+
status: "loading",
|
|
3279
|
+
load,
|
|
3280
|
+
lastGood
|
|
3281
|
+
};
|
|
3282
|
+
return load;
|
|
3283
|
+
}
|
|
3284
|
+
#isCurrentLoad(load) {
|
|
3285
|
+
return this.#state.status === "loading" && this.#state.load === load;
|
|
3286
|
+
}
|
|
3287
|
+
async #load() {
|
|
3288
|
+
const resolution = await resolveConfigInputs(this.configPath, (uri) => this.#options.documents.text(uri));
|
|
3289
|
+
const artifacts = new ProjectArtifacts({
|
|
3290
|
+
controlStack: resolution.controlStack,
|
|
3291
|
+
inputs: resolution.inputs,
|
|
3292
|
+
readSnapshot: this.#options.documents.readSnapshot,
|
|
3293
|
+
onInterpretationError: (uri, error) => {
|
|
3294
|
+
const detail = error instanceof Error ? error.stack ?? error.message : String(error);
|
|
3295
|
+
this.#options.connection.console.error(`PSL interpretation failed for ${uri}: ${detail}`);
|
|
3296
|
+
},
|
|
3297
|
+
...resolution.interpretation === void 0 ? {} : { interpretation: resolution.interpretation },
|
|
3298
|
+
...resolution.parserOptions === void 0 ? {} : { parserOptions: resolution.parserOptions }
|
|
3299
|
+
});
|
|
3300
|
+
return {
|
|
3301
|
+
...resolution,
|
|
3302
|
+
artifacts
|
|
3303
|
+
};
|
|
3304
|
+
}
|
|
3305
|
+
#clearWatcher() {
|
|
3306
|
+
const generation = ++this.#watcherGeneration;
|
|
3307
|
+
this.#options.documents.setWatchCoverage(this.configPath, []);
|
|
3308
|
+
if (this.#watcher !== void 0) this.#unregisterWatcher(this.#watcher.id);
|
|
3309
|
+
this.#watcher = void 0;
|
|
3310
|
+
return generation;
|
|
3311
|
+
}
|
|
3312
|
+
#unregisterWatcher(id) {
|
|
3313
|
+
this.#options.connection.sendRequest(UnregistrationRequest.type, { unregisterations: [{
|
|
3314
|
+
id,
|
|
3315
|
+
method: DidChangeWatchedFilesNotification.type.method
|
|
3316
|
+
}] });
|
|
3317
|
+
}
|
|
3318
|
+
async #registerWatcher(project) {
|
|
3319
|
+
const generation = this.#clearWatcher();
|
|
3320
|
+
if (!this.#options.watchedFilesRegistration) return;
|
|
3321
|
+
const patterns = project.schemaInputConfig.contract?.source.inputs ?? [];
|
|
3322
|
+
if (patterns.length === 0) return;
|
|
3323
|
+
const id = randomUUID();
|
|
3324
|
+
if (await this.#options.connection.sendRequest(RegistrationRequest.type, { registrations: [{
|
|
3325
|
+
id,
|
|
3326
|
+
method: DidChangeWatchedFilesNotification.type.method,
|
|
3327
|
+
registerOptions: { watchers: patterns.map((pattern) => ({ globPattern: toWatcherGlobPattern(pattern) })) }
|
|
3328
|
+
}] }) === void 0) return;
|
|
3329
|
+
if (this.#watcherGeneration !== generation) {
|
|
3330
|
+
this.#unregisterWatcher(id);
|
|
3331
|
+
return;
|
|
3332
|
+
}
|
|
3333
|
+
this.#watcher = {
|
|
3334
|
+
id,
|
|
3335
|
+
schemaInputConfig: project.schemaInputConfig
|
|
3336
|
+
};
|
|
3337
|
+
const current = this.#current();
|
|
3338
|
+
if (current?.schemaInputConfig === project.schemaInputConfig && isWatcherCacheEligible(project.schemaInputConfig)) this.#options.documents.setWatchCoverage(this.configPath, current.inputs.uris());
|
|
3339
|
+
}
|
|
3340
|
+
#publishMembers(project) {
|
|
3341
|
+
if (this.#options.pullDiagnostics) return;
|
|
3342
|
+
const nextLedger = /* @__PURE__ */ new Set();
|
|
3343
|
+
const projectSymbolDiagnostics = project.artifacts.symbolDiagnostics();
|
|
3344
|
+
for (const candidateUri of project.inputs.uris()) {
|
|
3345
|
+
const uri = normalizeFileUri(candidateUri);
|
|
3346
|
+
this.#sendDiagnostics({
|
|
3347
|
+
uri,
|
|
3348
|
+
diagnostics: toDiagnostics(project.artifacts.diagnostics(uri, projectSymbolDiagnostics))
|
|
3349
|
+
});
|
|
3350
|
+
nextLedger.add(uri);
|
|
3351
|
+
}
|
|
3352
|
+
for (const uri of this.#reportedMembers) if (!nextLedger.has(uri)) this.#sendDiagnostics({
|
|
3353
|
+
uri,
|
|
3354
|
+
diagnostics: []
|
|
3355
|
+
});
|
|
3356
|
+
this.#reportedMembers = nextLedger;
|
|
3357
|
+
}
|
|
3358
|
+
#clearPublishedMembers() {
|
|
3359
|
+
if (this.#options.pullDiagnostics) return;
|
|
3360
|
+
for (const uri of this.#reportedMembers) this.#sendDiagnostics({
|
|
3361
|
+
uri,
|
|
3362
|
+
diagnostics: []
|
|
3363
|
+
});
|
|
3364
|
+
this.#reportedMembers = /* @__PURE__ */ new Set();
|
|
3365
|
+
}
|
|
3366
|
+
#publishConfigFailure(error) {
|
|
3367
|
+
this.#sendDiagnostics({
|
|
3368
|
+
uri: pathToFileURL(this.configPath).toString(),
|
|
3369
|
+
diagnostics: [{
|
|
3370
|
+
range: {
|
|
3371
|
+
start: {
|
|
3372
|
+
line: 0,
|
|
3373
|
+
character: 0
|
|
3374
|
+
},
|
|
3375
|
+
end: {
|
|
3376
|
+
line: 0,
|
|
3377
|
+
character: 1
|
|
3378
|
+
}
|
|
3379
|
+
},
|
|
3380
|
+
message: CliStructuredError.is(error) ? error.why ?? error.message : error instanceof Error ? error.message : String(error),
|
|
3381
|
+
code: CONFIG_LOAD_FAILED_CODE,
|
|
3382
|
+
severity: DiagnosticSeverity.Error,
|
|
3383
|
+
source: "prisma"
|
|
3384
|
+
}]
|
|
3385
|
+
});
|
|
3386
|
+
}
|
|
3387
|
+
#sendDiagnostics(params) {
|
|
3388
|
+
this.#options.connection.sendDiagnostics({
|
|
3389
|
+
...params,
|
|
3390
|
+
uri: normalizeFileUri(params.uri)
|
|
3391
|
+
});
|
|
3392
|
+
}
|
|
3393
|
+
};
|
|
3394
|
+
function toDiagnostics(computed) {
|
|
3395
|
+
return computed.map((diagnostic) => ({
|
|
3396
|
+
range: diagnostic.range,
|
|
3397
|
+
message: diagnostic.message,
|
|
3398
|
+
code: diagnostic.code,
|
|
3399
|
+
severity: toLspSeverity(diagnostic.severity),
|
|
3400
|
+
source: "prisma"
|
|
3401
|
+
}));
|
|
3402
|
+
}
|
|
3403
|
+
function toLspSeverity(severity) {
|
|
3404
|
+
switch (severity) {
|
|
3405
|
+
case ParseDiagnosticSeverity.Warning: return DiagnosticSeverity.Warning;
|
|
3406
|
+
case ParseDiagnosticSeverity.Information: return DiagnosticSeverity.Information;
|
|
3407
|
+
case ParseDiagnosticSeverity.Hint: return DiagnosticSeverity.Hint;
|
|
3408
|
+
default: return DiagnosticSeverity.Error;
|
|
3409
|
+
}
|
|
3410
|
+
}
|
|
3411
|
+
var ProjectRegistry = class {
|
|
3412
|
+
#documents;
|
|
3413
|
+
#connection;
|
|
3414
|
+
#projectsByConfig = /* @__PURE__ */ new Map();
|
|
3415
|
+
#projectsByDocument = /* @__PURE__ */ new Map();
|
|
3416
|
+
#eventSequence = 0;
|
|
3417
|
+
#capabilities = {
|
|
3418
|
+
pullDiagnostics: false,
|
|
3419
|
+
watchedFilesRegistration: false,
|
|
3420
|
+
diagnosticsRefresh: false
|
|
3421
|
+
};
|
|
3422
|
+
constructor(documents, connection) {
|
|
3423
|
+
this.#documents = documents;
|
|
3424
|
+
this.#connection = connection;
|
|
3425
|
+
}
|
|
3426
|
+
setClientCapabilities(capabilities) {
|
|
3427
|
+
this.#capabilities = capabilities;
|
|
3428
|
+
}
|
|
3429
|
+
async nearestProject(uri) {
|
|
3430
|
+
const knownProject = this.associatedProject(uri);
|
|
3431
|
+
if (knownProject !== void 0) return knownProject;
|
|
3432
|
+
const filePath = filePathFromUri(uri);
|
|
3433
|
+
if (filePath === void 0) return void 0;
|
|
3434
|
+
let configPath;
|
|
3435
|
+
try {
|
|
3436
|
+
configPath = await findNearestConfigPathForFile(filePath);
|
|
3437
|
+
} catch {
|
|
3438
|
+
return;
|
|
3439
|
+
}
|
|
3440
|
+
if (configPath === void 0) return void 0;
|
|
3441
|
+
const project = this.#projectForConfig(configPath);
|
|
3442
|
+
this.#projectsByDocument.set(canonicalFileIdentity(uri), project);
|
|
3443
|
+
return project;
|
|
3444
|
+
}
|
|
3445
|
+
associatedProject(uri) {
|
|
3446
|
+
return this.#projectsByDocument.get(canonicalFileIdentity(uri));
|
|
3447
|
+
}
|
|
3448
|
+
documentChanged(uri) {
|
|
3449
|
+
this.associatedProject(uri)?.documentChanged(uri);
|
|
3450
|
+
this.#publishForDocument(uri).catch((error) => {
|
|
3451
|
+
this.#connection.console.error(error instanceof Error ? error.message : String(error));
|
|
3452
|
+
});
|
|
3453
|
+
}
|
|
3454
|
+
documentClosed(uri) {
|
|
3455
|
+
const project = this.associatedProject(uri);
|
|
3456
|
+
project?.documentClosed(uri);
|
|
3457
|
+
this.#projectsByDocument.delete(canonicalFileIdentity(uri));
|
|
3458
|
+
if (project?.artifacts === void 0) {
|
|
3459
|
+
if (!this.#capabilities.pullDiagnostics) this.#connection.sendDiagnostics({
|
|
3460
|
+
uri: normalizeFileUri(uri),
|
|
3461
|
+
diagnostics: []
|
|
3462
|
+
});
|
|
3463
|
+
return;
|
|
3464
|
+
}
|
|
3465
|
+
project.publishMembers();
|
|
3466
|
+
}
|
|
3467
|
+
watchConfigFiles(rootPath) {
|
|
3468
|
+
if (this.#capabilities.watchedFilesRegistration) this.#connection.sendRequest(RegistrationRequest.type, { registrations: [{
|
|
3469
|
+
id: "prisma-8-config-watcher",
|
|
3470
|
+
method: DidChangeWatchedFilesNotification.type.method,
|
|
3471
|
+
registerOptions: { watchers: [{ globPattern: join(rootPath, "**", CONFIG_FILENAME) }] }
|
|
3472
|
+
}] });
|
|
3473
|
+
else this.#connection.console.warn("Client does not support dynamic file-watcher registration; Prisma 8 config changes will not be picked up without a restart.");
|
|
3474
|
+
}
|
|
3475
|
+
async watchedFilesChanged(changes) {
|
|
3476
|
+
const changedConfigPaths = /* @__PURE__ */ new Set();
|
|
3477
|
+
const memberChanges = [];
|
|
3478
|
+
for (const change of changes) {
|
|
3479
|
+
const filePath = filePathFromUri(change.uri);
|
|
3480
|
+
if (filePath?.endsWith("prisma.config.ts")) changedConfigPaths.add(filePath);
|
|
3481
|
+
else memberChanges.push(change.uri);
|
|
3482
|
+
}
|
|
3483
|
+
const configRefreshes = Array.from(changedConfigPaths, async (configPath) => {
|
|
3484
|
+
return this.#projectsByConfig.get(configPath)?.reload().catch(() => void 0);
|
|
3485
|
+
});
|
|
3486
|
+
const [, memberResults] = await Promise.all([Promise.all(configRefreshes), Promise.all(memberChanges.map((uri) => this.#handleSchemaMemberChange(uri)))]);
|
|
3487
|
+
if (this.#capabilities.pullDiagnostics && this.#capabilities.diagnosticsRefresh && (changedConfigPaths.size > 0 || memberResults.some(Boolean))) this.#connection.languages.diagnostics.refresh();
|
|
3488
|
+
}
|
|
3489
|
+
#projectForConfig(configPath) {
|
|
3490
|
+
let project = this.#projectsByConfig.get(configPath);
|
|
3491
|
+
if (project === void 0) {
|
|
3492
|
+
project = new Project(configPath, {
|
|
3493
|
+
documents: this.#documents,
|
|
3494
|
+
connection: this.#connection,
|
|
3495
|
+
pullDiagnostics: this.#capabilities.pullDiagnostics,
|
|
3496
|
+
watchedFilesRegistration: this.#capabilities.watchedFilesRegistration,
|
|
3497
|
+
nextSequence: () => ++this.#eventSequence,
|
|
3498
|
+
unmanage: (uri) => {
|
|
3499
|
+
if (uri === void 0) this.#unmanageDocuments(configPath);
|
|
3500
|
+
else this.#projectsByDocument.delete(canonicalFileIdentity(uri));
|
|
3501
|
+
}
|
|
3502
|
+
});
|
|
3503
|
+
this.#projectsByConfig.set(configPath, project);
|
|
3504
|
+
}
|
|
3505
|
+
return project;
|
|
3506
|
+
}
|
|
3507
|
+
#unmanageDocuments(configPath) {
|
|
3508
|
+
for (const document of this.#documents.openDocuments()) if (this.associatedProject(document.uri)?.configPath === configPath) this.#projectsByDocument.delete(canonicalFileIdentity(document.uri));
|
|
3509
|
+
}
|
|
3510
|
+
async #publishForDocument(uri) {
|
|
3511
|
+
await (await this.nearestProject(uri))?.publishForDocument(uri);
|
|
3512
|
+
}
|
|
3513
|
+
async #handleSchemaMemberChange(uri) {
|
|
3514
|
+
const sequence = ++this.#eventSequence;
|
|
3515
|
+
this.#documents.invalidate(uri);
|
|
3516
|
+
const filePath = filePathFromUri(uri);
|
|
3517
|
+
if (filePath === void 0) return false;
|
|
3518
|
+
let configPath;
|
|
3519
|
+
try {
|
|
3520
|
+
configPath = await findNearestConfigPathForFile(filePath);
|
|
3521
|
+
} catch {
|
|
3522
|
+
return false;
|
|
3523
|
+
}
|
|
3524
|
+
if (configPath === void 0) return false;
|
|
3525
|
+
return this.#projectsByConfig.get(configPath)?.refreshMembership(uri, sequence) ?? false;
|
|
3526
|
+
}
|
|
3527
|
+
};
|
|
3528
|
+
function filePathFromUri(uri) {
|
|
3529
|
+
try {
|
|
3530
|
+
return fileURLToPath(uri);
|
|
3531
|
+
} catch {
|
|
3532
|
+
return;
|
|
3533
|
+
}
|
|
3534
|
+
}
|
|
3535
|
+
const semanticTokenSourceLimit = 1e5;
|
|
3536
|
+
function createServer(connection) {
|
|
3537
|
+
return createServerOn(guardedConnection(connection));
|
|
3538
|
+
}
|
|
3539
|
+
function createServerOn(connection) {
|
|
3540
|
+
const documents = new DocumentStore();
|
|
3541
|
+
const { getOpenDocument } = documents;
|
|
3542
|
+
const projects = new ProjectRegistry(documents, connection);
|
|
3543
|
+
let rootPath = process.cwd();
|
|
3544
|
+
let clientCapabilities = noClientCapabilities;
|
|
3545
|
+
async function formatDocument(uri) {
|
|
3546
|
+
const document = getOpenDocument(uri);
|
|
3547
|
+
if (document === void 0) return [];
|
|
3548
|
+
const source = document.getText();
|
|
3549
|
+
if (!isPrismaNextSchema(source)) return [];
|
|
3550
|
+
const formatted = await (await projects.nearestProject(uri))?.formatDocument(uri, source);
|
|
3551
|
+
if (formatted === void 0 || formatted === source) return [];
|
|
3552
|
+
return [{
|
|
3553
|
+
range: {
|
|
3554
|
+
start: {
|
|
3555
|
+
line: 0,
|
|
3556
|
+
character: 0
|
|
3557
|
+
},
|
|
3558
|
+
end: document.positionAt(source.length)
|
|
3559
|
+
},
|
|
3560
|
+
newText: formatted
|
|
3561
|
+
}];
|
|
3562
|
+
}
|
|
3563
|
+
async function semanticTokensForDocument(uri, range) {
|
|
3564
|
+
const document = getOpenDocument(uri);
|
|
3565
|
+
if (document === void 0) return emptySemanticTokens();
|
|
3566
|
+
if (document.getText().length > semanticTokenSourceLimit) return emptySemanticTokens();
|
|
3567
|
+
return (await projects.nearestProject(uri))?.semanticTokens(uri, range) ?? emptySemanticTokens();
|
|
3568
|
+
}
|
|
3569
|
+
async function completeDocument(uri, position) {
|
|
3570
|
+
if (getOpenDocument(uri) === void 0) return [];
|
|
3571
|
+
return (await projects.nearestProject(uri))?.completions(uri, position, clientCapabilities) ?? [];
|
|
3572
|
+
}
|
|
3573
|
+
async function signatureHelpForDocument(uri, position) {
|
|
3574
|
+
if (getOpenDocument(uri) === void 0) return null;
|
|
3575
|
+
return (await projects.nearestProject(uri))?.signatureHelp(uri, position, clientCapabilities.signatureLabelOffsets) ?? null;
|
|
3576
|
+
}
|
|
3577
|
+
async function hoverForDocument(uri, position) {
|
|
3578
|
+
if (getOpenDocument(uri) === void 0) return null;
|
|
3579
|
+
return (await projects.nearestProject(uri))?.hover(uri, position) ?? null;
|
|
3580
|
+
}
|
|
3581
|
+
async function definitionForDocument(uri, position) {
|
|
3582
|
+
if (getOpenDocument(uri) === void 0) return null;
|
|
3583
|
+
return (await projects.nearestProject(uri))?.definition(uri, position, clientCapabilities.definitionLinks) ?? null;
|
|
3584
|
+
}
|
|
3585
|
+
async function referencesForDocument(uri, position, includeDeclaration) {
|
|
3586
|
+
if (getOpenDocument(uri) === void 0) return [];
|
|
3587
|
+
return (await projects.nearestProject(uri))?.references(uri, position, includeDeclaration) ?? [];
|
|
3588
|
+
}
|
|
3589
|
+
async function prepareRenameForDocument(uri, position) {
|
|
3590
|
+
if (getOpenDocument(uri) === void 0) return null;
|
|
3591
|
+
return (await projects.nearestProject(uri))?.prepareRename(uri, position) ?? null;
|
|
3592
|
+
}
|
|
3593
|
+
async function renameForDocument(uri, position, newName) {
|
|
3594
|
+
if (getOpenDocument(uri) === void 0) return null;
|
|
3595
|
+
return (await projects.nearestProject(uri))?.rename(uri, position, newName) ?? null;
|
|
3596
|
+
}
|
|
3597
|
+
connection.onInitialize(async (params) => {
|
|
3598
|
+
rootPath = resolveRootPath(params);
|
|
3599
|
+
clientCapabilities = resolveClientCapabilities(params);
|
|
3600
|
+
projects.setClientCapabilities(clientCapabilities);
|
|
3601
|
+
return { capabilities: {
|
|
3602
|
+
textDocumentSync: {
|
|
3603
|
+
openClose: true,
|
|
3604
|
+
change: TextDocumentSyncKind.Incremental
|
|
3605
|
+
},
|
|
3606
|
+
documentFormattingProvider: true,
|
|
3607
|
+
foldingRangeProvider: true,
|
|
3608
|
+
semanticTokensProvider: {
|
|
3609
|
+
legend: semanticTokensLegend,
|
|
3610
|
+
full: true,
|
|
3611
|
+
range: true
|
|
3612
|
+
},
|
|
3613
|
+
completionProvider: { triggerCharacters: [
|
|
3614
|
+
".",
|
|
3615
|
+
"@",
|
|
3616
|
+
"[",
|
|
3617
|
+
"(",
|
|
3618
|
+
"{",
|
|
3619
|
+
":",
|
|
3620
|
+
",",
|
|
3621
|
+
"+"
|
|
3622
|
+
] },
|
|
3623
|
+
signatureHelpProvider: { triggerCharacters: ["(", ","] },
|
|
3624
|
+
hoverProvider: true,
|
|
3625
|
+
definitionProvider: true,
|
|
3626
|
+
referencesProvider: true,
|
|
3627
|
+
renameProvider: clientCapabilities.renamePrepareSupport ? { prepareProvider: true } : true,
|
|
3628
|
+
...clientCapabilities.pullDiagnostics ? { diagnosticProvider: {
|
|
3629
|
+
interFileDependencies: true,
|
|
3630
|
+
workspaceDiagnostics: false
|
|
3631
|
+
} } : {}
|
|
3632
|
+
} };
|
|
3633
|
+
});
|
|
3634
|
+
connection.onInitialized(() => projects.watchConfigFiles(rootPath));
|
|
3635
|
+
connection.onDidChangeWatchedFiles((params) => projects.watchedFilesChanged(params.changes));
|
|
3636
|
+
connection.onDocumentFormatting((params) => formatDocument(params.textDocument.uri));
|
|
3637
|
+
connection.onCompletion((params) => completeDocument(params.textDocument.uri, params.position));
|
|
3638
|
+
connection.onSignatureHelp((params) => signatureHelpForDocument(params.textDocument.uri, params.position));
|
|
3639
|
+
connection.onDefinition((params) => definitionForDocument(params.textDocument.uri, params.position));
|
|
3640
|
+
connection.onReferences((params) => referencesForDocument(params.textDocument.uri, params.position, params.context.includeDeclaration));
|
|
3641
|
+
connection.onPrepareRename((params) => prepareRenameForDocument(params.textDocument.uri, params.position));
|
|
3642
|
+
connection.onRenameRequest((params) => renameForDocument(params.textDocument.uri, params.position, params.newName));
|
|
3643
|
+
connection.onHover((params) => hoverForDocument(params.textDocument.uri, params.position));
|
|
3644
|
+
connection.languages.semanticTokens.on((params) => semanticTokensForDocument(params.textDocument.uri));
|
|
3645
|
+
connection.languages.semanticTokens.onRange((params) => semanticTokensForDocument(params.textDocument.uri, params.range));
|
|
3646
|
+
connection.languages.diagnostics.on(async (params) => {
|
|
3647
|
+
if (!clientCapabilities.pullDiagnostics) return {
|
|
3648
|
+
kind: DocumentDiagnosticReportKind.Full,
|
|
3649
|
+
items: []
|
|
3650
|
+
};
|
|
3651
|
+
const uri = normalizeFileUri(params.textDocument.uri);
|
|
3652
|
+
const project = await projects.nearestProject(uri);
|
|
3653
|
+
if (project === void 0) return {
|
|
3654
|
+
kind: DocumentDiagnosticReportKind.Full,
|
|
3655
|
+
items: []
|
|
3656
|
+
};
|
|
3657
|
+
return project.diagnosticReport(uri);
|
|
3658
|
+
});
|
|
3659
|
+
connection.onFoldingRanges(async (params) => {
|
|
3660
|
+
return (await projects.nearestProject(params.textDocument.uri))?.foldingRanges(params.textDocument.uri) ?? [];
|
|
3661
|
+
});
|
|
3662
|
+
connection.onDidOpenTextDocument((event) => {
|
|
3663
|
+
const document = documents.open(event.textDocument);
|
|
3664
|
+
projects.documentChanged(document.uri);
|
|
3665
|
+
});
|
|
3666
|
+
connection.onDidChangeTextDocument((event) => {
|
|
3667
|
+
const document = documents.change(event.textDocument, event.contentChanges);
|
|
3668
|
+
if (document !== void 0) projects.documentChanged(document.uri);
|
|
3669
|
+
});
|
|
3670
|
+
connection.onDidCloseTextDocument((event) => {
|
|
3671
|
+
const document = documents.close(event.textDocument.uri);
|
|
3672
|
+
if (document === void 0) return;
|
|
3673
|
+
projects.documentClosed(document.uri);
|
|
3674
|
+
});
|
|
3675
|
+
connection.listen();
|
|
3676
|
+
function artifactsForDocument(uri) {
|
|
3677
|
+
return projects.associatedProject(uri)?.artifacts;
|
|
3678
|
+
}
|
|
3679
|
+
return {
|
|
3680
|
+
dispose: () => connection.dispose(),
|
|
3681
|
+
getDocumentAst: (uri) => artifactsForDocument(uri)?.document(uri),
|
|
3682
|
+
getProjectSymbolTable: (uri) => {
|
|
3683
|
+
const artifacts = artifactsForDocument(uri);
|
|
3684
|
+
if (artifacts?.document(uri) === void 0) return void 0;
|
|
3685
|
+
return artifacts.symbolTable();
|
|
3686
|
+
}
|
|
3687
|
+
};
|
|
3688
|
+
}
|
|
3689
|
+
function emptySemanticTokens() {
|
|
3690
|
+
return { data: [] };
|
|
3691
|
+
}
|
|
3692
|
+
const noClientCapabilities = {
|
|
3693
|
+
watchedFilesRegistration: false,
|
|
3694
|
+
completionSnippets: false,
|
|
3695
|
+
signatureLabelOffsets: false,
|
|
3696
|
+
definitionLinks: false,
|
|
3697
|
+
renamePrepareSupport: false,
|
|
3698
|
+
completionTriggerSuggestCommand: false,
|
|
3699
|
+
completionTriggerParameterHintsCommand: false,
|
|
3700
|
+
pullDiagnostics: false,
|
|
3701
|
+
diagnosticsRefresh: false
|
|
3702
|
+
};
|
|
3703
|
+
function resolveClientCapabilities(params) {
|
|
3704
|
+
return {
|
|
3705
|
+
watchedFilesRegistration: params.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration === true,
|
|
3706
|
+
completionSnippets: params.capabilities.textDocument?.completion?.completionItem?.snippetSupport === true,
|
|
3707
|
+
signatureLabelOffsets: params.capabilities.textDocument?.signatureHelp?.signatureInformation?.parameterInformation?.labelOffsetSupport === true,
|
|
3708
|
+
definitionLinks: params.capabilities.textDocument?.definition?.linkSupport === true,
|
|
3709
|
+
renamePrepareSupport: params.capabilities.textDocument?.rename?.prepareSupport === true,
|
|
3710
|
+
completionTriggerSuggestCommand: supportsCompletionCommand(params.initializationOptions, "supportsTriggerSuggestCommand"),
|
|
3711
|
+
completionTriggerParameterHintsCommand: supportsCompletionCommand(params.initializationOptions, "supportsTriggerParameterHintsCommand"),
|
|
3712
|
+
pullDiagnostics: params.capabilities.textDocument?.diagnostic?.relatedDocumentSupport === true,
|
|
3713
|
+
diagnosticsRefresh: params.capabilities.workspace?.diagnostics?.refreshSupport === true
|
|
3714
|
+
};
|
|
3715
|
+
}
|
|
3716
|
+
function supportsCompletionCommand(options, capability) {
|
|
3717
|
+
if (typeof options !== "object" || options === null || !("completion" in options)) return false;
|
|
3718
|
+
const completion = options.completion;
|
|
3719
|
+
if (typeof completion !== "object" || completion === null) return false;
|
|
3720
|
+
return capability === "supportsTriggerSuggestCommand" ? "supportsTriggerSuggestCommand" in completion && completion.supportsTriggerSuggestCommand === true : "supportsTriggerParameterHintsCommand" in completion && completion.supportsTriggerParameterHintsCommand === true;
|
|
3721
|
+
}
|
|
3722
|
+
function resolveRootPath(params) {
|
|
3723
|
+
const workspaceFolder = params.workspaceFolders?.[0];
|
|
3724
|
+
if (workspaceFolder !== void 0) return fileURLToPath(workspaceFolder.uri);
|
|
3725
|
+
if (params.rootUri) return fileURLToPath(params.rootUri);
|
|
3726
|
+
if (params.rootPath) return params.rootPath;
|
|
3727
|
+
return process.cwd();
|
|
3728
|
+
}
|
|
3729
|
+
/**
|
|
3730
|
+
* `objectMode: false` is what makes this a byte stream rather than a stream of
|
|
3731
|
+
* whatever objects the host yielded: it converts each chunk to a `Buffer`.
|
|
3732
|
+
* `vscode-jsonrpc` needs that — it slices header blocks with
|
|
3733
|
+
* `Buffer.from(chunk, 0, length)`, and on a plain `Uint8Array` those arguments
|
|
3734
|
+
* are ignored, so it reads the whole chunk as one header block and rejects the
|
|
3735
|
+
* message.
|
|
3736
|
+
*/
|
|
3737
|
+
function byteInputStream(stdin) {
|
|
3738
|
+
return Readable.from(stdin, { objectMode: false });
|
|
3739
|
+
}
|
|
3740
|
+
/**
|
|
3741
|
+
* Bridges the byte stream `vscode-jsonrpc` writes to the text sink a host
|
|
3742
|
+
* hands over.
|
|
3743
|
+
*
|
|
3744
|
+
* LSP declares each message's `Content-Length` in bytes, so a UTF-8 sequence
|
|
3745
|
+
* that arrives split across two writes has to be held back until it is whole:
|
|
3746
|
+
* decoding half of one yields a replacement character, which is a different
|
|
3747
|
+
* number of bytes than the header promised. `StreamMessageWriter` writes each
|
|
3748
|
+
* body in one call and Node never splits a chunk given to `_write`, so the
|
|
3749
|
+
* decoder holds nothing back in practice — it is here because the contract
|
|
3750
|
+
* this satisfies is "bytes in, text out", and a writer that chunks its bodies
|
|
3751
|
+
* would otherwise corrupt every multi-byte message silently.
|
|
3752
|
+
*
|
|
3753
|
+
* Back-pressure is dropped: `TextSink.write` returns nothing to wait on, so
|
|
3754
|
+
* every write reports flushed the moment the sink has taken it. A client that
|
|
3755
|
+
* stops reading grows the host's own output queue instead of slowing the
|
|
3756
|
+
* server down, and the diagnostics for a large schema are not small. Fixing it
|
|
3757
|
+
* needs a sink that reports when it drained.
|
|
3758
|
+
*/
|
|
3759
|
+
function textOutputStream(stdout) {
|
|
3760
|
+
const decoder = new StringDecoder("utf8");
|
|
3761
|
+
return new Writable({
|
|
3762
|
+
write(chunk, _encoding, callback) {
|
|
3763
|
+
stdout.write(decoder.write(chunk));
|
|
3764
|
+
callback();
|
|
3765
|
+
},
|
|
3766
|
+
final(callback) {
|
|
3767
|
+
const pending = decoder.end();
|
|
3768
|
+
if (pending !== "") stdout.write(pending);
|
|
3769
|
+
callback();
|
|
3770
|
+
}
|
|
3771
|
+
});
|
|
3772
|
+
}
|
|
3773
|
+
/**
|
|
3774
|
+
* Sends everything written through the global `console` to the host's stderr
|
|
3775
|
+
* for the length of the run, and returns the undo.
|
|
3776
|
+
*
|
|
3777
|
+
* The client owns stdout: anything on it that is not a `Content-Length` frame
|
|
3778
|
+
* desynchronises the client for good. `console.log` and friends write straight
|
|
3779
|
+
* to the process's own stdout, so one call from anywhere in the dependency
|
|
3780
|
+
* graph — resolving a project's config reaches c12 and jiti — corrupts the
|
|
3781
|
+
* protocol. `vscode-languageserver/node` redirects the console for exactly
|
|
3782
|
+
* this reason when it takes stdio off `process.argv`; over injected streams
|
|
3783
|
+
* that never runs, so the redirect happens here.
|
|
3784
|
+
*
|
|
3785
|
+
* A dependency that writes to `process.stdout` directly still reaches the
|
|
3786
|
+
* client. Nothing short of replacing the process's own descriptor covers that,
|
|
3787
|
+
* and only the host owns the process.
|
|
3788
|
+
*/
|
|
3789
|
+
function captureConsole(stderr) {
|
|
3790
|
+
const host = globalThis.console;
|
|
3791
|
+
const sink = textOutputStream(stderr);
|
|
3792
|
+
globalThis.console = new Console({
|
|
3793
|
+
stdout: sink,
|
|
3794
|
+
stderr: sink
|
|
3795
|
+
});
|
|
3796
|
+
return () => {
|
|
3797
|
+
globalThis.console = host;
|
|
3798
|
+
};
|
|
3799
|
+
}
|
|
3800
|
+
/**
|
|
3801
|
+
* How long the conversation may stand completely still before a message the
|
|
3802
|
+
* connection took off the reader but never dispatched is written off. It
|
|
3803
|
+
* answers a cancellation itself without telling anyone, so the count of
|
|
3804
|
+
* messages awaiting dispatch can be left standing; every other route decrements
|
|
3805
|
+
* it. Any activity restarts the clock, so this delays the exit rather than
|
|
3806
|
+
* cutting a reply short.
|
|
3807
|
+
*/
|
|
3808
|
+
const stalledDispatchGraceMs = 50;
|
|
3809
|
+
/**
|
|
3810
|
+
* How long a host abort lets in-flight work drain before the run settles
|
|
3811
|
+
* regardless. The host has already decided to stop, so a handler that never
|
|
3812
|
+
* settles — or work that never goes idle — must not hold the exit code back
|
|
3813
|
+
* forever; it only gets this long to finish cleanly.
|
|
3814
|
+
*/
|
|
3815
|
+
const abortDrainDeadlineMs = 2e3;
|
|
3816
|
+
/**
|
|
3817
|
+
* How often the client's process id is polled when the host handed one over.
|
|
3818
|
+
* The same cadence `vscode-languageserver/node` uses for its own watch.
|
|
3819
|
+
*/
|
|
3820
|
+
const clientProcessPollMs = 3e3;
|
|
3821
|
+
function processAlive(pid) {
|
|
3822
|
+
try {
|
|
3823
|
+
process.kill(pid, 0);
|
|
3824
|
+
return true;
|
|
3825
|
+
} catch {
|
|
3826
|
+
return false;
|
|
3827
|
+
}
|
|
3828
|
+
}
|
|
3829
|
+
/**
|
|
3830
|
+
* Runs the server over the host's streams and resolves with the exit code the
|
|
3831
|
+
* client's departure implies. The host owns the process, so nothing here ends
|
|
3832
|
+
* it; every route out settles the promise instead.
|
|
3833
|
+
*/
|
|
3834
|
+
function runServerOverStreams(streams) {
|
|
3835
|
+
const input = byteInputStream(streams.stdin);
|
|
3836
|
+
const inputMessages = new StreamMessageReader(input);
|
|
3837
|
+
const outputMessages = new StreamMessageWriter(textOutputStream(streams.stdout));
|
|
3838
|
+
const releaseConsole = captureConsole(streams.stderr);
|
|
3839
|
+
return new Promise((resolve) => {
|
|
3840
|
+
let settled = false;
|
|
3841
|
+
/**
|
|
3842
|
+
* Messages the connection is handling and replies it is writing. A request
|
|
3843
|
+
* handler's dispatch covers everything it awaits and the write of its
|
|
3844
|
+
* reply, so this stays above zero for as long as the client is owed
|
|
3845
|
+
* anything.
|
|
3846
|
+
*/
|
|
3847
|
+
let inFlight = 0;
|
|
3848
|
+
/** Messages decoded off the stream that the connection has not started. */
|
|
3849
|
+
let awaitingDispatch = 0;
|
|
3850
|
+
let lastActivity = Date.now();
|
|
3851
|
+
let departure;
|
|
3852
|
+
let idleCheck;
|
|
3853
|
+
let abortDeadline;
|
|
3854
|
+
let clientWatch;
|
|
3855
|
+
function settle(code) {
|
|
3856
|
+
if (settled) return;
|
|
3857
|
+
settled = true;
|
|
3858
|
+
if (idleCheck !== void 0) clearTimeout(idleCheck);
|
|
3859
|
+
if (abortDeadline !== void 0) clearTimeout(abortDeadline);
|
|
3860
|
+
if (clientWatch !== void 0) clearInterval(clientWatch);
|
|
3861
|
+
releaseConsole();
|
|
3862
|
+
server.dispose();
|
|
3863
|
+
input.destroy();
|
|
3864
|
+
resolve(code);
|
|
3865
|
+
}
|
|
3866
|
+
function moved() {
|
|
3867
|
+
lastActivity = Date.now();
|
|
3868
|
+
checkIdle();
|
|
3869
|
+
}
|
|
3870
|
+
/**
|
|
3871
|
+
* Settles once nothing is left in flight. The client's departure is not the
|
|
3872
|
+
* end of the work: everything already read is queued, and a handler that
|
|
3873
|
+
* awaits — resolving a project reads the filesystem — has its reply written
|
|
3874
|
+
* turns later.
|
|
3875
|
+
*/
|
|
3876
|
+
function settleOnceIdle(code) {
|
|
3877
|
+
departure ??= code;
|
|
3878
|
+
checkIdle();
|
|
3879
|
+
}
|
|
3880
|
+
function checkIdle() {
|
|
3881
|
+
if (settled || departure === void 0 || idleCheck !== void 0) return;
|
|
3882
|
+
idleCheck = setTimeout(() => {
|
|
3883
|
+
idleCheck = void 0;
|
|
3884
|
+
if (settled || departure === void 0) return;
|
|
3885
|
+
if (inFlight > 0) return;
|
|
3886
|
+
if (awaitingDispatch === 0 || Date.now() - lastActivity >= stalledDispatchGraceMs) {
|
|
3887
|
+
settle(departure());
|
|
3888
|
+
return;
|
|
3889
|
+
}
|
|
3890
|
+
checkIdle();
|
|
3891
|
+
}, 1);
|
|
3892
|
+
}
|
|
3893
|
+
/** LSP reserves 0 for a client that asked to shut down before leaving. */
|
|
3894
|
+
function departureCode() {
|
|
3895
|
+
return watchDog.shutdownReceived ? 0 : 1;
|
|
3896
|
+
}
|
|
3897
|
+
const reader = {
|
|
3898
|
+
onError: inputMessages.onError,
|
|
3899
|
+
onClose: inputMessages.onClose,
|
|
3900
|
+
onPartialMessage: inputMessages.onPartialMessage,
|
|
3901
|
+
listen: (callback) => inputMessages.listen((message) => {
|
|
3902
|
+
awaitingDispatch += 1;
|
|
3903
|
+
moved();
|
|
3904
|
+
callback(message);
|
|
3905
|
+
}),
|
|
3906
|
+
dispose: () => inputMessages.dispose()
|
|
3907
|
+
};
|
|
3908
|
+
const writer = {
|
|
3909
|
+
onError: outputMessages.onError,
|
|
3910
|
+
onClose: outputMessages.onClose,
|
|
3911
|
+
write: (message) => {
|
|
3912
|
+
inFlight += 1;
|
|
3913
|
+
moved();
|
|
3914
|
+
return outputMessages.write(message).finally(() => {
|
|
3915
|
+
inFlight -= 1;
|
|
3916
|
+
moved();
|
|
3917
|
+
});
|
|
3918
|
+
},
|
|
3919
|
+
end: () => outputMessages.end(),
|
|
3920
|
+
dispose: () => outputMessages.dispose()
|
|
3921
|
+
};
|
|
3922
|
+
const watchDog = {
|
|
3923
|
+
shutdownReceived: false,
|
|
3924
|
+
initialize: () => void 0,
|
|
3925
|
+
exit: (code) => settleOnceIdle(() => code)
|
|
3926
|
+
};
|
|
3927
|
+
const server = createServer(createConnection((logger) => createProtocolConnection(reader, writer, logger, { messageStrategy: { handleMessage: (message, next) => {
|
|
3928
|
+
awaitingDispatch -= 1;
|
|
3929
|
+
inFlight += 1;
|
|
3930
|
+
moved();
|
|
3931
|
+
return Promise.resolve(next(message)).finally(() => {
|
|
3932
|
+
inFlight -= 1;
|
|
3933
|
+
moved();
|
|
3934
|
+
});
|
|
3935
|
+
} } }), watchDog, ProposedFeatures.all));
|
|
3936
|
+
inputMessages.onClose(() => settleOnceIdle(departureCode));
|
|
3937
|
+
inputMessages.onError((error) => {
|
|
3938
|
+
streams.stderr.write(`Language server transport error: ${messageOf(error)}\n`);
|
|
3939
|
+
settleOnceIdle(() => 1);
|
|
3940
|
+
});
|
|
3941
|
+
const clientProcessId = streams.clientProcessId;
|
|
3942
|
+
if (clientProcessId !== void 0) {
|
|
3943
|
+
const settleIfClientGone = () => {
|
|
3944
|
+
if (!processAlive(clientProcessId)) settle(departureCode());
|
|
3945
|
+
};
|
|
3946
|
+
clientWatch = setInterval(settleIfClientGone, clientProcessPollMs);
|
|
3947
|
+
clientWatch.unref();
|
|
3948
|
+
settleIfClientGone();
|
|
3949
|
+
}
|
|
3950
|
+
function settleOnAbort() {
|
|
3951
|
+
settleOnceIdle(departureCode);
|
|
3952
|
+
abortDeadline ??= setTimeout(() => settle(departureCode()), abortDrainDeadlineMs);
|
|
3953
|
+
abortDeadline.unref();
|
|
3954
|
+
}
|
|
3955
|
+
const hostShutdown = streams.signal;
|
|
3956
|
+
if (hostShutdown?.aborted === true) settleOnAbort();
|
|
3957
|
+
else hostShutdown?.addEventListener("abort", settleOnAbort, { once: true });
|
|
3958
|
+
});
|
|
3959
|
+
}
|
|
3960
|
+
function messageOf(error) {
|
|
3961
|
+
return error instanceof Error ? error.message : String(error);
|
|
3962
|
+
}
|
|
3963
|
+
function startServer(streams) {
|
|
3964
|
+
if (streams === void 0) {
|
|
3965
|
+
createServer(createConnection$1(ProposedFeatures$1.all));
|
|
3966
|
+
return;
|
|
3967
|
+
}
|
|
3968
|
+
return runServerOverStreams(streams);
|
|
3969
|
+
}
|
|
3970
|
+
//#endregion
|
|
3971
|
+
export { startServer };
|
|
3972
|
+
|
|
3973
|
+
//# sourceMappingURL=exports-CKgwcXbp.mjs.map
|