From e75997377b0a2814bf9e8b1d1d38394c816c90a6 Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Fri, 21 Aug 2026 12:28:11 -0400 Subject: [PATCH 01/21] Fix ServerSpec | undefined type safety and wire up TS project references - Fix getServerSpec and ProtocolMethods resolveFromUri to return ServerSpec | undefined - Add guards at all getServerSpec call sites across providers - Fix resolveServerSpec in client to avoid non-null assertion - Add TS project references for common from client/server/root - Update clean script to remove tsbuildinfo files - Rename deprecated typescript.* settings to js/ts.* --- .vscode/settings.json | 7 +++++-- client/src/extension.ts | 9 ++++++--- client/tsconfig.json | 6 ++++++ common/src/types.ts | 2 +- common/tsconfig.json | 1 + package.json | 2 +- server/src/providers/completion.ts | 15 ++++++++++++--- server/src/providers/definition.ts | 5 ++++- server/src/providers/diagnostic.ts | 3 ++- server/src/providers/documentLink.ts | 5 ++++- server/src/providers/formatting.ts | 5 ++++- server/src/providers/hover.ts | 5 ++++- server/src/providers/refactoring.ts | 20 ++++++++++++++++---- server/src/providers/signatureHelp.ts | 5 ++++- server/src/providers/typeDefinition.ts | 7 +++++-- server/src/providers/typeHierarchy.ts | 5 ++++- server/src/utils/functions.ts | 7 +++++-- server/src/utils/types.ts | 2 +- server/src/utils/variables.ts | 11 ++++++++--- server/tsconfig.json | 8 +++++++- tsconfig.json | 3 +++ 21 files changed, 103 insertions(+), 30 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 28eddc1..7038c07 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,6 +1,9 @@ { "editor.insertSpaces": false, "tslint.enable": true, - "typescript.tsc.autoDetect": "off", - "typescript.preferences.quoteStyle": "single" + "js/ts.tsc.autoDetect": "off", + "js/ts.preferences.quoteStyle": "single", + "objectscript.conn": { + "active": false + } } \ No newline at end of file diff --git a/client/src/extension.ts b/client/src/extension.ts index 767513e..626b625 100644 --- a/client/src/extension.ts +++ b/client/src/extension.ts @@ -164,9 +164,12 @@ export async function activate(context: ExtensionContext) { // Resolve the ServerSpec for a document or workspace folder URI, prompting // for a missing password via the Server Manager's authentication provider. - async function resolveServerSpec(uri: Uri) { + async function resolveServerSpec(uri: Uri): Promise { const wsFolderUriString = workspace.getWorkspaceFolder(uri)?.uri.toString(); - const serverSpec = objectScriptApi.serverForUri(uri)!; + const serverSpec = objectScriptApi.serverForUri(uri); + if (serverSpec === undefined) { + return undefined; + } const auth = serverSpec.auth ?? new BasicAuthorization(serverSpec.username, serverSpec.password); if ( // Server was resolved @@ -234,7 +237,7 @@ export async function activate(context: ExtensionContext) { for (const f of workspace.workspaceFolders ?? []) { try { const serverSpec = await resolveServerSpec(f.uri); - if (serverSpec.active) { + if (serverSpec?.active) { await makeRESTRequest("HEAD", 1, "", serverSpec); } } catch { diff --git a/client/tsconfig.json b/client/tsconfig.json index 479c618..db61596 100644 --- a/client/tsconfig.json +++ b/client/tsconfig.json @@ -7,7 +7,13 @@ "rootDir": "src", "sourceMap": true, "strictNullChecks": true, + "skipLibCheck": true, }, + "references": [ + { + "path": "../common" + } + ], "include": ["src"], "exclude": ["node_modules", ".vscode-test"] } diff --git a/common/src/types.ts b/common/src/types.ts index 34a0c7b..19a03b1 100644 --- a/common/src/types.ts +++ b/common/src/types.ts @@ -37,7 +37,7 @@ export interface GetTextParams { } export interface ProtocolMethods { - "intersystems/server/resolveFromUri": (_: string) => Promise; + "intersystems/server/resolveFromUri": (_: string) => Promise; "intersystems/uri/localToVirtual": (_: string) => string; "intersystems/uri/forDocument": (_: string) => string | null; "intersystems/uri/forTypeHierarchyClasses": (_: string[]) => string[]; diff --git a/common/tsconfig.json b/common/tsconfig.json index f973a88..5a05aeb 100644 --- a/common/tsconfig.json +++ b/common/tsconfig.json @@ -8,6 +8,7 @@ "sourceMap": true, "declaration": true, "declarationMap": true, + "composite": true, "strict": true, "esModuleInterop": true, "skipLibCheck": true, diff --git a/package.json b/package.json index 241033d..718d2bf 100644 --- a/package.json +++ b/package.json @@ -1790,7 +1790,7 @@ "compile": "npm run compile:common && tsc -b", "compile:common": "cd common && npm run compile", "watch": "tsc -b -w", - "clean": "rimraf client/out && rimraf server/out && rimraf common/out", + "clean": "rimraf client/out && rimraf server/out && rimraf common/out && rimraf common/tsconfig.tsbuildinfo && rimraf client/tsconfig.tsbuildinfo && rimraf server/tsconfig.tsbuildinfo && rimraf tsconfig.tsbuildinfo", "lint": "eslint && prettier --check .", "lint-fix": "prettier --write . && eslint --fix", "postinstall": "cd client && npm install && cd ../server && npm install && cd ../common && npm install && cd .." diff --git a/server/src/providers/completion.ts b/server/src/providers/completion.ts index aa960cc..78edea8 100644 --- a/server/src/providers/completion.ts +++ b/server/src/providers/completion.ts @@ -790,7 +790,10 @@ export async function onCompletion(params: CompletionParams): Promise { if (Array.isArray(item.data) && item.data[0] === "class") { // Get the description for this class from the server - const server: ServerSpec = await getServerSpec(item.data[2]); + const server = await getServerSpec(item.data[2]); + if (!server) { + return item; + } const querydata: QueryData = { query: "SELECT Description FROM %Dictionary.ClassDefinition WHERE Name = ?", parameters: [item.data[1]], @@ -2445,7 +2451,10 @@ export async function onCompletionResolve(item: CompletionItem): Promise { - const server: ServerSpec = await getServerSpec(params.uri); + const server = await getServerSpec(params.uri); + if (!server) { + return []; + } const result: QuickPickItem[] = []; const classname: string = params.classmame; @@ -730,7 +739,10 @@ export async function addMethod(params: AddMethodParams): Promise= 4) { comma = ", \n" + tab; } diff --git a/server/src/providers/signatureHelp.ts b/server/src/providers/signatureHelp.ts index a3bffb0..edd99b3 100644 --- a/server/src/providers/signatureHelp.ts +++ b/server/src/providers/signatureHelp.ts @@ -170,7 +170,10 @@ export async function onSignatureHelp(params: SignatureHelpParams): Promise { const doc = documents.get(params.textDocument.uri); if (doc === undefined) { return null; @@ -24,7 +24,10 @@ export async function onTypeDefinition(params: TextDocumentPositionParams) { if (parsed === undefined) { return null; } - const server: ServerSpec = await getServerSpec(params.textDocument.uri); + const server = await getServerSpec(params.textDocument.uri); + if (!server) { + return + } if (parsed[params.position.line] === undefined) { // This is the blank last line of the file diff --git a/server/src/providers/typeHierarchy.ts b/server/src/providers/typeHierarchy.ts index 9ebeb32..8b565b3 100644 --- a/server/src/providers/typeHierarchy.ts +++ b/server/src/providers/typeHierarchy.ts @@ -32,7 +32,10 @@ export async function onPrepare(params: TypeHierarchyPrepareParams): Promise { +export async function getServerSpec(uri: string): Promise { const spec = serverSpecs.get(uri); if (spec !== undefined) { return spec; } - const newspec: ServerSpec = await connection.sendRequest("intersystems/server/resolveFromUri", uri); + const newspec = await connection.sendRequest("intersystems/server/resolveFromUri", uri); + if (newspec === undefined) { + return + } serverSpecs.set(uri, newspec); return newspec; } diff --git a/server/src/utils/types.ts b/server/src/utils/types.ts index ad81810..570207f 100644 --- a/server/src/utils/types.ts +++ b/server/src/utils/types.ts @@ -109,7 +109,7 @@ export type KeywordDoc = { constraint?: string | string[]; }; -export type { ServerSpec } from "../../../common/out/types"; +export type { ProtocolMethods, ServerSpec } from "../../../common/out/types"; /** * Context of the method/routine that a macro is in, including extra information needed for macro expansion. diff --git a/server/src/utils/variables.ts b/server/src/utils/variables.ts index 55cd5be..d0cd6e0 100644 --- a/server/src/utils/variables.ts +++ b/server/src/utils/variables.ts @@ -1,6 +1,6 @@ -import { createConnection, SemanticTokensBuilder, TextDocuments } from "vscode-languageserver/node"; +import { Connection, createConnection, SemanticTokensBuilder, TextDocuments } from "vscode-languageserver/node"; import { TextDocument } from "vscode-languageserver-textdocument"; -import { compressedline, LanguageServerConfiguration, ServerSpec } from "./types"; +import { compressedline, LanguageServerConfiguration, ProtocolMethods, ServerSpec } from "./types"; /** * TextDocument URI's mapped to the tokenized representation of the document. @@ -10,7 +10,12 @@ export const parsedDocuments: Map = new Ma /** * Node IPC connection between the server and client. */ -export const connection = createConnection(); +export const connection: Omit & { + sendRequest( + method: K, + params: Parameters[0], + ): Promise>>; +} = createConnection(); /** * TextDocument manager. diff --git a/server/tsconfig.json b/server/tsconfig.json index 9326bc7..2c2e5d2 100644 --- a/server/tsconfig.json +++ b/server/tsconfig.json @@ -11,8 +11,14 @@ "noImplicitAny": false, "resolveJsonModule": true, "esModuleInterop": true, - "allowJs": true + "allowJs": true, + "skipLibCheck": true }, + "references": [ + { + "path": "../common" + } + ], "include": ["src"], "exclude": ["node_modules", ".vscode-test"] } diff --git a/tsconfig.json b/tsconfig.json index e5aa540..193ee96 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,6 +1,9 @@ { "files": [], "references": [ + { + "path": "./common" + }, { "path": "./client" }, From 399087619911820759e7497540a7d6d232adfc34 Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Fri, 21 Aug 2026 12:40:08 -0400 Subject: [PATCH 02/21] Add explicit parens around server && normalizeClassname() in diagnostic.ts --- server/src/providers/diagnostic.ts | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/server/src/providers/diagnostic.ts b/server/src/providers/diagnostic.ts index c4711c6..4debcd9 100644 --- a/server/src/providers/diagnostic.ts +++ b/server/src/providers/diagnostic.ts @@ -61,7 +61,6 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise = new Map(); // Keep track of current namespace for class/routine existence checks - const baseNs = server.namespace.toUpperCase(); + const baseNs = (server?.namespace ?? "").toUpperCase(); let currentNs = baseNs; let nsNestedBlockLevel = 0; const validNsRegex = /^"[A-Za-z%]?[A-Za-z0-9-_]+"$/; @@ -762,7 +761,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise 0) { // The class couldn't be resolved with the imports @@ -908,8 +907,8 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise 0) { // We got data back @@ -1419,7 +1418,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise 0) { // We got data back From 77905ad626bf4e0adb2021d650ef974312cff0c8 Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Fri, 21 Aug 2026 13:58:32 -0400 Subject: [PATCH 03/21] save --- client/src/extension.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/client/src/extension.ts b/client/src/extension.ts index 8d7e5c0..a2b8c89 100644 --- a/client/src/extension.ts +++ b/client/src/extension.ts @@ -164,10 +164,13 @@ export async function activate(context: ExtensionContext) { // Resolve the ServerSpec for a document or workspace folder URI, prompting // for a missing password via the Server Manager's authentication provider. - async function resolveServerSpec(uri: Uri): Promise { + async function resolveServerSpec(uri: Uri): Promise { try { const wsFolderUriString = workspace.getWorkspaceFolder(uri)?.uri.toString(); - const serverSpec = objectScriptApi.serverForUri(uri)!; + const serverSpec = objectScriptApi.serverForUri(uri); + if (serverSpec === undefined) { + return + } const auth = serverSpec.auth ?? new BasicAuthorization(serverSpec.username, serverSpec.password); if ( // Server was resolved @@ -250,7 +253,7 @@ export async function activate(context: ExtensionContext) { for (const f of workspace.workspaceFolders ?? []) { try { const serverSpec = await resolveServerSpec(f.uri); - if (serverSpec.active) { + if (serverSpec?.active) { await makeRESTRequest("HEAD", 0, "", serverSpec); } } catch { From 3c0a9a07c920371a33358fae442c7982a61c944f Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Fri, 21 Aug 2026 14:28:07 -0400 Subject: [PATCH 04/21] clean up --- .vscode/settings.json | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 7038c07..f91b6a6 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -2,8 +2,5 @@ "editor.insertSpaces": false, "tslint.enable": true, "js/ts.tsc.autoDetect": "off", - "js/ts.preferences.quoteStyle": "single", - "objectscript.conn": { - "active": false - } + "js/ts.preferences.quoteStyle": "single" } \ No newline at end of file From 068d733be8cea4ae8eca782b654bfb28b056a75c Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Fri, 21 Aug 2026 15:09:36 -0400 Subject: [PATCH 05/21] fix --- server/src/providers/diagnostic.ts | 2028 ++++++++++++++-------------- server/src/providers/hover.ts | 66 +- 2 files changed, 1049 insertions(+), 1045 deletions(-) diff --git a/server/src/providers/diagnostic.ts b/server/src/providers/diagnostic.ts index 4debcd9..a302f15 100644 --- a/server/src/providers/diagnostic.ts +++ b/server/src/providers/diagnostic.ts @@ -165,7 +165,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise = new Map(); const classes: Map = new Map(); - // Keep track of current namespace for class/routine existence checks - const baseNs = (server?.namespace ?? "").toUpperCase(); - let currentNs = baseNs; - let nsNestedBlockLevel = 0; - const validNsRegex = /^"[A-Za-z%]?[A-Za-z0-9-_]+"$/; + if (server) { + // Keep track of current namespace for class/routine existence checks + const baseNs = server.namespace.toUpperCase(); + let currentNs = baseNs; + let nsNestedBlockLevel = 0; + const validNsRegex = /^"[A-Za-z%]?[A-Za-z0-9-_]+"$/; - // Store the ns, name and ranges of all classes and routines from other namespaces that we see - // Keys are of the form "ns:::doc.ext" - const otherNsDocs: Map = new Map(); + // Store the ns, name and ranges of all classes and routines from other namespaces that we see + // Keys are of the form "ns:::doc.ext" + const otherNsDocs: Map = new Map(); - // We need to know if the last syntax error token was whitespace so we don't - // try to combine error tokens that aren't for the same underlying error. - let lastErrWasWhitespace = false; + // We need to know if the last syntax error token was whitespace so we don't + // try to combine error tokens that aren't for the same underlying error. + let lastErrWasWhitespace = false; - // Don't report diagnostics in a #if 0 block, and - // mark all of the code in the block as "unused" - let ifZeroStartPos: Position | undefined; - const ifZeroStart = /^\s*#if\s+(?:0|"0")(?:$|\s)/i; - const ifZeroEnd = /^\s*#elseif\s+|(?:#else|#endif)(?:$|\s)/i; + // Don't report diagnostics in a #if 0 block, and + // mark all of the code in the block as "unused" + let ifZeroStartPos: Position | undefined; + const ifZeroStart = /^\s*#if\s+(?:0|"0")(?:$|\s)/i; + const ifZeroEnd = /^\s*#elseif\s+|(?:#else|#endif)(?:$|\s)/i; - // Loop through the parsed document to find errors and warnings - for (let i = startline; i < parsed.length; i++) { - if (!parsed[i]?.length) continue; + // Loop through the parsed document to find errors and warnings + for (let i = startline; i < parsed.length; i++) { + if (!parsed[i]?.length) continue; - const lineText = doc.getText(Range.create(i, 0, i + 1, 0)); - if (doc.languageId != "objectscript-int" && !ifZeroStartPos) { - const ifZeroStartMatch = lineText.match(ifZeroStart); - if (ifZeroStartMatch) { - ifZeroStartPos = Position.create(i, ifZeroStartMatch[0].length); + const lineText = doc.getText(Range.create(i, 0, i + 1, 0)); + if (doc.languageId != "objectscript-int" && !ifZeroStartPos) { + const ifZeroStartMatch = lineText.match(ifZeroStart); + if (ifZeroStartMatch) { + ifZeroStartPos = Position.create(i, ifZeroStartMatch[0].length); + continue; // No more diagnostics on this line + } + } else if (ifZeroStartPos && ifZeroEnd.test(lineText)) { + if (i > ifZeroStartPos.line + 1) + diagnostics.push({ + severity: DiagnosticSeverity.Hint, + range: Range.create(ifZeroStartPos, Position.create(i, 0)), + message: "Unused code detected", + tags: [DiagnosticTag.Unnecessary], + source: "InterSystems Language Server", + }); + ifZeroStartPos = undefined; continue; // No more diagnostics on this line } - } else if (ifZeroStartPos && ifZeroEnd.test(lineText)) { - if (i > ifZeroStartPos.line + 1) - diagnostics.push({ - severity: DiagnosticSeverity.Hint, - range: Range.create(ifZeroStartPos, Position.create(i, 0)), - message: "Unused code detected", - tags: [DiagnosticTag.Unnecessary], - source: "InterSystems Language Server", - }); - ifZeroStartPos = undefined; - continue; // No more diagnostics on this line - } - // Loop through the line's tokens - for (let j = 0; j < parsed[i].length; j++) { - const symbolstart: number = parsed[i][j].p; - const symbolend: number = parsed[i][j].p + parsed[i][j].c; + // Loop through the line's tokens + for (let j = 0; j < parsed[i].length; j++) { + const symbolstart: number = parsed[i][j].p; + const symbolend: number = parsed[i][j].p + parsed[i][j].c; - if (j > 0 && parsed[i][j].l === parsed[i][j - 1].l && parsed[i][j].s === parsed[i][j - 1].s && !ifZeroStartPos) { - // This token is the same as the last + if (j > 0 && parsed[i][j].l === parsed[i][j - 1].l && parsed[i][j].s === parsed[i][j - 1].s && !ifZeroStartPos) { + // This token is the same as the last - if (parsed[i][j].s === ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { - const errorDesc = normalizeErrorDesc(parsed[i][j].e); - const errorRange = Range.create(i, symbolstart, i, symbolend); - if (doc.getText(errorRange).trim()) { - if ( - !lastErrWasWhitespace && - parsed[i][j].l == parsed[i][j - 1].l && - diagnostics.length && - [syntaxError, diagnostics[diagnostics.length - 1].message].includes(errorDesc) - ) { - // This error token is a continuation of the same underlying error - diagnostics[diagnostics.length - 1].range.end = Position.create(i, symbolend); - } else { - // This is a token for a new error + if (parsed[i][j].s === ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { + const errorDesc = normalizeErrorDesc(parsed[i][j].e); + const errorRange = Range.create(i, symbolstart, i, symbolend); + if (doc.getText(errorRange).trim()) { + if ( + !lastErrWasWhitespace && + parsed[i][j].l == parsed[i][j - 1].l && + diagnostics.length && + [syntaxError, diagnostics[diagnostics.length - 1].message].includes(errorDesc) + ) { + // This error token is a continuation of the same underlying error + diagnostics[diagnostics.length - 1].range.end = Position.create(i, symbolend); + } else { + // This is a token for a new error + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: { + start: Position.create(i, symbolstart), + end: Position.create(i, symbolend), + }, + message: errorDesc, + source: "InterSystems Language Server", + }); + } + } + lastErrWasWhitespace = false; + } else { + lastErrWasWhitespace = true; + } + } else { + if (parsed[i][j].s === ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l) && !ifZeroStartPos) { + // This is an error token + const errorRange = Range.create(i, symbolstart, i, symbolend); + // Don't create a diagnostic for this error if it's just whitespace. + // This can happen because the parsers can report a syntax error token + // that spans only whitespace, and it won't be filtered out + // at the parser level since it's an error token. + if (doc.getText(errorRange).trim()) { diagnostics.push({ severity: DiagnosticSeverity.Error, - range: { - start: Position.create(i, symbolstart), - end: Position.create(i, symbolend), - }, - message: errorDesc, + range: errorRange, + message: normalizeErrorDesc(parsed[i][j].e), source: "InterSystems Language Server", }); + lastErrWasWhitespace = false; + } else { + lastErrWasWhitespace = true; } - } - lastErrWasWhitespace = false; - } else { - lastErrWasWhitespace = true; - } - } else { - if (parsed[i][j].s === ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l) && !ifZeroStartPos) { - // This is an error token - const errorRange = Range.create(i, symbolstart, i, symbolend); - // Don't create a diagnostic for this error if it's just whitespace. - // This can happen because the parsers can report a syntax error token - // that spans only whitespace, and it won't be filtered out - // at the parser level since it's an error token. - if (doc.getText(errorRange).trim()) { + } else if ( + parsed[i][j].l == ld.cos_langindex && + parsed[i][j].s == ld.cos_otw_attrindex && + settings.diagnostics.undefinedVariables && + !ifZeroStartPos + ) { + // This is an OptionTrackWarning (unset local variable) + const varrange = Range.create(Position.create(i, symbolstart), Position.create(i, symbolend)); diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: errorRange, - message: normalizeErrorDesc(parsed[i][j].e), + severity: DiagnosticSeverity.Warning, + range: varrange, + message: `Local variable "${doc.getText(varrange)}" may be undefined`, source: "InterSystems Language Server", }); - lastErrWasWhitespace = false; - } else { - lastErrWasWhitespace = true; - } - } else if ( - parsed[i][j].l == ld.cos_langindex && - parsed[i][j].s == ld.cos_otw_attrindex && - settings.diagnostics.undefinedVariables && - !ifZeroStartPos - ) { - // This is an OptionTrackWarning (unset local variable) - const varrange = Range.create(Position.create(i, symbolstart), Position.create(i, symbolend)); - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: varrange, - message: `Local variable "${doc.getText(varrange)}" may be undefined`, - source: "InterSystems Language Server", - }); - } else if ( - parsed[i][j].l == ld.cls_langindex && - parsed[i][j].s == ld.cls_clsname_attrindex && - j !== 0 && - parsed[i][j - 1].l == ld.cls_langindex && - parsed[i][j - 1].s == ld.cls_keyword_attrindex && - doc.getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)).toLowerCase() === + } else if ( + parsed[i][j].l == ld.cls_langindex && + parsed[i][j].s == ld.cls_clsname_attrindex && + j !== 0 && + parsed[i][j - 1].l == ld.cls_langindex && + parsed[i][j - 1].s == ld.cls_keyword_attrindex && + doc.getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)).toLowerCase() === "class" - ) { - // This is the class name in the class definition line + ) { + // This is the class name in the class definition line - // Check if the class name has a package - const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); - const word = doc.getText(wordrange); - if (!word.includes(".")) { - // The class name doesn't have a package, so report an error diagnostic here - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: wordrange, - message: "A package must be specified", - source: "InterSystems Language Server", - }); - } else if (isPersistent) { - // Check if a SqlTableName is present - let sqlTableName: Range | undefined, - hasSqlTableName = false; - for (let k = j + 1; k < parsed[i].length; k++) { - if (hasSqlTableName) { - if ( + // Check if the class name has a package + const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); + const word = doc.getText(wordrange); + if (!word.includes(".")) { + // The class name doesn't have a package, so report an error diagnostic here + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: wordrange, + message: "A package must be specified", + source: "InterSystems Language Server", + }); + } else if (isPersistent) { + // Check if a SqlTableName is present + let sqlTableName: Range | undefined, + hasSqlTableName = false; + for (let k = j + 1; k < parsed[i].length; k++) { + if (hasSqlTableName) { + if ( + parsed[i][k].l == ld.cls_langindex && + (parsed[i][k].s == ld.cls_sqliden_attrindex || + parsed[i][k].s == ld.error_attrindex || + (parsed[i][k].s == ld.cls_delim_attrindex && + [",", "]"].includes( + doc.getText(Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c)), + ))) + ) { + if (parsed[i][k].s == ld.cls_sqliden_attrindex) { + sqlTableName = Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c); + } + break; + } + } else if ( parsed[i][k].l == ld.cls_langindex && - (parsed[i][k].s == ld.cls_sqliden_attrindex || - parsed[i][k].s == ld.error_attrindex || - (parsed[i][k].s == ld.cls_delim_attrindex && - [",", "]"].includes( - doc.getText(Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c)), - ))) + parsed[i][k].s == ld.cls_keyword_attrindex && + doc.getText(Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c)).toLowerCase() == + "sqltablename" ) { - if (parsed[i][k].s == ld.cls_sqliden_attrindex) { - sqlTableName = Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c); - } - break; + hasSqlTableName = true; } - } else if ( - parsed[i][k].l == ld.cls_langindex && - parsed[i][k].s == ld.cls_keyword_attrindex && - doc.getText(Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c)).toLowerCase() == - "sqltablename" - ) { - hasSqlTableName = true; } - } - if (hasSqlTableName) { - if (sqlTableName && sqlReservedWords.includes(doc.getText(sqlTableName).toUpperCase())) { - // The SqlTableName is a reserved word + if (hasSqlTableName) { + if (sqlTableName && sqlReservedWords.includes(doc.getText(sqlTableName).toUpperCase())) { + // The SqlTableName is a reserved word + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: sqlTableName, + message: "SqlTableName is a SQL reserved word", + source: "InterSystems Language Server", + }); + } + } else if (sqlReservedWords.includes(word.split(".").pop()!.toUpperCase())) { + // The short class name is a reserved word, and it's not corrected by a SqlTableName + wordrange.start.character = wordrange.end.character - word.split(".").pop()!.length; diagnostics.push({ severity: DiagnosticSeverity.Warning, - range: sqlTableName, - message: "SqlTableName is a SQL reserved word", + range: wordrange, + message: "Class name is a SQL reserved word", source: "InterSystems Language Server", }); } - } else if (sqlReservedWords.includes(word.split(".").pop()!.toUpperCase())) { - // The short class name is a reserved word, and it's not corrected by a SqlTableName - wordrange.start.character = wordrange.end.character - word.split(".").pop()!.length; - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: wordrange, - message: "Class name is a SQL reserved word", - source: "InterSystems Language Server", - }); } - } - } else if ( - j === 0 && - parsed[i][j].l == ld.cls_langindex && - parsed[i][j].s == ld.cls_keyword_attrindex && - doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase() === + } else if ( + j === 0 && + parsed[i][j].l == ld.cls_langindex && + parsed[i][j].s == ld.cls_keyword_attrindex && + doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase() === "parameter" && - settings.diagnostics.parameters - ) { - // This line is a UDL Parameter definition - - const endsWithSemi = - parsed[i][parsed[i].length - 1].l == ld.cls_langindex && - parsed[i][parsed[i].length - 1].s == ld.cls_delim_attrindex && - doc.getText( - Range.create( - i, - parsed[i][parsed[i].length - 1].p, - i, - parsed[i][parsed[i].length - 1].p + parsed[i][parsed[i].length - 1].c, - ), - ) == ";"; - if ( - isPersistent && - parsed[i].length > 3 && - doc.getText(Range.create(i, parsed[i][1].p, i, parsed[i][1].p + parsed[i][1].c)) == "DEFAULTGLOBAL" + settings.diagnostics.parameters ) { - // Check if the provided value is a valid global name, with leading caret - let inKeywords = false; - for (let tkn = 2; tkn < parsed[i].length; tkn++) { - if (parsed[i][tkn].l == ld.cls_langindex && parsed[i][tkn].s == ld.cls_delim_attrindex) { - const delim = doc.getText(Range.create(i, parsed[i][tkn].p, i, parsed[i][tkn].p + parsed[i][tkn].c)); - if (inKeywords && delim == "]") { - inKeywords = false; - } else if (!inKeywords && delim == "[") { - inKeywords = true; - } else if (!inKeywords && delim == "=" && tkn < parsed[i].length - 1) { + // This line is a UDL Parameter definition + + const endsWithSemi = + parsed[i][parsed[i].length - 1].l == ld.cls_langindex && + parsed[i][parsed[i].length - 1].s == ld.cls_delim_attrindex && + doc.getText( + Range.create( + i, + parsed[i][parsed[i].length - 1].p, + i, + parsed[i][parsed[i].length - 1].p + parsed[i][parsed[i].length - 1].c, + ), + ) == ";"; + if ( + isPersistent && + parsed[i].length > 3 && + doc.getText(Range.create(i, parsed[i][1].p, i, parsed[i][1].p + parsed[i][1].c)) == "DEFAULTGLOBAL" + ) { + // Check if the provided value is a valid global name, with leading caret + let inKeywords = false; + for (let tkn = 2; tkn < parsed[i].length; tkn++) { + if (parsed[i][tkn].l == ld.cls_langindex && parsed[i][tkn].s == ld.cls_delim_attrindex) { + const delim = doc.getText(Range.create(i, parsed[i][tkn].p, i, parsed[i][tkn].p + parsed[i][tkn].c)); + if (inKeywords && delim == "]") { + inKeywords = false; + } else if (!inKeywords && delim == "[") { + inKeywords = true; + } else if (!inKeywords && delim == "=" && tkn < parsed[i].length - 1) { + const valueEndTkn = parsed[i].length - (endsWithSemi ? 2 : 1); + const valueRange = Range.create( + i, + parsed[i][tkn + 1].p, + i, + parsed[i][valueEndTkn].p + parsed[i][valueEndTkn].c, + ); + const valueText = doc.getText(valueRange); + if ( + !valueText.startsWith("{") && + !/^"\^[%\x41-\xFF]([\x41-\xFF\d.]*[\x41-\xFF\d])?"$/.test(valueText) + ) { + // The value is neither a valid global name nor a compile-time expression + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: valueRange, + message: "DEFAULTGLOBAL Parameter value should be a valid global name prefixed by a caret", + source: "InterSystems Language Server", + }); + } + break; + } + } + } + } + if ( + parsed[i].length > 3 && + parsed[i][2].l == ld.cls_langindex && + parsed[i][2].s === ld.cls_keyword_attrindex && + doc.getText(Range.create(i, parsed[i][2].p, i, parsed[i][2].p + parsed[i][2].c)).toLowerCase() === "as" + ) { + // This Parameter has a type + const tokenrange = Range.create(i, parsed[i][3].p, i, parsed[i][3].p + parsed[i][3].c); + const tokentext = doc.getText(tokenrange).toUpperCase(); + const thistypedoc = parameterTypes.find((typedoc) => typedoc.name === tokentext); + if (thistypedoc === undefined) { + // The type is invalid + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: tokenrange, + message: "Invalid parameter type", + source: "InterSystems Language Server", + }); + } else if (parsed[i].length > 4) { + // The type is valid + + // See if this Parameter has a value + let valuetkn: number | undefined; + const delimtext = doc.getText(Range.create(i, parsed[i][4].p, i, parsed[i][4].p + parsed[i][4].c)); + if (delimtext === "[") { + // Loop through the line to find the closing brace + let closingtkn: number | undefined; + for (let ptkn = 5; ptkn < parsed[i].length; ptkn++) { + if ( + parsed[i][ptkn].l == ld.cls_langindex && + parsed[i][ptkn].s === ld.cls_delim_attrindex && + doc.getText(Range.create(i, parsed[i][ptkn].p, i, parsed[i][ptkn].p + parsed[i][ptkn].c)) === "]" + ) { + closingtkn = ptkn; + break; + } + } + // Check if the token following the closing brace is = + if ( + closingtkn && + parsed[i].length > closingtkn && + doc.getText( + Range.create( + i, + parsed[i][closingtkn + 1].p, + i, + parsed[i][closingtkn + 1].p + parsed[i][closingtkn + 1].c, + ), + ) === "=" + ) { + // There is a value following the = + valuetkn = closingtkn + 2; + } + } else if (delimtext === "=") { + // The value follows this delimiter + valuetkn = 5; + } else { + // Delimiter is a ; so there isn't a value to evaluate + } + + if (valuetkn && parsed[i].length > valuetkn + 1) { const valueEndTkn = parsed[i].length - (endsWithSemi ? 2 : 1); - const valueRange = Range.create( + const valtext = doc.getText( + Range.create(i, parsed[i][valuetkn].p, i, parsed[i][valuetkn].p + parsed[i][valuetkn].c), + ); + const valrange = Range.create( i, - parsed[i][tkn + 1].p, + parsed[i][valuetkn].p, i, parsed[i][valueEndTkn].p + parsed[i][valueEndTkn].c, ); - const valueText = doc.getText(valueRange); if ( - !valueText.startsWith("{") && - !/^"\^[%\x41-\xFF]([\x41-\xFF\d.]*[\x41-\xFF\d])?"$/.test(valueText) + (thistypedoc.name === "STRING" && + (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || + (thistypedoc.name === "COSEXPRESSION" && + (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || + (thistypedoc.name === "CLASSNAME" && + (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || + (thistypedoc.name === "INTEGER" && + (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_num_attrindex)) || + (thistypedoc.name === "BOOLEAN" && + (parsed[i][valuetkn].l !== ld.cls_langindex || + parsed[i][valuetkn].s !== ld.cls_num_attrindex || + (valtext !== "1" && valtext !== "0"))) ) { - // The value is neither a valid global name nor a compile-time expression - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: valueRange, - message: "DEFAULTGLOBAL Parameter value should be a valid global name prefixed by a caret", - source: "InterSystems Language Server", - }); + // Allow curly brace syntax for all types but COSEXPRESSION + if (thistypedoc.name == "COSEXPRESSION" || !valtext.startsWith("{")) { + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: valrange, + message: "Parameter value and type do not match", + source: "InterSystems Language Server", + }); + } + } else if (thistypedoc.name === "CLASSNAME" && settings.diagnostics.classes) { + // Validate the class name in the string + let classname: string = valtext.slice(1, -1); + if (classname.startsWith("%") && !classname.includes(".")) { + classname = `%Library.${classname.slice(1)}`; + } + // Check if class exists + const filtered = files.filter((file) => file.Name === classname + ".cls"); + if (filtered.length !== 1 && !classname.startsWith("%SYSTEM.")) { + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: valrange, + message: `Class "${classname}" does not exist in namespace "${baseNs}"`, + source: "InterSystems Language Server", + }); + } } - break; } } } - } - if ( - parsed[i].length > 3 && - parsed[i][2].l == ld.cls_langindex && - parsed[i][2].s === ld.cls_keyword_attrindex && - doc.getText(Range.create(i, parsed[i][2].p, i, parsed[i][2].p + parsed[i][2].c)).toLowerCase() === "as" - ) { - // This Parameter has a type - const tokenrange = Range.create(i, parsed[i][3].p, i, parsed[i][3].p + parsed[i][3].c); - const tokentext = doc.getText(tokenrange).toUpperCase(); - const thistypedoc = parameterTypes.find((typedoc) => typedoc.name === tokentext); - if (thistypedoc === undefined) { - // The type is invalid - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: tokenrange, - message: "Invalid parameter type", - source: "InterSystems Language Server", - }); - } else if (parsed[i].length > 4) { - // The type is valid - // See if this Parameter has a value - let valuetkn: number | undefined; - const delimtext = doc.getText(Range.create(i, parsed[i][4].p, i, parsed[i][4].p + parsed[i][4].c)); - if (delimtext === "[") { - // Loop through the line to find the closing brace - let closingtkn: number | undefined; - for (let ptkn = 5; ptkn < parsed[i].length; ptkn++) { - if ( - parsed[i][ptkn].l == ld.cls_langindex && - parsed[i][ptkn].s === ld.cls_delim_attrindex && - doc.getText(Range.create(i, parsed[i][ptkn].p, i, parsed[i][ptkn].p + parsed[i][ptkn].c)) === "]" - ) { - closingtkn = ptkn; - break; - } - } - // Check if the token following the closing brace is = + // Loop through the line to capture any syntax errors + for (let ptkn = 1; ptkn < parsed[i].length; ptkn++) { + if (parsed[i][ptkn].s == ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { + const errorDesc = normalizeErrorDesc(parsed[i][j].e); if ( - closingtkn && - parsed[i].length > closingtkn && - doc.getText( - Range.create( - i, - parsed[i][closingtkn + 1].p, - i, - parsed[i][closingtkn + 1].p + parsed[i][closingtkn + 1].c, - ), - ) === "=" + parsed[i][ptkn].l == parsed[i][ptkn - 1].l && + parsed[i][ptkn - 1].s == 0 && + diagnostics.length && + [syntaxError, diagnostics[diagnostics.length - 1].message].includes(errorDesc) ) { - // There is a value following the = - valuetkn = closingtkn + 2; + // This error token is a continuation of the same underlying error + diagnostics[diagnostics.length - 1].range.end = Position.create( + i, + parsed[i][ptkn].p + parsed[i][ptkn].c, + ); + } else { + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: Range.create(i, parsed[i][ptkn].p, i, parsed[i][ptkn].p + parsed[i][ptkn].c), + message: errorDesc, + source: "InterSystems Language Server", + }); } - } else if (delimtext === "=") { - // The value follows this delimiter - valuetkn = 5; - } else { - // Delimiter is a ; so there isn't a value to evaluate } + } - if (valuetkn && parsed[i].length > valuetkn + 1) { - const valueEndTkn = parsed[i].length - (endsWithSemi ? 2 : 1); - const valtext = doc.getText( - Range.create(i, parsed[i][valuetkn].p, i, parsed[i][valuetkn].p + parsed[i][valuetkn].c), - ); - const valrange = Range.create( - i, - parsed[i][valuetkn].p, + break; + } else if ( + j === 0 && + parsed[i][j].l == ld.cls_langindex && + parsed[i][j].s == ld.cls_keyword_attrindex && + doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase() === "import" + ) { + // This is the UDL Import line + + // Loop through the line and update the inheritedpackages list + let lastpkgend: number = 0; + for (let imptkn = 1; imptkn < parsed[i].length; imptkn++) { + if (parsed[i][imptkn].s == ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { + if ( + parsed[i][imptkn - 1].s == ld.error_attrindex && + !doc.getText(Range.create(i, parsed[i][imptkn].p - 1, i, parsed[i][imptkn].p)).trim() + ) { + // The previous token is an error without a space in between, so extend the existing syntax error Diagnostic to cover this token + diagnostics[diagnostics.length - 1].range.end = Position.create( + i, + parsed[i][imptkn].p + parsed[i][imptkn].c, + ); + } else { + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: Range.create(i, parsed[i][imptkn].p, i, parsed[i][imptkn].p + parsed[i][imptkn].c), + message: syntaxError, + source: "InterSystems Language Server", + }); + } + } + if (parsed[i][imptkn].l == ld.cls_langindex && parsed[i][imptkn].s == ld.cls_clsname_attrindex) { + const pkgrange = findFullRange( i, - parsed[i][valueEndTkn].p + parsed[i][valueEndTkn].c, + parsed, + imptkn, + parsed[i][imptkn].p, + parsed[i][imptkn].p + parsed[i][imptkn].c, ); + const pkg = doc.getText(pkgrange); + if (!inheritedpackages.includes(pkg)) { + inheritedpackages.push(pkg); + } if ( - (thistypedoc.name === "STRING" && - (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || - (thistypedoc.name === "COSEXPRESSION" && - (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || - (thistypedoc.name === "CLASSNAME" && - (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || - (thistypedoc.name === "INTEGER" && - (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_num_attrindex)) || - (thistypedoc.name === "BOOLEAN" && - (parsed[i][valuetkn].l !== ld.cls_langindex || - parsed[i][valuetkn].s !== ld.cls_num_attrindex || - (valtext !== "1" && valtext !== "0"))) + files.length > 0 && + settings.diagnostics.classes && + lastpkgend != pkgrange.end.character && + !files.some((f) => f.Name.startsWith(pkg + ".") && f.Name.endsWith(".cls")) ) { - // Allow curly brace syntax for all types but COSEXPRESSION - if (thistypedoc.name == "COSEXPRESSION" || !valtext.startsWith("{")) { - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: valrange, - message: "Parameter value and type do not match", - source: "InterSystems Language Server", - }); - } - } else if (thistypedoc.name === "CLASSNAME" && settings.diagnostics.classes) { - // Validate the class name in the string - let classname: string = valtext.slice(1, -1); - if (classname.startsWith("%") && !classname.includes(".")) { - classname = `%Library.${classname.slice(1)}`; - } - // Check if class exists - const filtered = files.filter((file) => file.Name === classname + ".cls"); - if (filtered.length !== 1 && !classname.startsWith("%SYSTEM.")) { - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: valrange, - message: `Class "${classname}" does not exist in namespace "${baseNs}"`, - source: "InterSystems Language Server", - }); - } + // This package does not exist + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: pkgrange, + message: `Package "${pkg}" does not exist in namespace "${baseNs}"`, + source: "InterSystems Language Server", + }); } + lastpkgend = pkgrange.end.character; } } - } - // Loop through the line to capture any syntax errors - for (let ptkn = 1; ptkn < parsed[i].length; ptkn++) { - if (parsed[i][ptkn].s == ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { - const errorDesc = normalizeErrorDesc(parsed[i][j].e); - if ( - parsed[i][ptkn].l == parsed[i][ptkn - 1].l && - parsed[i][ptkn - 1].s == 0 && - diagnostics.length && - [syntaxError, diagnostics[diagnostics.length - 1].message].includes(errorDesc) - ) { - // This error token is a continuation of the same underlying error - diagnostics[diagnostics.length - 1].range.end = Position.create( - i, - parsed[i][ptkn].p + parsed[i][ptkn].c, - ); - } else { - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: Range.create(i, parsed[i][ptkn].p, i, parsed[i][ptkn].p + parsed[i][ptkn].c), - message: errorDesc, - source: "InterSystems Language Server", - }); + break; + } else if ( + files.length > 0 && + ((parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_clsname_attrindex) || + (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_clsname_attrindex)) && + (settings.diagnostics.classes || settings.diagnostics.deprecation) && + !ifZeroStartPos + ) { + // This is a class name + + // Don't validate a class name that follows the "Class" keyword + if (j !== 0 && parsed[i][j - 1].l == ld.cls_langindex && parsed[i][j - 1].s == ld.cls_keyword_attrindex) { + // The previous token is a UDL keyword + const prevkeytext = doc + .getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)) + .toLowerCase(); + if (prevkeytext === "class") { + continue; } } - } - break; - } else if ( - j === 0 && - parsed[i][j].l == ld.cls_langindex && - parsed[i][j].s == ld.cls_keyword_attrindex && - doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase() === "import" - ) { - // This is the UDL Import line - - // Loop through the line and update the inheritedpackages list - let lastpkgend: number = 0; - for (let imptkn = 1; imptkn < parsed[i].length; imptkn++) { - if (parsed[i][imptkn].s == ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { - if ( - parsed[i][imptkn - 1].s == ld.error_attrindex && - !doc.getText(Range.create(i, parsed[i][imptkn].p - 1, i, parsed[i][imptkn].p)).trim() - ) { - // The previous token is an error without a space in between, so extend the existing syntax error Diagnostic to cover this token - diagnostics[diagnostics.length - 1].range.end = Position.create( - i, - parsed[i][imptkn].p + parsed[i][imptkn].c, - ); + // Get the full text of the selection + const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); + let word = doc.getText(wordrange); + if (word.charAt(0) === ".") { + // This might be $SYSTEM.ClassName + const prevseven = doc.getText(Range.create(i, wordrange.start.character - 7, i, wordrange.start.character)); + if (prevseven.toUpperCase() !== "$SYSTEM") { + // This classname is invalid + if (settings.diagnostics.classes) { + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: wordrange, + message: "Invalid class name", + source: "InterSystems Language Server", + }); + } + continue; } else { - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: Range.create(i, parsed[i][imptkn].p, i, parsed[i][imptkn].p + parsed[i][imptkn].c), - message: syntaxError, - source: "InterSystems Language Server", - }); + word = "%SYSTEM" + word; } } - if (parsed[i][imptkn].l == ld.cls_langindex && parsed[i][imptkn].s == ld.cls_clsname_attrindex) { - const pkgrange = findFullRange( - i, - parsed, - imptkn, - parsed[i][imptkn].p, - parsed[i][imptkn].p + parsed[i][imptkn].c, - ); - const pkg = doc.getText(pkgrange); - if (!inheritedpackages.includes(pkg)) { - inheritedpackages.push(pkg); - } - if ( - files.length > 0 && - settings.diagnostics.classes && - lastpkgend != pkgrange.end.character && - !files.some((f) => f.Name.startsWith(pkg + ".") && f.Name.endsWith(".cls")) - ) { - // This package does not exist - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: pkgrange, - message: `Package "${pkg}" does not exist in namespace "${baseNs}"`, - source: "InterSystems Language Server", - }); - } - lastpkgend = pkgrange.end.character; + if (word.charAt(0) === '"') { + // This classname is delimited with ", so strip them + word = word.slice(1, -1); } - } - break; - } else if ( - files.length > 0 && - ((parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_clsname_attrindex) || - (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_clsname_attrindex)) && - (settings.diagnostics.classes || settings.diagnostics.deprecation) && - !ifZeroStartPos - ) { - // This is a class name - - // Don't validate a class name that follows the "Class" keyword - if (j !== 0 && parsed[i][j - 1].l == ld.cls_langindex && parsed[i][j - 1].s == ld.cls_keyword_attrindex) { - // The previous token is a UDL keyword - const prevkeytext = doc - .getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)) - .toLowerCase(); - if (prevkeytext === "class") { - continue; - } - } + if (currentNs == baseNs) { + // Normalize the class name if there are imports + const possiblecls = { num: 0 }; + const normalizedname = (server && await normalizeClassname( + doc, + parsed, + word, + server, + i, + files, + possiblecls, + inheritedpackages, + )) || ""; - // Get the full text of the selection - const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); - let word = doc.getText(wordrange); - if (word.charAt(0) === ".") { - // This might be $SYSTEM.ClassName - const prevseven = doc.getText(Range.create(i, wordrange.start.character - 7, i, wordrange.start.character)); - if (prevseven.toUpperCase() !== "$SYSTEM") { - // This classname is invalid - if (settings.diagnostics.classes) { + if (normalizedname === "" && possiblecls.num > 0) { + // The class couldn't be resolved with the imports + if (settings.diagnostics.classes) { + const diagnostic: Diagnostic = { + severity: DiagnosticSeverity.Error, + range: wordrange, + message: `Class name "${word}" is ambiguous`, + source: "InterSystems Language Server", + }; + diagnostics.push(diagnostic); + } + } else { + // Check if class exists + const filtered = files.filter((file) => file.Name === normalizedname + ".cls"); + if (filtered.length !== 1) { + // Exempt %SYSTEM classes because some of them don't have ^oddDEF entries + if (settings.diagnostics.classes && !word.startsWith("%SYSTEM.")) { + const diagnostic: Diagnostic = { + severity: DiagnosticSeverity.Error, + range: wordrange, + message: `Class "${word}" does not exist in namespace "${baseNs}"`, + source: "InterSystems Language Server", + }; + diagnostics.push(diagnostic); + } + } else if (settings.diagnostics.deprecation) { + // The class exists, so add it to the map + addRangeToMapVal(classes, normalizedname, wordrange); + } + } + } else if (currentNs != "" && settings.diagnostics.classes && !word.startsWith("%SYSTEM.")) { + if (!word.includes(".") && !word.startsWith("%")) { + // Using a short class name when you may be in another namespace is bad diagnostics.push({ severity: DiagnosticSeverity.Error, range: wordrange, - message: "Invalid class name", + message: "Short class name used after a namespace switch", source: "InterSystems Language Server", }); + } else { + // Add this class to the map + addRangeToMapVal( + otherNsDocs, + `${currentNs}:::${ + !word.includes(".") && word.startsWith("%") ? `%Library.${word.slice(1)}` : word + }.cls`, + wordrange, + ); } - continue; - } else { - word = "%SYSTEM" + word; } - } - if (word.charAt(0) === '"') { - // This classname is delimited with ", so strip them - word = word.slice(1, -1); - } + } else if ( + files.length > 0 && + ((parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_rtnname_attrindex) || + (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_rtnname_attrindex)) && + settings.diagnostics.routines && + !ifZeroStartPos + ) { + // This is a routine name - if (currentNs == baseNs) { - // Normalize the class name if there are imports - const possiblecls = { num: 0 }; - const normalizedname = (server && await normalizeClassname( - doc, - parsed, - word, - server, - i, - files, - possiblecls, - inheritedpackages, - )) || ""; + // Get the full text of the selection + const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); + const word = doc.getText(wordrange); - if (normalizedname === "" && possiblecls.num > 0) { - // The class couldn't be resolved with the imports - if (settings.diagnostics.classes) { - const diagnostic: Diagnostic = { - severity: DiagnosticSeverity.Error, - range: wordrange, - message: `Class name "${word}" is ambiguous`, - source: "InterSystems Language Server", - }; - diagnostics.push(diagnostic); - } + // Determine if this is an include file + let isinc = false; + if (parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_rtnname_attrindex) { + isinc = true; } else { - // Check if class exists - const filtered = files.filter((file) => file.Name === normalizedname + ".cls"); - if (filtered.length !== 1) { - // Exempt %SYSTEM classes because some of them don't have ^oddDEF entries - if (settings.diagnostics.classes && !word.startsWith("%SYSTEM.")) { - const diagnostic: Diagnostic = { + if ( + parsed[i][j - 1].l == ld.cos_langindex && + parsed[i][j - 1].s == ld.cos_ppc_attrindex && + doc + .getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)) + .toLowerCase() === "include" + ) { + isinc = true; + } + } + + if (currentNs == baseNs) { + // Check if the routine exists + if (isinc) { + if (!files.some((file) => file.Name == word + ".inc")) { + diagnostics.push({ severity: DiagnosticSeverity.Error, range: wordrange, - message: `Class "${word}" does not exist in namespace "${baseNs}"`, + message: `Include file "${word}" does not exist in namespace "${baseNs}"`, source: "InterSystems Language Server", - }; - diagnostics.push(diagnostic); + }); + } + } else if (word.length && /^%?[\d.\p{L}]*$/u.test(word)) { + // Need validation to avoid creating a bad regex + const regex = new RegExp(`^${word.replace(/\./g, ".")}\\.(mac|int|obj)$`); + if (!files.some((file) => regex.test(file.Name))) { + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: wordrange, + message: `Routine "${word}" does not exist in namespace "${baseNs}"`, + source: "InterSystems Language Server", + }); } - } else if (settings.diagnostics.deprecation) { - // The class exists, so add it to the map - addRangeToMapVal(classes, normalizedname, wordrange); } + } else if (currentNs != "") { + // Add this document to the map + addRangeToMapVal(otherNsDocs, `${currentNs}:::${word}${isinc ? ".inc" : ".mac"}`, wordrange); } - } else if (currentNs != "" && settings.diagnostics.classes && !word.startsWith("%SYSTEM.")) { - if (!word.includes(".") && !word.startsWith("%")) { - // Using a short class name when you may be in another namespace is bad - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: wordrange, - message: "Short class name used after a namespace switch", - source: "InterSystems Language Server", - }); - } else { - // Add this class to the map - addRangeToMapVal( - otherNsDocs, - `${currentNs}:::${ - !word.includes(".") && word.startsWith("%") ? `%Library.${word.slice(1)}` : word - }.cls`, - wordrange, - ); - } - } - } else if ( - files.length > 0 && - ((parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_rtnname_attrindex) || - (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_rtnname_attrindex)) && - settings.diagnostics.routines && - !ifZeroStartPos - ) { - // This is a routine name - - // Get the full text of the selection - const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); - const word = doc.getText(wordrange); + } else if ( + files.length > 0 && + parsed[i][j].l == ld.cos_langindex && + (parsed[i][j].s == ld.cos_prop_attrindex || + parsed[i][j].s == ld.cos_method_attrindex || + parsed[i][j].s == ld.cos_attr_attrindex || + parsed[i][j].s == ld.cos_mem_attrindex) && + settings.diagnostics.deprecation + ) { + // This is a class member (property/parameter/method) - // Determine if this is an include file - let isinc = false; - if (parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_rtnname_attrindex) { - isinc = true; - } else { - if ( - parsed[i][j - 1].l == ld.cos_langindex && - parsed[i][j - 1].s == ld.cos_ppc_attrindex && - doc - .getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)) - .toLowerCase() === "include" - ) { - isinc = true; + // Get the full text of the member + const memberrange = findFullRange(i, parsed, j, symbolstart, symbolend); + let member = doc.getText(memberrange); + if (member.charAt(0) === "#") { + member = member.slice(1); } - } + const unquotedname = quoteUDLIdentifier(member, 0); - if (currentNs == baseNs) { - // Check if the routine exists - if (isinc) { - if (!files.some((file) => file.Name == word + ".inc")) { - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: wordrange, - message: `Include file "${word}" does not exist in namespace "${baseNs}"`, - source: "InterSystems Language Server", - }); - } - } else if (word.length && /^%?[\d.\p{L}]*$/u.test(word)) { - // Need validation to avoid creating a bad regex - const regex = new RegExp(`^${word.replace(/\./g, ".")}\\.(mac|int|obj)$`); - if (!files.some((file) => regex.test(file.Name))) { - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: wordrange, - message: `Routine "${word}" does not exist in namespace "${baseNs}"`, - source: "InterSystems Language Server", - }); + // Find the dot token + let dottkn = 0; + for (let tkn = 0; tkn < parsed[i].length; tkn++) { + if (parsed[i][tkn].p >= memberrange.start.character) { + break; } + dottkn = tkn; } - } else if (currentNs != "") { - // Add this document to the map - addRangeToMapVal(otherNsDocs, `${currentNs}:::${word}${isinc ? ".inc" : ".mac"}`, wordrange); - } - } else if ( - files.length > 0 && - parsed[i][j].l == ld.cos_langindex && - (parsed[i][j].s == ld.cos_prop_attrindex || - parsed[i][j].s == ld.cos_method_attrindex || - parsed[i][j].s == ld.cos_attr_attrindex || - parsed[i][j].s == ld.cos_mem_attrindex) && - settings.diagnostics.deprecation - ) { - // This is a class member (property/parameter/method) - - // Get the full text of the member - const memberrange = findFullRange(i, parsed, j, symbolstart, symbolend); - let member = doc.getText(memberrange); - if (member.charAt(0) === "#") { - member = member.slice(1); - } - const unquotedname = quoteUDLIdentifier(member, 0); - - // Find the dot token - let dottkn = 0; - for (let tkn = 0; tkn < parsed[i].length; tkn++) { - if (parsed[i][tkn].p >= memberrange.start.character) { - break; - } - dottkn = tkn; - } - - // Get the base class that this member is in - const membercontext = server && await getClassMemberContext(doc, parsed, dottkn, i, server, files, inheritedpackages); - if (membercontext && membercontext.baseclass !== "") { - // We could determine the class, so add the member to the correct map - const memberstr: string = membercontext.baseclass + ":::" + unquotedname; - if (parsed[i][j].s == ld.cos_prop_attrindex) { - // This is a parameter - addRangeToMapVal(parameters, memberstr, memberrange); - } else if (parsed[i][j].s == ld.cos_method_attrindex) { - // This is a method - addRangeToMapVal(methods, memberstr, memberrange); - } else if ( - parsed[i][j].s == ld.cos_attr_attrindex && - membercontext.baseclass !== "%Library.DynamicArray" && - membercontext.baseclass !== "%Library.DynamicObject" - ) { - // This is a non-JSON property - addRangeToMapVal(properties, memberstr, memberrange); - } else if (parsed[i][j].s == ld.cos_mem_attrindex) { - // This is a generic member + // Get the base class that this member is in + const membercontext = server && await getClassMemberContext(doc, parsed, dottkn, i, server, files, inheritedpackages); + if (membercontext && membercontext.baseclass !== "") { + // We could determine the class, so add the member to the correct map - if (membercontext.baseclass.startsWith("%SYSTEM.")) { - // This is always a method - addRangeToMapVal(methods, memberstr, memberrange); - } else { - // This can be a method or property + const memberstr: string = membercontext.baseclass + ":::" + unquotedname; + if (parsed[i][j].s == ld.cos_prop_attrindex) { + // This is a parameter + addRangeToMapVal(parameters, memberstr, memberrange); + } else if (parsed[i][j].s == ld.cos_method_attrindex) { + // This is a method addRangeToMapVal(methods, memberstr, memberrange); + } else if ( + parsed[i][j].s == ld.cos_attr_attrindex && + membercontext.baseclass !== "%Library.DynamicArray" && + membercontext.baseclass !== "%Library.DynamicObject" + ) { + // This is a non-JSON property addRangeToMapVal(properties, memberstr, memberrange); + } else if (parsed[i][j].s == ld.cos_mem_attrindex) { + // This is a generic member + + if (membercontext.baseclass.startsWith("%SYSTEM.")) { + // This is always a method + addRangeToMapVal(methods, memberstr, memberrange); + } else { + // This can be a method or property + addRangeToMapVal(methods, memberstr, memberrange); + addRangeToMapVal(properties, memberstr, memberrange); + } } } - } - } else if ( - settings.diagnostics.zutil && - !ifZeroStartPos && - parsed[i][j].l == ld.cos_langindex && - parsed[i][j].s == ld.cos_sysf_attrindex && - /^\$zu(til)?$/i.test(doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c))) && - j < parsed[i].length - 1 - ) { - // This is a $ZUTIL call + } else if ( + settings.diagnostics.zutil && + !ifZeroStartPos && + parsed[i][j].l == ld.cos_langindex && + parsed[i][j].s == ld.cos_sysf_attrindex && + /^\$zu(til)?$/i.test(doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c))) && + j < parsed[i].length - 1 + ) { + // This is a $ZUTIL call - // Determine if this is a known function - let brk = false; - const nums: string[] = []; - for (let ln = i; ln < parsed.length; ln++) { - if (parsed[ln] == undefined || parsed[ln].length == 0) { - continue; - } - for (let tkn = ln == i ? j + 2 : 0; tkn < parsed[ln].length; tkn++) { - if (parsed[ln][tkn].l != ld.cos_langindex) { - // We hit another language, so exit - brk = true; - break; + // Determine if this is a known function + let brk = false; + const nums: string[] = []; + for (let ln = i; ln < parsed.length; ln++) { + if (parsed[ln] == undefined || parsed[ln].length == 0) { + continue; } - const tknText = doc.getText( - Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), - ); - if (parsed[ln][tkn].s == ld.cos_delim_attrindex) { - if (nums.length) { - const argList = nums.join(",") + tknText; - if ( - zutilFunctions.deprecated.includes(argList) || - zutilFunctions.replace[argList] != undefined || - zutilFunctions.noReplace.includes(argList) - ) { - // This is a known function, so create a Diagnostic - const diag: Diagnostic = { - range: Range.create(i, parsed[i][j].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), - severity: DiagnosticSeverity.Warning, - source: "InterSystems Language Server", - message: "", - }; - if (zutilFunctions.deprecated.includes(argList)) { - diag.message = "Deprecated function"; - diag.tags = [DiagnosticTag.Deprecated]; - } else { - diag.message = "Function has been superseded"; - if (zutilFunctions.replace[argList] != undefined) { - diag.data = argList; - } - if (argList == "5,") { - // This is a namespace switch - const nsTkn = tkn == parsed[ln].length - 1 ? 0 : tkn + 1; - const nsLn = nsTkn == 0 ? ln + 1 : ln; - const nsText = doc.getText( - Range.create( - nsLn, - parsed[nsLn][nsTkn].p, - nsLn, - parsed[nsLn][nsTkn].p + parsed[nsLn][nsTkn].c, - ), - ); - if (parsed[nsLn][nsTkn].s == ld.cos_str_attrindex && validNsRegex.test(nsText)) { - currentNs = nsText.slice(1, -1).toUpperCase(); - if (currentNs != baseNs) { - nsNestedBlockLevel = 1; + for (let tkn = ln == i ? j + 2 : 0; tkn < parsed[ln].length; tkn++) { + if (parsed[ln][tkn].l != ld.cos_langindex) { + // We hit another language, so exit + brk = true; + break; + } + const tknText = doc.getText( + Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), + ); + if (parsed[ln][tkn].s == ld.cos_delim_attrindex) { + if (nums.length) { + const argList = nums.join(",") + tknText; + if ( + zutilFunctions.deprecated.includes(argList) || + zutilFunctions.replace[argList] != undefined || + zutilFunctions.noReplace.includes(argList) + ) { + // This is a known function, so create a Diagnostic + const diag: Diagnostic = { + range: Range.create(i, parsed[i][j].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), + severity: DiagnosticSeverity.Warning, + source: "InterSystems Language Server", + message: "", + }; + if (zutilFunctions.deprecated.includes(argList)) { + diag.message = "Deprecated function"; + diag.tags = [DiagnosticTag.Deprecated]; + } else { + diag.message = "Function has been superseded"; + if (zutilFunctions.replace[argList] != undefined) { + diag.data = argList; + } + if (argList == "5,") { + // This is a namespace switch + const nsTkn = tkn == parsed[ln].length - 1 ? 0 : tkn + 1; + const nsLn = nsTkn == 0 ? ln + 1 : ln; + const nsText = doc.getText( + Range.create( + nsLn, + parsed[nsLn][nsTkn].p, + nsLn, + parsed[nsLn][nsTkn].p + parsed[nsLn][nsTkn].c, + ), + ); + if (parsed[nsLn][nsTkn].s == ld.cos_str_attrindex && validNsRegex.test(nsText)) { + currentNs = nsText.slice(1, -1).toUpperCase(); + if (currentNs != baseNs) { + nsNestedBlockLevel = 1; + } else { + nsNestedBlockLevel = 0; + } } else { - nsNestedBlockLevel = 0; + // We can't determine what namespace we are in + currentNs = ""; + nsNestedBlockLevel = 1; } - } else { - // We can't determine what namespace we are in - currentNs = ""; - nsNestedBlockLevel = 1; } } + diagnostics.push(diag); + brk = true; + break; + } else if (tknText == ")") { + // Hit the end of the arg list, so exit + brk = true; + break; } - diagnostics.push(diag); - brk = true; - break; - } else if (tknText == ")") { - // Hit the end of the arg list, so exit + } else { + // Delimiter is first token after open parenthesis, so exit brk = true; break; } + } else if (parsed[ln][tkn].s == ld.cos_number_attrindex) { + nums.push(tknText); } else { - // Delimiter is first token after open parenthesis, so exit + // We hit another token, so exit brk = true; break; } - } else if (parsed[ln][tkn].s == ld.cos_number_attrindex) { - nums.push(tknText); - } else { - // We hit another token, so exit - brk = true; + } + if (brk) { break; } } - if (brk) { - break; - } - } - } else if ( - parsed[i][j].l == ld.cos_langindex && - parsed[i][j].s == ld.cos_sysv_attrindex && - ["$namespace", "$znspace"].includes( - doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase(), - ) - ) { - // This is a potential namespace switch + } else if ( + parsed[i][j].l == ld.cos_langindex && + parsed[i][j].s == ld.cos_sysv_attrindex && + ["$namespace", "$znspace"].includes( + doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase(), + ) + ) { + // This is a potential namespace switch - // Check if this is in a Set command - let isSet = false; - let hasPc = false; - let brk = false; - for (let ln = i; ln >= 0; ln--) { - if (parsed[ln] == undefined || parsed[ln].length == 0) { - continue; - } - for (let tkn = ln == i ? j : parsed[ln].length - 1; tkn >= 0; tkn--) { - if (parsed[ln][tkn].l != ld.cos_langindex || parsed[ln][tkn].s == ld.cos_zcom_attrindex) { - brk = true; - break; + // Check if this is in a Set command + let isSet = false; + let hasPc = false; + let brk = false; + for (let ln = i; ln >= 0; ln--) { + if (parsed[ln] == undefined || parsed[ln].length == 0) { + continue; } - if (parsed[ln][tkn].s == ld.cos_command_attrindex) { - if ( - ["s", "set"].includes( - doc - .getText(Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c)) - .toLowerCase(), - ) - ) { - isSet = true; + for (let tkn = ln == i ? j : parsed[ln].length - 1; tkn >= 0; tkn--) { + if (parsed[ln][tkn].l != ld.cos_langindex || parsed[ln][tkn].s == ld.cos_zcom_attrindex) { + brk = true; + break; + } + if (parsed[ln][tkn].s == ld.cos_command_attrindex) { if ( - tkn < parsed[ln].length - 1 && - parsed[ln][tkn + 1].l == ld.cos_langindex && - parsed[ln][tkn + 1].s === ld.cos_delim_attrindex && - doc.getText( - Range.create(ln, parsed[ln][tkn + 1].p, ln, parsed[ln][tkn + 1].p + parsed[ln][tkn + 1].c), - ) == ":" + ["s", "set"].includes( + doc + .getText(Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c)) + .toLowerCase(), + ) ) { - hasPc = true; + isSet = true; + if ( + tkn < parsed[ln].length - 1 && + parsed[ln][tkn + 1].l == ld.cos_langindex && + parsed[ln][tkn + 1].s === ld.cos_delim_attrindex && + doc.getText( + Range.create(ln, parsed[ln][tkn + 1].p, ln, parsed[ln][tkn + 1].p + parsed[ln][tkn + 1].c), + ) == ":" + ) { + hasPc = true; + } } + brk = true; + break; } - brk = true; + } + if (brk) { break; } } - if (brk) { - break; - } - } - if (isSet) { - if (hasPc) { - // We can't determine what namespace we are in - currentNs = ""; - nsNestedBlockLevel = 1; - } else { - // Check what we are being Set to - let brk = false; - let foundOp = false; - for (let ln = i; ln < parsed.length; ln++) { - if (parsed[ln] == undefined || parsed[ln].length == 0) { - continue; - } - for (let tkn = ln == i ? j : 0; tkn < parsed[ln].length; tkn++) { - if ( - parsed[ln][tkn].l != ld.cos_langindex || - parsed[ln][tkn].s == ld.cos_zcom_attrindex || - parsed[ln][tkn].s == ld.cos_command_attrindex - ) { - brk = true; - break; + if (isSet) { + if (hasPc) { + // We can't determine what namespace we are in + currentNs = ""; + nsNestedBlockLevel = 1; + } else { + // Check what we are being Set to + let brk = false; + let foundOp = false; + for (let ln = i; ln < parsed.length; ln++) { + if (parsed[ln] == undefined || parsed[ln].length == 0) { + continue; } - if (foundOp) { - const nsText = doc.getText( - Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), - ); - if (parsed[ln][tkn].s == ld.cos_str_attrindex && validNsRegex.test(nsText)) { - currentNs = nsText.slice(1, -1).toUpperCase(); - if (currentNs != baseNs) { - nsNestedBlockLevel = 1; + for (let tkn = ln == i ? j : 0; tkn < parsed[ln].length; tkn++) { + if ( + parsed[ln][tkn].l != ld.cos_langindex || + parsed[ln][tkn].s == ld.cos_zcom_attrindex || + parsed[ln][tkn].s == ld.cos_command_attrindex + ) { + brk = true; + break; + } + if (foundOp) { + const nsText = doc.getText( + Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), + ); + if (parsed[ln][tkn].s == ld.cos_str_attrindex && validNsRegex.test(nsText)) { + currentNs = nsText.slice(1, -1).toUpperCase(); + if (currentNs != baseNs) { + nsNestedBlockLevel = 1; + } else { + nsNestedBlockLevel = 0; + } } else { - nsNestedBlockLevel = 0; + // We can't determine what namespace we are in + currentNs = ""; + nsNestedBlockLevel = 1; } - } else { - // We can't determine what namespace we are in - currentNs = ""; - nsNestedBlockLevel = 1; + brk = true; + break; + } + if ( + parsed[ln][tkn].s == ld.cos_oper_attrindex && + doc.getText(Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c)) == "=" + ) { + foundOp = true; } - brk = true; - break; } - if ( - parsed[ln][tkn].s == ld.cos_oper_attrindex && - doc.getText(Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c)) == "=" - ) { - foundOp = true; + if (brk) { + break; } } - if (brk) { - break; - } } } - } - } else if ( - parsed[i][j].l == ld.cos_langindex && - parsed[i][j].s == ld.cos_command_attrindex && - /^zn(space)?$/i.test(doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c))) - ) { - // This is a potential namespace switch + } else if ( + parsed[i][j].l == ld.cos_langindex && + parsed[i][j].s == ld.cos_command_attrindex && + /^zn(space)?$/i.test(doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c))) + ) { + // This is a potential namespace switch - if (j < parsed[i].length - 1) { - const nextTknText = doc.getText( - Range.create(i, parsed[i][j + 1].p, i, parsed[i][j + 1].p + parsed[i][j + 1].c), - ); - if ( - parsed[i][j + 1].l == ld.cos_langindex && - parsed[i][j + 1].s == ld.cos_str_attrindex && - validNsRegex.test(nextTknText) - ) { - currentNs = nextTknText.slice(1, -1).toUpperCase(); - if (currentNs != baseNs) { - nsNestedBlockLevel = 1; + if (j < parsed[i].length - 1) { + const nextTknText = doc.getText( + Range.create(i, parsed[i][j + 1].p, i, parsed[i][j + 1].p + parsed[i][j + 1].c), + ); + if ( + parsed[i][j + 1].l == ld.cos_langindex && + parsed[i][j + 1].s == ld.cos_str_attrindex && + validNsRegex.test(nextTknText) + ) { + currentNs = nextTknText.slice(1, -1).toUpperCase(); + if (currentNs != baseNs) { + nsNestedBlockLevel = 1; + } else { + nsNestedBlockLevel = 0; + } } else { - nsNestedBlockLevel = 0; + // We can't determine what namespace we are in + currentNs = ""; + nsNestedBlockLevel = 1; } - } else { - // We can't determine what namespace we are in - currentNs = ""; - nsNestedBlockLevel = 1; } - } - } else if ( - j == 0 && - parsed[i][j].l == ld.cls_langindex && - parsed[i][j].s == ld.cls_keyword_attrindex && - isPersistent && - parsed[i].length > 2 && - ["property", "relationship"].includes( - doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase(), - ) - ) { - // This is the start of a UDL Property definition + } else if ( + j == 0 && + parsed[i][j].l == ld.cls_langindex && + parsed[i][j].s == ld.cls_keyword_attrindex && + isPersistent && + parsed[i].length > 2 && + ["property", "relationship"].includes( + doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase(), + ) + ) { + // This is the start of a UDL Property definition - const propRange = Range.create(i, parsed[i][1].p, i, parsed[i][1].p + parsed[i][1].c); - const propName = quoteUDLIdentifier(doc.getText(propRange), 0); + const propRange = Range.create(i, parsed[i][1].p, i, parsed[i][1].p + parsed[i][1].c); + const propName = quoteUDLIdentifier(doc.getText(propRange), 0); - // Check if a SqlFieldName is present - let sqlFieldName: Range | undefined, - hasSqlFieldName = false, - inKeywords = false, - brk = false; - for (let ln = i; ln < parsed.length; ln++) { - if ( - ln != i && - parsed[ln]?.length && - parsed[ln][0].l == ld.cls_langindex && - (parsed[ln][0].s == ld.cls_desc_attrindex || - (parsed[ln][0].s == ld.cls_keyword_attrindex && - isClassMember(doc.getText(Range.create(ln, parsed[ln][0].p, ln, parsed[ln][0].p + parsed[ln][0].c))))) - ) { - // This is the start of the next class member - break; - } - for (let k = 0; k < parsed[ln].length; k++) { - if (hasSqlFieldName) { - if ( + // Check if a SqlFieldName is present + let sqlFieldName: Range | undefined, + hasSqlFieldName = false, + inKeywords = false, + brk = false; + for (let ln = i; ln < parsed.length; ln++) { + if ( + ln != i && + parsed[ln]?.length && + parsed[ln][0].l == ld.cls_langindex && + (parsed[ln][0].s == ld.cls_desc_attrindex || + (parsed[ln][0].s == ld.cls_keyword_attrindex && + isClassMember(doc.getText(Range.create(ln, parsed[ln][0].p, ln, parsed[ln][0].p + parsed[ln][0].c))))) + ) { + // This is the start of the next class member + break; + } + for (let k = 0; k < parsed[ln].length; k++) { + if (hasSqlFieldName) { + if ( + parsed[ln][k].l == ld.cls_langindex && + (parsed[ln][k].s == ld.cls_sqliden_attrindex || + parsed[ln][k].s == ld.error_attrindex || + (parsed[ln][k].s == ld.cls_delim_attrindex && + inKeywords && + [",", "]"].includes( + doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)), + ))) + ) { + if (parsed[ln][k].s == ld.cls_sqliden_attrindex) { + sqlFieldName = Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c); + } + brk = true; + break; + } + } else if ( parsed[ln][k].l == ld.cls_langindex && - (parsed[ln][k].s == ld.cls_sqliden_attrindex || - parsed[ln][k].s == ld.error_attrindex || - (parsed[ln][k].s == ld.cls_delim_attrindex && - inKeywords && - [",", "]"].includes( - doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)), - ))) + parsed[ln][k].s == ld.cls_keyword_attrindex && + doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)).toLowerCase() == + "sqlfieldname" ) { - if (parsed[ln][k].s == ld.cls_sqliden_attrindex) { - sqlFieldName = Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c); - } - brk = true; - break; + hasSqlFieldName = true; + } else if ( + parsed[ln][k].l == ld.cls_langindex && + parsed[ln][k].s == ld.cls_delim_attrindex && + doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)) == "[" + ) { + inKeywords = true; } - } else if ( - parsed[ln][k].l == ld.cls_langindex && - parsed[ln][k].s == ld.cls_keyword_attrindex && - doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)).toLowerCase() == - "sqlfieldname" - ) { - hasSqlFieldName = true; - } else if ( - parsed[ln][k].l == ld.cls_langindex && - parsed[ln][k].s == ld.cls_delim_attrindex && - doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)) == "[" - ) { - inKeywords = true; } + if (brk) break; } - if (brk) break; - } - if (hasSqlFieldName) { - if (sqlFieldName && sqlReservedWords.includes(doc.getText(sqlFieldName).toUpperCase())) { - // The SqlFieldName is a reserved word + if (hasSqlFieldName) { + if (sqlFieldName && sqlReservedWords.includes(doc.getText(sqlFieldName).toUpperCase())) { + // The SqlFieldName is a reserved word + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: sqlFieldName, + message: "SqlFieldName is a SQL reserved word", + source: "InterSystems Language Server", + }); + } + } else if (sqlReservedWords.includes(propName.toUpperCase())) { + // The property name is a reserved word, and it's not corrected by a SqlFieldName diagnostics.push({ severity: DiagnosticSeverity.Warning, - range: sqlFieldName, - message: "SqlFieldName is a SQL reserved word", + range: propRange, + message: "Property name is a SQL reserved word", source: "InterSystems Language Server", }); } - } else if (sqlReservedWords.includes(propName.toUpperCase())) { - // The property name is a reserved word, and it's not corrected by a SqlFieldName - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: propRange, - message: "Property name is a SQL reserved word", - source: "InterSystems Language Server", - }); } - } - if (nsNestedBlockLevel > 0) { - // Determine if we're still in the different namespace + if (nsNestedBlockLevel > 0) { + // Determine if we're still in the different namespace - if (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_brace_attrindex) { - const brace = doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)); - if (brace == "{") { - nsNestedBlockLevel++; - } else { - nsNestedBlockLevel--; - if (nsNestedBlockLevel == 0) { - // Ran off the end of that stack - currentNs = baseNs; + if (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_brace_attrindex) { + const brace = doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)); + if (brace == "{") { + nsNestedBlockLevel++; + } else { + nsNestedBlockLevel--; + if (nsNestedBlockLevel == 0) { + // Ran off the end of that stack + currentNs = baseNs; + } } + } else if ( + // Ran off the end of the implementation + parsed[i][j].l == ld.cls_langindex || + // Ran off the end of the method + // In a routine + (/^objectscript(-int)?$/.test(doc.languageId) && + // This is the first token and it's at the start of the line + j == 0 && + parsed[i][j].p == 0 && + // This token is a label + parsed[i][j].l == ld.cos_langindex && + parsed[i][j].s == ld.cos_label_attrindex) || + // Exited the script + (doc.languageId == "objectscript-csp" && parsed[i][j].l == ld.html_langindex) + ) { + currentNs = baseNs; + nsNestedBlockLevel = 0; } - } else if ( - // Ran off the end of the implementation - parsed[i][j].l == ld.cls_langindex || - // Ran off the end of the method - // In a routine - (/^objectscript(-int)?$/.test(doc.languageId) && - // This is the first token and it's at the start of the line - j == 0 && - parsed[i][j].p == 0 && - // This token is a label - parsed[i][j].l == ld.cos_langindex && - parsed[i][j].s == ld.cos_label_attrindex) || - // Exited the script - (doc.languageId == "objectscript-csp" && parsed[i][j].l == ld.html_langindex) - ) { - currentNs = baseNs; - nsNestedBlockLevel = 0; } } } } - } - if ( - settings.diagnostics.deprecation && - (methods.size > 0 || parameters.size > 0 || properties.size > 0 || classes.size > 0) - ) { - // Query the database for all Deprecated members or classes that we're referencing + if ( + settings.diagnostics.deprecation && + (methods.size > 0 || parameters.size > 0 || properties.size > 0 || classes.size > 0) + ) { + // Query the database for all Deprecated members or classes that we're referencing - // Build the query - const querydata: QueryData = { - query: - "SELECT Name, Parent AS Class, 'method' AS MemberType FROM %Dictionary.CompiledMethod WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + - "SELECT Name, Parent AS Class, 'parameter' AS MemberType FROM %Dictionary.CompiledParameter WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + - "SELECT Name, Parent AS Class, 'property' AS MemberType FROM %Dictionary.CompiledProperty WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + - "SELECT Name, NULL AS Class, 'class' AS MemberType FROM %Dictionary.CompiledClass WHERE Deprecated = 1 AND Name %INLIST $LISTFROMSTRING(?)", - parameters: [ - [ - ...new Set( - [...methods.keys()].map((elem) => { - return elem.split(":::")[0]; - }), - ), - ].join(","), - [ - ...new Set( - [...parameters.keys()].map((elem) => { - return elem.split(":::")[0]; - }), - ), - ].join(","), - [ - ...new Set( - [...properties.keys()].map((elem) => { - return elem.split(":::")[0]; - }), - ), - ].join(","), - [...classes.keys()].join(","), - ], - }; + // Build the query + const querydata: QueryData = { + query: + "SELECT Name, Parent AS Class, 'method' AS MemberType FROM %Dictionary.CompiledMethod WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + + "SELECT Name, Parent AS Class, 'parameter' AS MemberType FROM %Dictionary.CompiledParameter WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + + "SELECT Name, Parent AS Class, 'property' AS MemberType FROM %Dictionary.CompiledProperty WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + + "SELECT Name, NULL AS Class, 'class' AS MemberType FROM %Dictionary.CompiledClass WHERE Deprecated = 1 AND Name %INLIST $LISTFROMSTRING(?)", + parameters: [ + [ + ...new Set( + [...methods.keys()].map((elem) => { + return elem.split(":::")[0]; + }), + ), + ].join(","), + [ + ...new Set( + [...parameters.keys()].map((elem) => { + return elem.split(":::")[0]; + }), + ), + ].join(","), + [ + ...new Set( + [...properties.keys()].map((elem) => { + return elem.split(":::")[0]; + }), + ), + ].join(","), + [...classes.keys()].join(","), + ], + }; - // Make the request - const respdata = server && await makeRESTRequest("POST", 1, "/action/query", server, querydata); - if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { - // We got data back + // Make the request + const respdata = server && await makeRESTRequest("POST", 1, "/action/query", server, querydata); + if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { + // We got data back - for (const row of respdata.data.result.content) { - // Create a Diagnostic for each Range that this class or member appears in the document + for (const row of respdata.data.result.content) { + // Create a Diagnostic for each Range that this class or member appears in the document - const memberstr: string = row.Class + ":::" + row.Name; - let ranges: Range[] | undefined; - if (row.MemberType === "method") { - ranges = methods.get(memberstr); - } else if (row.MemberType === "parameter") { - ranges = parameters.get(memberstr); - } else if (row.MemberType === "class") { - ranges = classes.get(row.Name); - } else { - ranges = properties.get(memberstr); - } - if (ranges !== undefined) { - for (const range of ranges) { - diagnostics.push({ - range: range, - severity: DiagnosticSeverity.Warning, - source: "InterSystems Language Server", - tags: [DiagnosticTag.Deprecated], - message: "Deprecated " + row.MemberType, - }); + const memberstr: string = row.Class + ":::" + row.Name; + let ranges: Range[] | undefined; + if (row.MemberType === "method") { + ranges = methods.get(memberstr); + } else if (row.MemberType === "parameter") { + ranges = parameters.get(memberstr); + } else if (row.MemberType === "class") { + ranges = classes.get(row.Name); + } else { + ranges = properties.get(memberstr); } - } - } - } - } - if ((settings.diagnostics.classes || settings.diagnostics.routines) && otherNsDocs.size > 0) { - // Query the database for the existence of documents in other namespaces - - const namespaces = new Set(); - otherNsDocs.forEach((v, k) => namespaces.add(k.split(":::")[0])); - for (const namespace of namespaces) { - // Build the query - let querydata: QueryData; - const otherClasses: string[] = []; - const otherRtns: string[] = []; - otherNsDocs.forEach((v, k) => { - const [ns, doc] = k.split(":::"); - if (ns == namespace) { - switch (doc.slice(-3)) { - case "cls": - otherClasses.push(doc.slice(0, -4)); - break; - case "inc": - otherRtns.push(doc); - break; - default: - otherRtns.push(doc); - otherRtns.push(`${doc.slice(0, -3)}int`); - otherRtns.push(`${doc.slice(0, -3)}obj`); + if (ranges !== undefined) { + for (const range of ranges) { + diagnostics.push({ + range: range, + severity: DiagnosticSeverity.Warning, + source: "InterSystems Language Server", + tags: [DiagnosticTag.Deprecated], + message: "Deprecated " + row.MemberType, + }); + } } } - }); - if (otherClasses.length && otherRtns.length) { - // Check for both classes and routines - querydata = { - query: - "SELECT Name||'.cls' AS Name FROM %Dictionary.ClassDefinition WHERE Name %INLIST $LISTFROMSTRING(?) " + - "UNION ALL %PARALLEL " + - "SELECT Name FROM %Library.RoutineMgr_StudioOpenDialog(?,?,?,?,?,?,?) WHERE Name %INLIST $LISTFROMSTRING(?)", - parameters: [otherClasses.join(","), "*.mac,*.inc,*.int,*.obj", 1, 1, 1, 1, 1, 0, otherRtns.join(",")], - }; - } else if (otherClasses.length) { - // Check for just classes - querydata = { - query: "SELECT Name||'.cls' AS Name FROM %Dictionary.ClassDefinition WHERE Name %INLIST $LISTFROMSTRING(?)", - parameters: [otherClasses.join(",")], - }; - } else { - // Check for just routines - querydata = { - query: - "SELECT Name FROM %Library.RoutineMgr_StudioOpenDialog(?,?,?,?,?,?,?) WHERE Name %INLIST $LISTFROMSTRING(?)", - parameters: ["*.mac,*.inc,*.int,*.obj", 1, 1, 1, 1, 1, 0, otherRtns.join(",")], - }; } + } + if ((settings.diagnostics.classes || settings.diagnostics.routines) && otherNsDocs.size > 0) { + // Query the database for the existence of documents in other namespaces - // Make the request - const respdata = server && await makeRESTRequest("POST", 1, "/action/query", { ...server, namespace }, querydata); - if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { - // We got data back - - // Report Diagnostics for files that aren't in the returned data - respdata.data.result.content.forEach((e) => - otherNsDocs.delete( - `${namespace}:::${e.Name.endsWith(".int") || e.Name.endsWith(".obj") ? `${e.Name.slice(0, -3)}mac` : e.Name}`, - ), - ); + const namespaces = new Set(); + otherNsDocs.forEach((v, k) => namespaces.add(k.split(":::")[0])); + for (const namespace of namespaces) { + // Build the query + let querydata: QueryData; + const otherClasses: string[] = []; + const otherRtns: string[] = []; otherNsDocs.forEach((v, k) => { const [ns, doc] = k.split(":::"); if (ns == namespace) { - v.forEach((range) => - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range, - message: `${doc.endsWith("cls") ? "Class" : doc.endsWith("inc") ? "Include file" : "Routine"} "${doc.slice(0, -4)}" does not exist in namespace "${ns}"`, - source: "InterSystems Language Server", - }), - ); + switch (doc.slice(-3)) { + case "cls": + otherClasses.push(doc.slice(0, -4)); + break; + case "inc": + otherRtns.push(doc); + break; + default: + otherRtns.push(doc); + otherRtns.push(`${doc.slice(0, -3)}int`); + otherRtns.push(`${doc.slice(0, -3)}obj`); + } } }); + if (otherClasses.length && otherRtns.length) { + // Check for both classes and routines + querydata = { + query: + "SELECT Name||'.cls' AS Name FROM %Dictionary.ClassDefinition WHERE Name %INLIST $LISTFROMSTRING(?) " + + "UNION ALL %PARALLEL " + + "SELECT Name FROM %Library.RoutineMgr_StudioOpenDialog(?,?,?,?,?,?,?) WHERE Name %INLIST $LISTFROMSTRING(?)", + parameters: [otherClasses.join(","), "*.mac,*.inc,*.int,*.obj", 1, 1, 1, 1, 1, 0, otherRtns.join(",")], + }; + } else if (otherClasses.length) { + // Check for just classes + querydata = { + query: "SELECT Name||'.cls' AS Name FROM %Dictionary.ClassDefinition WHERE Name %INLIST $LISTFROMSTRING(?)", + parameters: [otherClasses.join(",")], + }; + } else { + // Check for just routines + querydata = { + query: + "SELECT Name FROM %Library.RoutineMgr_StudioOpenDialog(?,?,?,?,?,?,?) WHERE Name %INLIST $LISTFROMSTRING(?)", + parameters: ["*.mac,*.inc,*.int,*.obj", 1, 1, 1, 1, 1, 0, otherRtns.join(",")], + }; + } + + // Make the request + const respdata = server && await makeRESTRequest("POST", 1, "/action/query", { ...server, namespace }, querydata); + if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { + // We got data back + + // Report Diagnostics for files that aren't in the returned data + respdata.data.result.content.forEach((e) => + otherNsDocs.delete( + `${namespace}:::${e.Name.endsWith(".int") || e.Name.endsWith(".obj") ? `${e.Name.slice(0, -3)}mac` : e.Name}`, + ), + ); + otherNsDocs.forEach((v, k) => { + const [ns, doc] = k.split(":::"); + if (ns == namespace) { + v.forEach((range) => + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range, + message: `${doc.endsWith("cls") ? "Class" : doc.endsWith("inc") ? "Include file" : "Routine"} "${doc.slice(0, -4)}" does not exist in namespace "${ns}"`, + source: "InterSystems Language Server", + }), + ); + } + }); + } } } } diff --git a/server/src/providers/hover.ts b/server/src/providers/hover.ts index e21ce9b..472f4df 100644 --- a/server/src/providers/hover.ts +++ b/server/src/providers/hover.ts @@ -64,9 +64,6 @@ export async function onHover(params: TextDocumentPositionParams): Promise iden.lastIndexOf(".")) { + if (iden.lastIndexOf("_") > iden.lastIndexOf(".") && server) { // This table is projected from a multi-dimensional property // Split the identifier into the class and property @@ -1060,7 +1059,7 @@ export async function onHover(params: TextDocumentPositionParams): Promise tblname.lastIndexOf(".")) { // This table is projected from a multi-dimensional property, so we can't provide any info - } else { + } else if (server) { // Normalize the class name if there are imports const normalizedname = await normalizeClassname( doc, @@ -1235,30 +1234,31 @@ export async function onHover(params: TextDocumentPositionParams): Promise 0) { + // We got data back - // Determine the normalized class name - const normalizedcls = await normalizeClassname(doc, parsed, clsName, server, params.position.line); - if (normalizedcls !== "") { - const respdata = await makeRESTRequest("POST", 1, "/action/query", server, { - query: - "SELECT Description, Type FROM %Dictionary.CompiledParameter WHERE Name = ? AND (Parent = ? OR " + - "Parent %INLIST (SELECT $LISTFROMSTRING(PropertyClass) FROM %Dictionary.CompiledClass WHERE Name = ?))", - parameters: [param, normalizedcls, currentClass(doc, parsed)], - }); - if (respdata !== undefined) { - if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { - // We got data back - - const header = `(**${normalizedcls}**) **${param}**${ - respdata.data.result.content[0].Type != "" ? ` As **${respdata.data.result.content[0].Type}**` : "" - }`; - return { - contents: { - kind: MarkupKind.Markdown, - value: markupValue(header, documaticHtmlToMarkdown(respdata.data.result.content[0].Description)), - }, - range: paramrange, - }; + const header = `(**${normalizedcls}**) **${param}**${ + respdata.data.result.content[0].Type != "" ? ` As **${respdata.data.result.content[0].Type}**` : "" + }`; + return { + contents: { + kind: MarkupKind.Markdown, + value: markupValue(header, documaticHtmlToMarkdown(respdata.data.result.content[0].Description)), + }, + range: paramrange, + }; + } } } } @@ -1299,6 +1299,7 @@ export async function onHover(params: TextDocumentPositionParams): Promise Date: Fri, 21 Aug 2026 15:12:14 -0400 Subject: [PATCH 06/21] clean --- server/src/providers/diagnostic.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/server/src/providers/diagnostic.ts b/server/src/providers/diagnostic.ts index a302f15..6161710 100644 --- a/server/src/providers/diagnostic.ts +++ b/server/src/providers/diagnostic.ts @@ -762,7 +762,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise 0) { // The class couldn't be resolved with the imports @@ -908,7 +908,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise 0) { // We got data back @@ -1419,7 +1419,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise 0) { // We got data back From 5a7b6e2c9f5360a5964ff70ecc0bca6ab689ff36 Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Fri, 21 Aug 2026 15:13:33 -0400 Subject: [PATCH 07/21] clean --- server/src/providers/diagnostic.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/providers/diagnostic.ts b/server/src/providers/diagnostic.ts index 6161710..6ef8712 100644 --- a/server/src/providers/diagnostic.ts +++ b/server/src/providers/diagnostic.ts @@ -909,7 +909,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise Date: Fri, 21 Aug 2026 15:14:42 -0400 Subject: [PATCH 08/21] clean --- server/src/providers/hover.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/src/providers/hover.ts b/server/src/providers/hover.ts index 472f4df..75e408f 100644 --- a/server/src/providers/hover.ts +++ b/server/src/providers/hover.ts @@ -373,7 +373,7 @@ export async function onHover(params: TextDocumentPositionParams): Promise iden.lastIndexOf(".") && server) { + if (server && iden.lastIndexOf("_") > iden.lastIndexOf(".")) { // This table is projected from a multi-dimensional property // Split the identifier into the class and property From 858deb980da6b041fc9bc3ccf717f0016269ff52 Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Fri, 21 Aug 2026 16:41:43 -0400 Subject: [PATCH 09/21] fix --- client/src/extension.ts | 14 +- eslint.config.mjs | 9 +- server/src/providers/completion.ts | 166 +- server/src/providers/diagnostic.ts | 2046 ++++++++++++------------ server/src/providers/documentLink.ts | 1 - server/src/providers/formatting.ts | 2 +- server/src/providers/refactoring.ts | 2 +- server/src/providers/signatureHelp.ts | 2 +- server/src/providers/typeDefinition.ts | 1 - 9 files changed, 1127 insertions(+), 1116 deletions(-) diff --git a/client/src/extension.ts b/client/src/extension.ts index a2b8c89..d1e8fa0 100644 --- a/client/src/extension.ts +++ b/client/src/extension.ts @@ -169,7 +169,7 @@ export async function activate(context: ExtensionContext) { const wsFolderUriString = workspace.getWorkspaceFolder(uri)?.uri.toString(); const serverSpec = objectScriptApi.serverForUri(uri); if (serverSpec === undefined) { - return + return; } const auth = serverSpec.auth ?? new BasicAuthorization(serverSpec.username, serverSpec.password); if ( @@ -234,18 +234,6 @@ export async function activate(context: ExtensionContext) { return server; } catch { // Treat any thrown error as "no server connection" - return { - serverName: "", - active: false, - apiVersion: 1, - serverVersion: "", - scheme: "http", - host: "", - port: 0, - pathPrefix: "", - namespace: "", - username: "", - }; } } diff --git a/eslint.config.mjs b/eslint.config.mjs index bd0725c..4fc8daa 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -3,7 +3,14 @@ import tseslint from "typescript-eslint"; export default tseslint.config( { - ignores: ["**/vscode.d.ts", "**/vscode.proposed.d.ts", "client/out/**", "server/out/**", "**/*.config.{mjs,js}"], + ignores: [ + "**/vscode.d.ts", + "**/vscode.proposed.d.ts", + "client/out/**", + "server/out/**", + "common/out/**", + "**/*.config.{mjs,js}", + ], }, eslint.configs.recommended, ...tseslint.configs.recommended, diff --git a/server/src/providers/completion.ts b/server/src/providers/completion.ts index 78edea8..8202e7d 100644 --- a/server/src/providers/completion.ts +++ b/server/src/providers/completion.ts @@ -791,9 +791,6 @@ export async function onCompletion(params: CompletionParams): Promise closeParenCount && parenAndCommaRegex.test(prevline) && @@ -1899,75 +1902,77 @@ export async function onCompletion(params: CompletionParams): Promise 0) { - // We got data back - - for (const method of respdata.data.result.content) { - const item: CompletionItem = { - label: method.Name, - kind: CompletionItemKind.Method, - data: "member", - documentation: { - kind: MarkupKind.Markdown, - value: documaticHtmlToMarkdown(method.Description), - }, - }; - if (method.Origin === method.baseclass) { - // Members from the base class should appear first - item.sortText = sortPrefix + method.Name; - } else { - item.sortText = item.label; + const querydata = { + query: `SELECT Name, Description, Origin FROM %Dictionary.CompiledMethod WHERE Parent = ?${ + !(await showInternalForServer(server)) ? " AND Internal = 0" : "" + }`, + parameters: [thisclass], + }; + const respdata = await makeRESTRequest("POST", 1, "/action/query", server, querydata); + if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { + // We got data back + + for (const method of respdata.data.result.content) { + const item: CompletionItem = { + label: method.Name, + kind: CompletionItemKind.Method, + data: "member", + documentation: { + kind: MarkupKind.Markdown, + value: documaticHtmlToMarkdown(method.Description), + }, + }; + if (method.Origin === method.baseclass) { + // Members from the base class should appear first + item.sortText = sortPrefix + method.Name; + } else { + item.sortText = item.label; + } + result.push(item); } - result.push(item); } } } @@ -2010,12 +2015,13 @@ export async function onCompletion(params: CompletionParams): Promise prevline.split(">").length) || - prevline.endsWith("<") || - prevline.endsWith('"') + prevline.endsWith("<") || + prevline.endsWith('"')) ) { // Get the SchemaCache for this server or create one if it doesn't exist let schemaCache = schemaCaches.get(server); @@ -2374,7 +2380,7 @@ export async function onCompletion(params: CompletionParams): Promise = new Map(); const classes: Map = new Map(); - if (server) { - // Keep track of current namespace for class/routine existence checks - const baseNs = server.namespace.toUpperCase(); - let currentNs = baseNs; - let nsNestedBlockLevel = 0; - const validNsRegex = /^"[A-Za-z%]?[A-Za-z0-9-_]+"$/; + // Keep track of current namespace for class/routine existence checks. + // Only meaningful when we have a server to check against. + const nsContext = server && { + server, + baseNs: server.namespace.toUpperCase(), + currentNs: server.namespace.toUpperCase(), + nsNestedBlockLevel: 0, + }; + const validNsRegex = /^"[A-Za-z%]?[A-Za-z0-9-_]+"$/; - // Store the ns, name and ranges of all classes and routines from other namespaces that we see - // Keys are of the form "ns:::doc.ext" - const otherNsDocs: Map = new Map(); + // Store the ns, name and ranges of all classes and routines from other namespaces that we see + // Keys are of the form "ns:::doc.ext" + const otherNsDocs: Map = new Map(); - // We need to know if the last syntax error token was whitespace so we don't - // try to combine error tokens that aren't for the same underlying error. - let lastErrWasWhitespace = false; + // We need to know if the last syntax error token was whitespace so we don't + // try to combine error tokens that aren't for the same underlying error. + let lastErrWasWhitespace = false; - // Don't report diagnostics in a #if 0 block, and - // mark all of the code in the block as "unused" - let ifZeroStartPos: Position | undefined; - const ifZeroStart = /^\s*#if\s+(?:0|"0")(?:$|\s)/i; - const ifZeroEnd = /^\s*#elseif\s+|(?:#else|#endif)(?:$|\s)/i; + // Don't report diagnostics in a #if 0 block, and + // mark all of the code in the block as "unused" + let ifZeroStartPos: Position | undefined; + const ifZeroStart = /^\s*#if\s+(?:0|"0")(?:$|\s)/i; + const ifZeroEnd = /^\s*#elseif\s+|(?:#else|#endif)(?:$|\s)/i; - // Loop through the parsed document to find errors and warnings - for (let i = startline; i < parsed.length; i++) { - if (!parsed[i]?.length) continue; + // Loop through the parsed document to find errors and warnings + for (let i = startline; i < parsed.length; i++) { + if (!parsed[i]?.length) continue; - const lineText = doc.getText(Range.create(i, 0, i + 1, 0)); - if (doc.languageId != "objectscript-int" && !ifZeroStartPos) { - const ifZeroStartMatch = lineText.match(ifZeroStart); - if (ifZeroStartMatch) { - ifZeroStartPos = Position.create(i, ifZeroStartMatch[0].length); - continue; // No more diagnostics on this line - } - } else if (ifZeroStartPos && ifZeroEnd.test(lineText)) { - if (i > ifZeroStartPos.line + 1) - diagnostics.push({ - severity: DiagnosticSeverity.Hint, - range: Range.create(ifZeroStartPos, Position.create(i, 0)), - message: "Unused code detected", - tags: [DiagnosticTag.Unnecessary], - source: "InterSystems Language Server", - }); - ifZeroStartPos = undefined; + const lineText = doc.getText(Range.create(i, 0, i + 1, 0)); + if (doc.languageId != "objectscript-int" && !ifZeroStartPos) { + const ifZeroStartMatch = lineText.match(ifZeroStart); + if (ifZeroStartMatch) { + ifZeroStartPos = Position.create(i, ifZeroStartMatch[0].length); continue; // No more diagnostics on this line } + } else if (ifZeroStartPos && ifZeroEnd.test(lineText)) { + if (i > ifZeroStartPos.line + 1) + diagnostics.push({ + severity: DiagnosticSeverity.Hint, + range: Range.create(ifZeroStartPos, Position.create(i, 0)), + message: "Unused code detected", + tags: [DiagnosticTag.Unnecessary], + source: "InterSystems Language Server", + }); + ifZeroStartPos = undefined; + continue; // No more diagnostics on this line + } - // Loop through the line's tokens - for (let j = 0; j < parsed[i].length; j++) { - const symbolstart: number = parsed[i][j].p; - const symbolend: number = parsed[i][j].p + parsed[i][j].c; + // Loop through the line's tokens + for (let j = 0; j < parsed[i].length; j++) { + const symbolstart: number = parsed[i][j].p; + const symbolend: number = parsed[i][j].p + parsed[i][j].c; - if (j > 0 && parsed[i][j].l === parsed[i][j - 1].l && parsed[i][j].s === parsed[i][j - 1].s && !ifZeroStartPos) { - // This token is the same as the last + if (j > 0 && parsed[i][j].l === parsed[i][j - 1].l && parsed[i][j].s === parsed[i][j - 1].s && !ifZeroStartPos) { + // This token is the same as the last - if (parsed[i][j].s === ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { - const errorDesc = normalizeErrorDesc(parsed[i][j].e); - const errorRange = Range.create(i, symbolstart, i, symbolend); - if (doc.getText(errorRange).trim()) { - if ( - !lastErrWasWhitespace && - parsed[i][j].l == parsed[i][j - 1].l && - diagnostics.length && - [syntaxError, diagnostics[diagnostics.length - 1].message].includes(errorDesc) - ) { - // This error token is a continuation of the same underlying error - diagnostics[diagnostics.length - 1].range.end = Position.create(i, symbolend); - } else { - // This is a token for a new error - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: { - start: Position.create(i, symbolstart), - end: Position.create(i, symbolend), - }, - message: errorDesc, - source: "InterSystems Language Server", - }); - } - } - lastErrWasWhitespace = false; - } else { - lastErrWasWhitespace = true; - } - } else { - if (parsed[i][j].s === ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l) && !ifZeroStartPos) { - // This is an error token - const errorRange = Range.create(i, symbolstart, i, symbolend); - // Don't create a diagnostic for this error if it's just whitespace. - // This can happen because the parsers can report a syntax error token - // that spans only whitespace, and it won't be filtered out - // at the parser level since it's an error token. - if (doc.getText(errorRange).trim()) { + if (parsed[i][j].s === ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { + const errorDesc = normalizeErrorDesc(parsed[i][j].e); + const errorRange = Range.create(i, symbolstart, i, symbolend); + if (doc.getText(errorRange).trim()) { + if ( + !lastErrWasWhitespace && + parsed[i][j].l == parsed[i][j - 1].l && + diagnostics.length && + [syntaxError, diagnostics[diagnostics.length - 1].message].includes(errorDesc) + ) { + // This error token is a continuation of the same underlying error + diagnostics[diagnostics.length - 1].range.end = Position.create(i, symbolend); + } else { + // This is a token for a new error diagnostics.push({ severity: DiagnosticSeverity.Error, - range: errorRange, - message: normalizeErrorDesc(parsed[i][j].e), + range: { + start: Position.create(i, symbolstart), + end: Position.create(i, symbolend), + }, + message: errorDesc, source: "InterSystems Language Server", }); - lastErrWasWhitespace = false; - } else { - lastErrWasWhitespace = true; } - } else if ( - parsed[i][j].l == ld.cos_langindex && - parsed[i][j].s == ld.cos_otw_attrindex && - settings.diagnostics.undefinedVariables && - !ifZeroStartPos - ) { - // This is an OptionTrackWarning (unset local variable) - const varrange = Range.create(Position.create(i, symbolstart), Position.create(i, symbolend)); + } + lastErrWasWhitespace = false; + } else { + lastErrWasWhitespace = true; + } + } else { + if (parsed[i][j].s === ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l) && !ifZeroStartPos) { + // This is an error token + const errorRange = Range.create(i, symbolstart, i, symbolend); + // Don't create a diagnostic for this error if it's just whitespace. + // This can happen because the parsers can report a syntax error token + // that spans only whitespace, and it won't be filtered out + // at the parser level since it's an error token. + if (doc.getText(errorRange).trim()) { diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: varrange, - message: `Local variable "${doc.getText(varrange)}" may be undefined`, + severity: DiagnosticSeverity.Error, + range: errorRange, + message: normalizeErrorDesc(parsed[i][j].e), source: "InterSystems Language Server", }); - } else if ( - parsed[i][j].l == ld.cls_langindex && - parsed[i][j].s == ld.cls_clsname_attrindex && - j !== 0 && - parsed[i][j - 1].l == ld.cls_langindex && - parsed[i][j - 1].s == ld.cls_keyword_attrindex && - doc.getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)).toLowerCase() === + lastErrWasWhitespace = false; + } else { + lastErrWasWhitespace = true; + } + } else if ( + parsed[i][j].l == ld.cos_langindex && + parsed[i][j].s == ld.cos_otw_attrindex && + settings.diagnostics.undefinedVariables && + !ifZeroStartPos + ) { + // This is an OptionTrackWarning (unset local variable) + const varrange = Range.create(Position.create(i, symbolstart), Position.create(i, symbolend)); + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: varrange, + message: `Local variable "${doc.getText(varrange)}" may be undefined`, + source: "InterSystems Language Server", + }); + } else if ( + parsed[i][j].l == ld.cls_langindex && + parsed[i][j].s == ld.cls_clsname_attrindex && + j !== 0 && + parsed[i][j - 1].l == ld.cls_langindex && + parsed[i][j - 1].s == ld.cls_keyword_attrindex && + doc.getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)).toLowerCase() === "class" - ) { - // This is the class name in the class definition line + ) { + // This is the class name in the class definition line - // Check if the class name has a package - const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); - const word = doc.getText(wordrange); - if (!word.includes(".")) { - // The class name doesn't have a package, so report an error diagnostic here - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: wordrange, - message: "A package must be specified", - source: "InterSystems Language Server", - }); - } else if (isPersistent) { - // Check if a SqlTableName is present - let sqlTableName: Range | undefined, - hasSqlTableName = false; - for (let k = j + 1; k < parsed[i].length; k++) { - if (hasSqlTableName) { - if ( - parsed[i][k].l == ld.cls_langindex && - (parsed[i][k].s == ld.cls_sqliden_attrindex || - parsed[i][k].s == ld.error_attrindex || - (parsed[i][k].s == ld.cls_delim_attrindex && - [",", "]"].includes( - doc.getText(Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c)), - ))) - ) { - if (parsed[i][k].s == ld.cls_sqliden_attrindex) { - sqlTableName = Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c); - } - break; - } - } else if ( + // Check if the class name has a package + const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); + const word = doc.getText(wordrange); + if (!word.includes(".")) { + // The class name doesn't have a package, so report an error diagnostic here + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: wordrange, + message: "A package must be specified", + source: "InterSystems Language Server", + }); + } else if (isPersistent) { + // Check if a SqlTableName is present + let sqlTableName: Range | undefined, + hasSqlTableName = false; + for (let k = j + 1; k < parsed[i].length; k++) { + if (hasSqlTableName) { + if ( parsed[i][k].l == ld.cls_langindex && - parsed[i][k].s == ld.cls_keyword_attrindex && - doc.getText(Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c)).toLowerCase() == - "sqltablename" + (parsed[i][k].s == ld.cls_sqliden_attrindex || + parsed[i][k].s == ld.error_attrindex || + (parsed[i][k].s == ld.cls_delim_attrindex && + [",", "]"].includes( + doc.getText(Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c)), + ))) ) { - hasSqlTableName = true; + if (parsed[i][k].s == ld.cls_sqliden_attrindex) { + sqlTableName = Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c); + } + break; } + } else if ( + parsed[i][k].l == ld.cls_langindex && + parsed[i][k].s == ld.cls_keyword_attrindex && + doc.getText(Range.create(i, parsed[i][k].p, i, parsed[i][k].p + parsed[i][k].c)).toLowerCase() == + "sqltablename" + ) { + hasSqlTableName = true; } - if (hasSqlTableName) { - if (sqlTableName && sqlReservedWords.includes(doc.getText(sqlTableName).toUpperCase())) { - // The SqlTableName is a reserved word - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: sqlTableName, - message: "SqlTableName is a SQL reserved word", - source: "InterSystems Language Server", - }); - } - } else if (sqlReservedWords.includes(word.split(".").pop()!.toUpperCase())) { - // The short class name is a reserved word, and it's not corrected by a SqlTableName - wordrange.start.character = wordrange.end.character - word.split(".").pop()!.length; + } + if (hasSqlTableName) { + if (sqlTableName && sqlReservedWords.includes(doc.getText(sqlTableName).toUpperCase())) { + // The SqlTableName is a reserved word diagnostics.push({ severity: DiagnosticSeverity.Warning, - range: wordrange, - message: "Class name is a SQL reserved word", + range: sqlTableName, + message: "SqlTableName is a SQL reserved word", source: "InterSystems Language Server", }); } + } else if (sqlReservedWords.includes(word.split(".").pop()!.toUpperCase())) { + // The short class name is a reserved word, and it's not corrected by a SqlTableName + wordrange.start.character = wordrange.end.character - word.split(".").pop()!.length; + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: wordrange, + message: "Class name is a SQL reserved word", + source: "InterSystems Language Server", + }); } - } else if ( - j === 0 && - parsed[i][j].l == ld.cls_langindex && - parsed[i][j].s == ld.cls_keyword_attrindex && - doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase() === + } + } else if ( + j === 0 && + parsed[i][j].l == ld.cls_langindex && + parsed[i][j].s == ld.cls_keyword_attrindex && + doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase() === "parameter" && - settings.diagnostics.parameters - ) { - // This line is a UDL Parameter definition - - const endsWithSemi = - parsed[i][parsed[i].length - 1].l == ld.cls_langindex && - parsed[i][parsed[i].length - 1].s == ld.cls_delim_attrindex && - doc.getText( - Range.create( - i, - parsed[i][parsed[i].length - 1].p, - i, - parsed[i][parsed[i].length - 1].p + parsed[i][parsed[i].length - 1].c, - ), - ) == ";"; - if ( - isPersistent && - parsed[i].length > 3 && - doc.getText(Range.create(i, parsed[i][1].p, i, parsed[i][1].p + parsed[i][1].c)) == "DEFAULTGLOBAL" - ) { - // Check if the provided value is a valid global name, with leading caret - let inKeywords = false; - for (let tkn = 2; tkn < parsed[i].length; tkn++) { - if (parsed[i][tkn].l == ld.cls_langindex && parsed[i][tkn].s == ld.cls_delim_attrindex) { - const delim = doc.getText(Range.create(i, parsed[i][tkn].p, i, parsed[i][tkn].p + parsed[i][tkn].c)); - if (inKeywords && delim == "]") { - inKeywords = false; - } else if (!inKeywords && delim == "[") { - inKeywords = true; - } else if (!inKeywords && delim == "=" && tkn < parsed[i].length - 1) { - const valueEndTkn = parsed[i].length - (endsWithSemi ? 2 : 1); - const valueRange = Range.create( - i, - parsed[i][tkn + 1].p, - i, - parsed[i][valueEndTkn].p + parsed[i][valueEndTkn].c, - ); - const valueText = doc.getText(valueRange); - if ( - !valueText.startsWith("{") && - !/^"\^[%\x41-\xFF]([\x41-\xFF\d.]*[\x41-\xFF\d])?"$/.test(valueText) - ) { - // The value is neither a valid global name nor a compile-time expression - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: valueRange, - message: "DEFAULTGLOBAL Parameter value should be a valid global name prefixed by a caret", - source: "InterSystems Language Server", - }); - } - break; - } - } - } - } - if ( - parsed[i].length > 3 && - parsed[i][2].l == ld.cls_langindex && - parsed[i][2].s === ld.cls_keyword_attrindex && - doc.getText(Range.create(i, parsed[i][2].p, i, parsed[i][2].p + parsed[i][2].c)).toLowerCase() === "as" - ) { - // This Parameter has a type - const tokenrange = Range.create(i, parsed[i][3].p, i, parsed[i][3].p + parsed[i][3].c); - const tokentext = doc.getText(tokenrange).toUpperCase(); - const thistypedoc = parameterTypes.find((typedoc) => typedoc.name === tokentext); - if (thistypedoc === undefined) { - // The type is invalid - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: tokenrange, - message: "Invalid parameter type", - source: "InterSystems Language Server", - }); - } else if (parsed[i].length > 4) { - // The type is valid - - // See if this Parameter has a value - let valuetkn: number | undefined; - const delimtext = doc.getText(Range.create(i, parsed[i][4].p, i, parsed[i][4].p + parsed[i][4].c)); - if (delimtext === "[") { - // Loop through the line to find the closing brace - let closingtkn: number | undefined; - for (let ptkn = 5; ptkn < parsed[i].length; ptkn++) { - if ( - parsed[i][ptkn].l == ld.cls_langindex && - parsed[i][ptkn].s === ld.cls_delim_attrindex && - doc.getText(Range.create(i, parsed[i][ptkn].p, i, parsed[i][ptkn].p + parsed[i][ptkn].c)) === "]" - ) { - closingtkn = ptkn; - break; - } - } - // Check if the token following the closing brace is = - if ( - closingtkn && - parsed[i].length > closingtkn && - doc.getText( - Range.create( - i, - parsed[i][closingtkn + 1].p, - i, - parsed[i][closingtkn + 1].p + parsed[i][closingtkn + 1].c, - ), - ) === "=" - ) { - // There is a value following the = - valuetkn = closingtkn + 2; - } - } else if (delimtext === "=") { - // The value follows this delimiter - valuetkn = 5; - } else { - // Delimiter is a ; so there isn't a value to evaluate - } + settings.diagnostics.parameters + ) { + // This line is a UDL Parameter definition - if (valuetkn && parsed[i].length > valuetkn + 1) { + const endsWithSemi = + parsed[i][parsed[i].length - 1].l == ld.cls_langindex && + parsed[i][parsed[i].length - 1].s == ld.cls_delim_attrindex && + doc.getText( + Range.create( + i, + parsed[i][parsed[i].length - 1].p, + i, + parsed[i][parsed[i].length - 1].p + parsed[i][parsed[i].length - 1].c, + ), + ) == ";"; + if ( + isPersistent && + parsed[i].length > 3 && + doc.getText(Range.create(i, parsed[i][1].p, i, parsed[i][1].p + parsed[i][1].c)) == "DEFAULTGLOBAL" + ) { + // Check if the provided value is a valid global name, with leading caret + let inKeywords = false; + for (let tkn = 2; tkn < parsed[i].length; tkn++) { + if (parsed[i][tkn].l == ld.cls_langindex && parsed[i][tkn].s == ld.cls_delim_attrindex) { + const delim = doc.getText(Range.create(i, parsed[i][tkn].p, i, parsed[i][tkn].p + parsed[i][tkn].c)); + if (inKeywords && delim == "]") { + inKeywords = false; + } else if (!inKeywords && delim == "[") { + inKeywords = true; + } else if (!inKeywords && delim == "=" && tkn < parsed[i].length - 1) { const valueEndTkn = parsed[i].length - (endsWithSemi ? 2 : 1); - const valtext = doc.getText( - Range.create(i, parsed[i][valuetkn].p, i, parsed[i][valuetkn].p + parsed[i][valuetkn].c), - ); - const valrange = Range.create( + const valueRange = Range.create( i, - parsed[i][valuetkn].p, + parsed[i][tkn + 1].p, i, parsed[i][valueEndTkn].p + parsed[i][valueEndTkn].c, ); + const valueText = doc.getText(valueRange); if ( - (thistypedoc.name === "STRING" && - (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || - (thistypedoc.name === "COSEXPRESSION" && - (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || - (thistypedoc.name === "CLASSNAME" && - (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || - (thistypedoc.name === "INTEGER" && - (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_num_attrindex)) || - (thistypedoc.name === "BOOLEAN" && - (parsed[i][valuetkn].l !== ld.cls_langindex || - parsed[i][valuetkn].s !== ld.cls_num_attrindex || - (valtext !== "1" && valtext !== "0"))) + !valueText.startsWith("{") && + !/^"\^[%\x41-\xFF]([\x41-\xFF\d.]*[\x41-\xFF\d])?"$/.test(valueText) ) { - // Allow curly brace syntax for all types but COSEXPRESSION - if (thistypedoc.name == "COSEXPRESSION" || !valtext.startsWith("{")) { - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: valrange, - message: "Parameter value and type do not match", - source: "InterSystems Language Server", - }); - } - } else if (thistypedoc.name === "CLASSNAME" && settings.diagnostics.classes) { - // Validate the class name in the string - let classname: string = valtext.slice(1, -1); - if (classname.startsWith("%") && !classname.includes(".")) { - classname = `%Library.${classname.slice(1)}`; - } - // Check if class exists - const filtered = files.filter((file) => file.Name === classname + ".cls"); - if (filtered.length !== 1 && !classname.startsWith("%SYSTEM.")) { - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: valrange, - message: `Class "${classname}" does not exist in namespace "${baseNs}"`, - source: "InterSystems Language Server", - }); - } + // The value is neither a valid global name nor a compile-time expression + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: valueRange, + message: "DEFAULTGLOBAL Parameter value should be a valid global name prefixed by a caret", + source: "InterSystems Language Server", + }); } + break; } } } - - // Loop through the line to capture any syntax errors - for (let ptkn = 1; ptkn < parsed[i].length; ptkn++) { - if (parsed[i][ptkn].s == ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { - const errorDesc = normalizeErrorDesc(parsed[i][j].e); - if ( - parsed[i][ptkn].l == parsed[i][ptkn - 1].l && - parsed[i][ptkn - 1].s == 0 && - diagnostics.length && - [syntaxError, diagnostics[diagnostics.length - 1].message].includes(errorDesc) - ) { - // This error token is a continuation of the same underlying error - diagnostics[diagnostics.length - 1].range.end = Position.create( - i, - parsed[i][ptkn].p + parsed[i][ptkn].c, - ); - } else { - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: Range.create(i, parsed[i][ptkn].p, i, parsed[i][ptkn].p + parsed[i][ptkn].c), - message: errorDesc, - source: "InterSystems Language Server", - }); - } - } - } - - break; - } else if ( - j === 0 && - parsed[i][j].l == ld.cls_langindex && - parsed[i][j].s == ld.cls_keyword_attrindex && - doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase() === "import" + } + if ( + parsed[i].length > 3 && + parsed[i][2].l == ld.cls_langindex && + parsed[i][2].s === ld.cls_keyword_attrindex && + doc.getText(Range.create(i, parsed[i][2].p, i, parsed[i][2].p + parsed[i][2].c)).toLowerCase() === "as" ) { - // This is the UDL Import line + // This Parameter has a type + const tokenrange = Range.create(i, parsed[i][3].p, i, parsed[i][3].p + parsed[i][3].c); + const tokentext = doc.getText(tokenrange).toUpperCase(); + const thistypedoc = parameterTypes.find((typedoc) => typedoc.name === tokentext); + if (thistypedoc === undefined) { + // The type is invalid + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: tokenrange, + message: "Invalid parameter type", + source: "InterSystems Language Server", + }); + } else if (parsed[i].length > 4) { + // The type is valid - // Loop through the line and update the inheritedpackages list - let lastpkgend: number = 0; - for (let imptkn = 1; imptkn < parsed[i].length; imptkn++) { - if (parsed[i][imptkn].s == ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { + // See if this Parameter has a value + let valuetkn: number | undefined; + const delimtext = doc.getText(Range.create(i, parsed[i][4].p, i, parsed[i][4].p + parsed[i][4].c)); + if (delimtext === "[") { + // Loop through the line to find the closing brace + let closingtkn: number | undefined; + for (let ptkn = 5; ptkn < parsed[i].length; ptkn++) { + if ( + parsed[i][ptkn].l == ld.cls_langindex && + parsed[i][ptkn].s === ld.cls_delim_attrindex && + doc.getText(Range.create(i, parsed[i][ptkn].p, i, parsed[i][ptkn].p + parsed[i][ptkn].c)) === "]" + ) { + closingtkn = ptkn; + break; + } + } + // Check if the token following the closing brace is = if ( - parsed[i][imptkn - 1].s == ld.error_attrindex && - !doc.getText(Range.create(i, parsed[i][imptkn].p - 1, i, parsed[i][imptkn].p)).trim() + closingtkn && + parsed[i].length > closingtkn && + doc.getText( + Range.create( + i, + parsed[i][closingtkn + 1].p, + i, + parsed[i][closingtkn + 1].p + parsed[i][closingtkn + 1].c, + ), + ) === "=" ) { - // The previous token is an error without a space in between, so extend the existing syntax error Diagnostic to cover this token - diagnostics[diagnostics.length - 1].range.end = Position.create( - i, - parsed[i][imptkn].p + parsed[i][imptkn].c, - ); - } else { - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: Range.create(i, parsed[i][imptkn].p, i, parsed[i][imptkn].p + parsed[i][imptkn].c), - message: syntaxError, - source: "InterSystems Language Server", - }); + // There is a value following the = + valuetkn = closingtkn + 2; } + } else if (delimtext === "=") { + // The value follows this delimiter + valuetkn = 5; + } else { + // Delimiter is a ; so there isn't a value to evaluate } - if (parsed[i][imptkn].l == ld.cls_langindex && parsed[i][imptkn].s == ld.cls_clsname_attrindex) { - const pkgrange = findFullRange( + + if (valuetkn && parsed[i].length > valuetkn + 1) { + const valueEndTkn = parsed[i].length - (endsWithSemi ? 2 : 1); + const valtext = doc.getText( + Range.create(i, parsed[i][valuetkn].p, i, parsed[i][valuetkn].p + parsed[i][valuetkn].c), + ); + const valrange = Range.create( i, - parsed, - imptkn, - parsed[i][imptkn].p, - parsed[i][imptkn].p + parsed[i][imptkn].c, + parsed[i][valuetkn].p, + i, + parsed[i][valueEndTkn].p + parsed[i][valueEndTkn].c, ); - const pkg = doc.getText(pkgrange); - if (!inheritedpackages.includes(pkg)) { - inheritedpackages.push(pkg); - } if ( - files.length > 0 && - settings.diagnostics.classes && - lastpkgend != pkgrange.end.character && - !files.some((f) => f.Name.startsWith(pkg + ".") && f.Name.endsWith(".cls")) + (thistypedoc.name === "STRING" && + (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || + (thistypedoc.name === "COSEXPRESSION" && + (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || + (thistypedoc.name === "CLASSNAME" && + (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_str_attrindex)) || + (thistypedoc.name === "INTEGER" && + (parsed[i][valuetkn].l !== ld.cls_langindex || parsed[i][valuetkn].s !== ld.cls_num_attrindex)) || + (thistypedoc.name === "BOOLEAN" && + (parsed[i][valuetkn].l !== ld.cls_langindex || + parsed[i][valuetkn].s !== ld.cls_num_attrindex || + (valtext !== "1" && valtext !== "0"))) ) { - // This package does not exist - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: pkgrange, - message: `Package "${pkg}" does not exist in namespace "${baseNs}"`, - source: "InterSystems Language Server", - }); + // Allow curly brace syntax for all types but COSEXPRESSION + if (thistypedoc.name == "COSEXPRESSION" || !valtext.startsWith("{")) { + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: valrange, + message: "Parameter value and type do not match", + source: "InterSystems Language Server", + }); + } + } else if (thistypedoc.name === "CLASSNAME" && settings.diagnostics.classes) { + // Validate the class name in the string + let classname: string = valtext.slice(1, -1); + if (classname.startsWith("%") && !classname.includes(".")) { + classname = `%Library.${classname.slice(1)}`; + } + // Check if class exists + const filtered = files.filter((file) => file.Name === classname + ".cls"); + if (filtered.length !== 1 && !classname.startsWith("%SYSTEM.")) { + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: valrange, + message: `Class "${classname}" does not exist in namespace "${nsContext?.baseNs ?? ""}"`, + source: "InterSystems Language Server", + }); + } } - lastpkgend = pkgrange.end.character; } } + } - break; - } else if ( - files.length > 0 && - ((parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_clsname_attrindex) || - (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_clsname_attrindex)) && - (settings.diagnostics.classes || settings.diagnostics.deprecation) && - !ifZeroStartPos - ) { - // This is a class name - - // Don't validate a class name that follows the "Class" keyword - if (j !== 0 && parsed[i][j - 1].l == ld.cls_langindex && parsed[i][j - 1].s == ld.cls_keyword_attrindex) { - // The previous token is a UDL keyword - const prevkeytext = doc - .getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)) - .toLowerCase(); - if (prevkeytext === "class") { - continue; + // Loop through the line to capture any syntax errors + for (let ptkn = 1; ptkn < parsed[i].length; ptkn++) { + if (parsed[i][ptkn].s == ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { + const errorDesc = normalizeErrorDesc(parsed[i][j].e); + if ( + parsed[i][ptkn].l == parsed[i][ptkn - 1].l && + parsed[i][ptkn - 1].s == 0 && + diagnostics.length && + [syntaxError, diagnostics[diagnostics.length - 1].message].includes(errorDesc) + ) { + // This error token is a continuation of the same underlying error + diagnostics[diagnostics.length - 1].range.end = Position.create( + i, + parsed[i][ptkn].p + parsed[i][ptkn].c, + ); + } else { + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: Range.create(i, parsed[i][ptkn].p, i, parsed[i][ptkn].p + parsed[i][ptkn].c), + message: errorDesc, + source: "InterSystems Language Server", + }); } } + } - // Get the full text of the selection - const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); - let word = doc.getText(wordrange); - if (word.charAt(0) === ".") { - // This might be $SYSTEM.ClassName - const prevseven = doc.getText(Range.create(i, wordrange.start.character - 7, i, wordrange.start.character)); - if (prevseven.toUpperCase() !== "$SYSTEM") { - // This classname is invalid - if (settings.diagnostics.classes) { - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: wordrange, - message: "Invalid class name", - source: "InterSystems Language Server", - }); - } - continue; + break; + } else if ( + j === 0 && + parsed[i][j].l == ld.cls_langindex && + parsed[i][j].s == ld.cls_keyword_attrindex && + doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase() === "import" + ) { + // This is the UDL Import line + + // Loop through the line and update the inheritedpackages list + let lastpkgend: number = 0; + for (let imptkn = 1; imptkn < parsed[i].length; imptkn++) { + if (parsed[i][imptkn].s == ld.error_attrindex && reportSyntaxErrors(parsed[i][j].l)) { + if ( + parsed[i][imptkn - 1].s == ld.error_attrindex && + !doc.getText(Range.create(i, parsed[i][imptkn].p - 1, i, parsed[i][imptkn].p)).trim() + ) { + // The previous token is an error without a space in between, so extend the existing syntax error Diagnostic to cover this token + diagnostics[diagnostics.length - 1].range.end = Position.create( + i, + parsed[i][imptkn].p + parsed[i][imptkn].c, + ); } else { - word = "%SYSTEM" + word; + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: Range.create(i, parsed[i][imptkn].p, i, parsed[i][imptkn].p + parsed[i][imptkn].c), + message: syntaxError, + source: "InterSystems Language Server", + }); } } - if (word.charAt(0) === '"') { - // This classname is delimited with ", so strip them - word = word.slice(1, -1); - } - - if (currentNs == baseNs) { - // Normalize the class name if there are imports - const possiblecls = { num: 0 }; - const normalizedname = await normalizeClassname( - doc, - parsed, - word, - server, + if (parsed[i][imptkn].l == ld.cls_langindex && parsed[i][imptkn].s == ld.cls_clsname_attrindex) { + const pkgrange = findFullRange( i, - files, - possiblecls, - inheritedpackages, + parsed, + imptkn, + parsed[i][imptkn].p, + parsed[i][imptkn].p + parsed[i][imptkn].c, ); - - if (normalizedname === "" && possiblecls.num > 0) { - // The class couldn't be resolved with the imports - if (settings.diagnostics.classes) { - const diagnostic: Diagnostic = { - severity: DiagnosticSeverity.Error, - range: wordrange, - message: `Class name "${word}" is ambiguous`, - source: "InterSystems Language Server", - }; - diagnostics.push(diagnostic); - } - } else { - // Check if class exists - const filtered = files.filter((file) => file.Name === normalizedname + ".cls"); - if (filtered.length !== 1) { - // Exempt %SYSTEM classes because some of them don't have ^oddDEF entries - if (settings.diagnostics.classes && !word.startsWith("%SYSTEM.")) { - const diagnostic: Diagnostic = { - severity: DiagnosticSeverity.Error, - range: wordrange, - message: `Class "${word}" does not exist in namespace "${baseNs}"`, - source: "InterSystems Language Server", - }; - diagnostics.push(diagnostic); - } - } else if (settings.diagnostics.deprecation) { - // The class exists, so add it to the map - addRangeToMapVal(classes, normalizedname, wordrange); - } + const pkg = doc.getText(pkgrange); + if (!inheritedpackages.includes(pkg)) { + inheritedpackages.push(pkg); } - } else if (currentNs != "" && settings.diagnostics.classes && !word.startsWith("%SYSTEM.")) { - if (!word.includes(".") && !word.startsWith("%")) { - // Using a short class name when you may be in another namespace is bad + if ( + files.length > 0 && + settings.diagnostics.classes && + lastpkgend != pkgrange.end.character && + !files.some((f) => f.Name.startsWith(pkg + ".") && f.Name.endsWith(".cls")) + ) { + // This package does not exist diagnostics.push({ severity: DiagnosticSeverity.Error, - range: wordrange, - message: "Short class name used after a namespace switch", + range: pkgrange, + message: `Package "${pkg}" does not exist in namespace "${nsContext?.baseNs ?? ""}"`, source: "InterSystems Language Server", }); - } else { - // Add this class to the map - addRangeToMapVal( - otherNsDocs, - `${currentNs}:::${ - !word.includes(".") && word.startsWith("%") ? `%Library.${word.slice(1)}` : word - }.cls`, - wordrange, - ); } + lastpkgend = pkgrange.end.character; } - } else if ( - files.length > 0 && - ((parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_rtnname_attrindex) || - (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_rtnname_attrindex)) && - settings.diagnostics.routines && - !ifZeroStartPos - ) { - // This is a routine name + } - // Get the full text of the selection - const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); - const word = doc.getText(wordrange); + break; + } else if ( + nsContext && + files.length > 0 && + ((parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_clsname_attrindex) || + (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_clsname_attrindex)) && + (settings.diagnostics.classes || settings.diagnostics.deprecation) && + !ifZeroStartPos + ) { + // This is a class name - // Determine if this is an include file - let isinc = false; - if (parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_rtnname_attrindex) { - isinc = true; - } else { - if ( - parsed[i][j - 1].l == ld.cos_langindex && - parsed[i][j - 1].s == ld.cos_ppc_attrindex && - doc - .getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)) - .toLowerCase() === "include" - ) { - isinc = true; + // Don't validate a class name that follows the "Class" keyword + if (j !== 0 && parsed[i][j - 1].l == ld.cls_langindex && parsed[i][j - 1].s == ld.cls_keyword_attrindex) { + // The previous token is a UDL keyword + const prevkeytext = doc + .getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)) + .toLowerCase(); + if (prevkeytext === "class") { + continue; + } + } + + // Get the full text of the selection + const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); + let word = doc.getText(wordrange); + if (word.charAt(0) === ".") { + // This might be $SYSTEM.ClassName + const prevseven = doc.getText(Range.create(i, wordrange.start.character - 7, i, wordrange.start.character)); + if (prevseven.toUpperCase() !== "$SYSTEM") { + // This classname is invalid + if (settings.diagnostics.classes) { + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: wordrange, + message: "Invalid class name", + source: "InterSystems Language Server", + }); } + continue; + } else { + word = "%SYSTEM" + word; } + } + if (word.charAt(0) === '"') { + // This classname is delimited with ", so strip them + word = word.slice(1, -1); + } - if (currentNs == baseNs) { - // Check if the routine exists - if (isinc) { - if (!files.some((file) => file.Name == word + ".inc")) { - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range: wordrange, - message: `Include file "${word}" does not exist in namespace "${baseNs}"`, - source: "InterSystems Language Server", - }); - } - } else if (word.length && /^%?[\d.\p{L}]*$/u.test(word)) { - // Need validation to avoid creating a bad regex - const regex = new RegExp(`^${word.replace(/\./g, ".")}\\.(mac|int|obj)$`); - if (!files.some((file) => regex.test(file.Name))) { - diagnostics.push({ + if (nsContext.currentNs == nsContext.baseNs) { + // Normalize the class name if there are imports + const possiblecls = { num: 0 }; + const normalizedname = await normalizeClassname( + doc, + parsed, + word, + nsContext.server, + i, + files, + possiblecls, + inheritedpackages, + ); + + if (normalizedname === "" && possiblecls.num > 0) { + // The class couldn't be resolved with the imports + if (settings.diagnostics.classes) { + const diagnostic: Diagnostic = { + severity: DiagnosticSeverity.Error, + range: wordrange, + message: `Class name "${word}" is ambiguous`, + source: "InterSystems Language Server", + }; + diagnostics.push(diagnostic); + } + } else { + // Check if class exists + const filtered = files.filter((file) => file.Name === normalizedname + ".cls"); + if (filtered.length !== 1) { + // Exempt %SYSTEM classes because some of them don't have ^oddDEF entries + if (settings.diagnostics.classes && !word.startsWith("%SYSTEM.")) { + const diagnostic: Diagnostic = { severity: DiagnosticSeverity.Error, range: wordrange, - message: `Routine "${word}" does not exist in namespace "${baseNs}"`, + message: `Class "${word}" does not exist in namespace "${nsContext.baseNs}"`, source: "InterSystems Language Server", - }); + }; + diagnostics.push(diagnostic); } + } else if (settings.diagnostics.deprecation) { + // The class exists, so add it to the map + addRangeToMapVal(classes, normalizedname, wordrange); } - } else if (currentNs != "") { - // Add this document to the map - addRangeToMapVal(otherNsDocs, `${currentNs}:::${word}${isinc ? ".inc" : ".mac"}`, wordrange); } - } else if ( - files.length > 0 && - parsed[i][j].l == ld.cos_langindex && - (parsed[i][j].s == ld.cos_prop_attrindex || - parsed[i][j].s == ld.cos_method_attrindex || - parsed[i][j].s == ld.cos_attr_attrindex || - parsed[i][j].s == ld.cos_mem_attrindex) && - settings.diagnostics.deprecation - ) { - // This is a class member (property/parameter/method) + } else if (nsContext.currentNs != "" && settings.diagnostics.classes && !word.startsWith("%SYSTEM.")) { + if (!word.includes(".") && !word.startsWith("%")) { + // Using a short class name when you may be in another namespace is bad + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: wordrange, + message: "Short class name used after a namespace switch", + source: "InterSystems Language Server", + }); + } else { + // Add this class to the map + addRangeToMapVal( + otherNsDocs, + `${nsContext.currentNs}:::${ + !word.includes(".") && word.startsWith("%") ? `%Library.${word.slice(1)}` : word + }.cls`, + wordrange, + ); + } + } + } else if ( + nsContext && + files.length > 0 && + ((parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_rtnname_attrindex) || + (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_rtnname_attrindex)) && + settings.diagnostics.routines && + !ifZeroStartPos + ) { + // This is a routine name - // Get the full text of the member - const memberrange = findFullRange(i, parsed, j, symbolstart, symbolend); - let member = doc.getText(memberrange); - if (member.charAt(0) === "#") { - member = member.slice(1); + // Get the full text of the selection + const wordrange = findFullRange(i, parsed, j, symbolstart, symbolend); + const word = doc.getText(wordrange); + + // Determine if this is an include file + let isinc = false; + if (parsed[i][j].l == ld.cls_langindex && parsed[i][j].s == ld.cls_rtnname_attrindex) { + isinc = true; + } else { + if ( + parsed[i][j - 1].l == ld.cos_langindex && + parsed[i][j - 1].s == ld.cos_ppc_attrindex && + doc + .getText(Range.create(i, parsed[i][j - 1].p, i, parsed[i][j - 1].p + parsed[i][j - 1].c)) + .toLowerCase() === "include" + ) { + isinc = true; } - const unquotedname = quoteUDLIdentifier(member, 0); + } - // Find the dot token - let dottkn = 0; - for (let tkn = 0; tkn < parsed[i].length; tkn++) { - if (parsed[i][tkn].p >= memberrange.start.character) { - break; + if (nsContext.currentNs == nsContext.baseNs) { + // Check if the routine exists + if (isinc) { + if (!files.some((file) => file.Name == word + ".inc")) { + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: wordrange, + message: `Include file "${word}" does not exist in namespace "${nsContext.baseNs}"`, + source: "InterSystems Language Server", + }); + } + } else if (word.length && /^%?[\d.\p{L}]*$/u.test(word)) { + // Need validation to avoid creating a bad regex + const regex = new RegExp(`^${word.replace(/\./g, ".")}\\.(mac|int|obj)$`); + if (!files.some((file) => regex.test(file.Name))) { + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range: wordrange, + message: `Routine "${word}" does not exist in namespace "${nsContext.baseNs}"`, + source: "InterSystems Language Server", + }); } - dottkn = tkn; } + } else if (nsContext.currentNs != "") { + // Add this document to the map + addRangeToMapVal(otherNsDocs, `${nsContext.currentNs}:::${word}${isinc ? ".inc" : ".mac"}`, wordrange); + } + } else if ( + files.length > 0 && + parsed[i][j].l == ld.cos_langindex && + (parsed[i][j].s == ld.cos_prop_attrindex || + parsed[i][j].s == ld.cos_method_attrindex || + parsed[i][j].s == ld.cos_attr_attrindex || + parsed[i][j].s == ld.cos_mem_attrindex) && + settings.diagnostics.deprecation + ) { + // This is a class member (property/parameter/method) + + // Get the full text of the member + const memberrange = findFullRange(i, parsed, j, symbolstart, symbolend); + let member = doc.getText(memberrange); + if (member.charAt(0) === "#") { + member = member.slice(1); + } + const unquotedname = quoteUDLIdentifier(member, 0); - // Get the base class that this member is in - const membercontext = await getClassMemberContext(doc, parsed, dottkn, i, server, files, inheritedpackages); - if (membercontext.baseclass !== "") { - // We could determine the class, so add the member to the correct map + // Find the dot token + let dottkn = 0; + for (let tkn = 0; tkn < parsed[i].length; tkn++) { + if (parsed[i][tkn].p >= memberrange.start.character) { + break; + } + dottkn = tkn; + } - const memberstr: string = membercontext.baseclass + ":::" + unquotedname; - if (parsed[i][j].s == ld.cos_prop_attrindex) { - // This is a parameter - addRangeToMapVal(parameters, memberstr, memberrange); - } else if (parsed[i][j].s == ld.cos_method_attrindex) { - // This is a method + // Get the base class that this member is in + const membercontext = (server && + (await getClassMemberContext(doc, parsed, dottkn, i, server, files, inheritedpackages))) || { + baseclass: "", + context: "", + }; + if (membercontext.baseclass !== "") { + // We could determine the class, so add the member to the correct map + + const memberstr: string = membercontext.baseclass + ":::" + unquotedname; + if (parsed[i][j].s == ld.cos_prop_attrindex) { + // This is a parameter + addRangeToMapVal(parameters, memberstr, memberrange); + } else if (parsed[i][j].s == ld.cos_method_attrindex) { + // This is a method + addRangeToMapVal(methods, memberstr, memberrange); + } else if ( + parsed[i][j].s == ld.cos_attr_attrindex && + membercontext.baseclass !== "%Library.DynamicArray" && + membercontext.baseclass !== "%Library.DynamicObject" + ) { + // This is a non-JSON property + addRangeToMapVal(properties, memberstr, memberrange); + } else if (parsed[i][j].s == ld.cos_mem_attrindex) { + // This is a generic member + + if (membercontext.baseclass.startsWith("%SYSTEM.")) { + // This is always a method + addRangeToMapVal(methods, memberstr, memberrange); + } else { + // This can be a method or property addRangeToMapVal(methods, memberstr, memberrange); - } else if ( - parsed[i][j].s == ld.cos_attr_attrindex && - membercontext.baseclass !== "%Library.DynamicArray" && - membercontext.baseclass !== "%Library.DynamicObject" - ) { - // This is a non-JSON property addRangeToMapVal(properties, memberstr, memberrange); - } else if (parsed[i][j].s == ld.cos_mem_attrindex) { - // This is a generic member - - if (membercontext.baseclass.startsWith("%SYSTEM.")) { - // This is always a method - addRangeToMapVal(methods, memberstr, memberrange); - } else { - // This can be a method or property - addRangeToMapVal(methods, memberstr, memberrange); - addRangeToMapVal(properties, memberstr, memberrange); - } } } - } else if ( - settings.diagnostics.zutil && - !ifZeroStartPos && - parsed[i][j].l == ld.cos_langindex && - parsed[i][j].s == ld.cos_sysf_attrindex && - /^\$zu(til)?$/i.test(doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c))) && - j < parsed[i].length - 1 - ) { - // This is a $ZUTIL call + } + } else if ( + settings.diagnostics.zutil && + !ifZeroStartPos && + parsed[i][j].l == ld.cos_langindex && + parsed[i][j].s == ld.cos_sysf_attrindex && + /^\$zu(til)?$/i.test(doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c))) && + j < parsed[i].length - 1 + ) { + // This is a $ZUTIL call - // Determine if this is a known function - let brk = false; - const nums: string[] = []; - for (let ln = i; ln < parsed.length; ln++) { - if (parsed[ln] == undefined || parsed[ln].length == 0) { - continue; + // Determine if this is a known function + let brk = false; + const nums: string[] = []; + for (let ln = i; ln < parsed.length; ln++) { + if (parsed[ln] == undefined || parsed[ln].length == 0) { + continue; + } + for (let tkn = ln == i ? j + 2 : 0; tkn < parsed[ln].length; tkn++) { + if (parsed[ln][tkn].l != ld.cos_langindex) { + // We hit another language, so exit + brk = true; + break; } - for (let tkn = ln == i ? j + 2 : 0; tkn < parsed[ln].length; tkn++) { - if (parsed[ln][tkn].l != ld.cos_langindex) { - // We hit another language, so exit - brk = true; - break; - } - const tknText = doc.getText( - Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), - ); - if (parsed[ln][tkn].s == ld.cos_delim_attrindex) { - if (nums.length) { - const argList = nums.join(",") + tknText; - if ( - zutilFunctions.deprecated.includes(argList) || - zutilFunctions.replace[argList] != undefined || - zutilFunctions.noReplace.includes(argList) - ) { - // This is a known function, so create a Diagnostic - const diag: Diagnostic = { - range: Range.create(i, parsed[i][j].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), - severity: DiagnosticSeverity.Warning, - source: "InterSystems Language Server", - message: "", - }; - if (zutilFunctions.deprecated.includes(argList)) { - diag.message = "Deprecated function"; - diag.tags = [DiagnosticTag.Deprecated]; - } else { - diag.message = "Function has been superseded"; - if (zutilFunctions.replace[argList] != undefined) { - diag.data = argList; - } - if (argList == "5,") { - // This is a namespace switch - const nsTkn = tkn == parsed[ln].length - 1 ? 0 : tkn + 1; - const nsLn = nsTkn == 0 ? ln + 1 : ln; - const nsText = doc.getText( - Range.create( - nsLn, - parsed[nsLn][nsTkn].p, - nsLn, - parsed[nsLn][nsTkn].p + parsed[nsLn][nsTkn].c, - ), - ); - if (parsed[nsLn][nsTkn].s == ld.cos_str_attrindex && validNsRegex.test(nsText)) { - currentNs = nsText.slice(1, -1).toUpperCase(); - if (currentNs != baseNs) { - nsNestedBlockLevel = 1; - } else { - nsNestedBlockLevel = 0; - } + const tknText = doc.getText( + Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), + ); + if (parsed[ln][tkn].s == ld.cos_delim_attrindex) { + if (nums.length) { + const argList = nums.join(",") + tknText; + if ( + zutilFunctions.deprecated.includes(argList) || + zutilFunctions.replace[argList] != undefined || + zutilFunctions.noReplace.includes(argList) + ) { + // This is a known function, so create a Diagnostic + const diag: Diagnostic = { + range: Range.create(i, parsed[i][j].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), + severity: DiagnosticSeverity.Warning, + source: "InterSystems Language Server", + message: "", + }; + if (zutilFunctions.deprecated.includes(argList)) { + diag.message = "Deprecated function"; + diag.tags = [DiagnosticTag.Deprecated]; + } else { + diag.message = "Function has been superseded"; + if (zutilFunctions.replace[argList] != undefined) { + diag.data = argList; + } + if (argList == "5," && nsContext) { + // This is a namespace switch + const nsTkn = tkn == parsed[ln].length - 1 ? 0 : tkn + 1; + const nsLn = nsTkn == 0 ? ln + 1 : ln; + const nsText = doc.getText( + Range.create( + nsLn, + parsed[nsLn][nsTkn].p, + nsLn, + parsed[nsLn][nsTkn].p + parsed[nsLn][nsTkn].c, + ), + ); + if (parsed[nsLn][nsTkn].s == ld.cos_str_attrindex && validNsRegex.test(nsText)) { + nsContext.currentNs = nsText.slice(1, -1).toUpperCase(); + if (nsContext.currentNs != nsContext.baseNs) { + nsContext.nsNestedBlockLevel = 1; } else { - // We can't determine what namespace we are in - currentNs = ""; - nsNestedBlockLevel = 1; + nsContext.nsNestedBlockLevel = 0; } + } else { + // We can't determine what namespace we are in + nsContext.currentNs = ""; + nsContext.nsNestedBlockLevel = 1; } } - diagnostics.push(diag); - brk = true; - break; - } else if (tknText == ")") { - // Hit the end of the arg list, so exit - brk = true; - break; } - } else { - // Delimiter is first token after open parenthesis, so exit + diagnostics.push(diag); + brk = true; + break; + } else if (tknText == ")") { + // Hit the end of the arg list, so exit brk = true; break; } - } else if (parsed[ln][tkn].s == ld.cos_number_attrindex) { - nums.push(tknText); } else { - // We hit another token, so exit + // Delimiter is first token after open parenthesis, so exit brk = true; break; } - } - if (brk) { + } else if (parsed[ln][tkn].s == ld.cos_number_attrindex) { + nums.push(tknText); + } else { + // We hit another token, so exit + brk = true; break; } } - } else if ( - parsed[i][j].l == ld.cos_langindex && - parsed[i][j].s == ld.cos_sysv_attrindex && - ["$namespace", "$znspace"].includes( - doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase(), - ) - ) { - // This is a potential namespace switch + if (brk) { + break; + } + } + } else if ( + nsContext && + parsed[i][j].l == ld.cos_langindex && + parsed[i][j].s == ld.cos_sysv_attrindex && + ["$namespace", "$znspace"].includes( + doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase(), + ) + ) { + // This is a potential namespace switch - // Check if this is in a Set command - let isSet = false; - let hasPc = false; - let brk = false; - for (let ln = i; ln >= 0; ln--) { - if (parsed[ln] == undefined || parsed[ln].length == 0) { - continue; + // Check if this is in a Set command + let isSet = false; + let hasPc = false; + let brk = false; + for (let ln = i; ln >= 0; ln--) { + if (parsed[ln] == undefined || parsed[ln].length == 0) { + continue; + } + for (let tkn = ln == i ? j : parsed[ln].length - 1; tkn >= 0; tkn--) { + if (parsed[ln][tkn].l != ld.cos_langindex || parsed[ln][tkn].s == ld.cos_zcom_attrindex) { + brk = true; + break; } - for (let tkn = ln == i ? j : parsed[ln].length - 1; tkn >= 0; tkn--) { - if (parsed[ln][tkn].l != ld.cos_langindex || parsed[ln][tkn].s == ld.cos_zcom_attrindex) { - brk = true; - break; - } - if (parsed[ln][tkn].s == ld.cos_command_attrindex) { + if (parsed[ln][tkn].s == ld.cos_command_attrindex) { + if ( + ["s", "set"].includes( + doc + .getText(Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c)) + .toLowerCase(), + ) + ) { + isSet = true; if ( - ["s", "set"].includes( - doc - .getText(Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c)) - .toLowerCase(), - ) + tkn < parsed[ln].length - 1 && + parsed[ln][tkn + 1].l == ld.cos_langindex && + parsed[ln][tkn + 1].s === ld.cos_delim_attrindex && + doc.getText( + Range.create(ln, parsed[ln][tkn + 1].p, ln, parsed[ln][tkn + 1].p + parsed[ln][tkn + 1].c), + ) == ":" ) { - isSet = true; - if ( - tkn < parsed[ln].length - 1 && - parsed[ln][tkn + 1].l == ld.cos_langindex && - parsed[ln][tkn + 1].s === ld.cos_delim_attrindex && - doc.getText( - Range.create(ln, parsed[ln][tkn + 1].p, ln, parsed[ln][tkn + 1].p + parsed[ln][tkn + 1].c), - ) == ":" - ) { - hasPc = true; - } + hasPc = true; } - brk = true; - break; } - } - if (brk) { + brk = true; break; } } - if (isSet) { - if (hasPc) { - // We can't determine what namespace we are in - currentNs = ""; - nsNestedBlockLevel = 1; - } else { - // Check what we are being Set to - let brk = false; - let foundOp = false; - for (let ln = i; ln < parsed.length; ln++) { - if (parsed[ln] == undefined || parsed[ln].length == 0) { - continue; + if (brk) { + break; + } + } + if (isSet) { + if (hasPc) { + // We can't determine what namespace we are in + nsContext.currentNs = ""; + nsContext.nsNestedBlockLevel = 1; + } else { + // Check what we are being Set to + let brk = false; + let foundOp = false; + for (let ln = i; ln < parsed.length; ln++) { + if (parsed[ln] == undefined || parsed[ln].length == 0) { + continue; + } + for (let tkn = ln == i ? j : 0; tkn < parsed[ln].length; tkn++) { + if ( + parsed[ln][tkn].l != ld.cos_langindex || + parsed[ln][tkn].s == ld.cos_zcom_attrindex || + parsed[ln][tkn].s == ld.cos_command_attrindex + ) { + brk = true; + break; } - for (let tkn = ln == i ? j : 0; tkn < parsed[ln].length; tkn++) { - if ( - parsed[ln][tkn].l != ld.cos_langindex || - parsed[ln][tkn].s == ld.cos_zcom_attrindex || - parsed[ln][tkn].s == ld.cos_command_attrindex - ) { - brk = true; - break; - } - if (foundOp) { - const nsText = doc.getText( - Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), - ); - if (parsed[ln][tkn].s == ld.cos_str_attrindex && validNsRegex.test(nsText)) { - currentNs = nsText.slice(1, -1).toUpperCase(); - if (currentNs != baseNs) { - nsNestedBlockLevel = 1; - } else { - nsNestedBlockLevel = 0; - } + if (foundOp) { + const nsText = doc.getText( + Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c), + ); + if (parsed[ln][tkn].s == ld.cos_str_attrindex && validNsRegex.test(nsText)) { + nsContext.currentNs = nsText.slice(1, -1).toUpperCase(); + if (nsContext.currentNs != nsContext.baseNs) { + nsContext.nsNestedBlockLevel = 1; } else { - // We can't determine what namespace we are in - currentNs = ""; - nsNestedBlockLevel = 1; + nsContext.nsNestedBlockLevel = 0; } - brk = true; - break; + } else { + // We can't determine what namespace we are in + nsContext.currentNs = ""; + nsContext.nsNestedBlockLevel = 1; } - if ( - parsed[ln][tkn].s == ld.cos_oper_attrindex && - doc.getText(Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c)) == "=" - ) { - foundOp = true; - } - } - if (brk) { + brk = true; break; } + if ( + parsed[ln][tkn].s == ld.cos_oper_attrindex && + doc.getText(Range.create(ln, parsed[ln][tkn].p, ln, parsed[ln][tkn].p + parsed[ln][tkn].c)) == "=" + ) { + foundOp = true; + } + } + if (brk) { + break; } } } - } else if ( - parsed[i][j].l == ld.cos_langindex && - parsed[i][j].s == ld.cos_command_attrindex && - /^zn(space)?$/i.test(doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c))) - ) { - // This is a potential namespace switch + } + } else if ( + nsContext && + parsed[i][j].l == ld.cos_langindex && + parsed[i][j].s == ld.cos_command_attrindex && + /^zn(space)?$/i.test(doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c))) + ) { + // This is a potential namespace switch - if (j < parsed[i].length - 1) { - const nextTknText = doc.getText( - Range.create(i, parsed[i][j + 1].p, i, parsed[i][j + 1].p + parsed[i][j + 1].c), - ); - if ( - parsed[i][j + 1].l == ld.cos_langindex && - parsed[i][j + 1].s == ld.cos_str_attrindex && - validNsRegex.test(nextTknText) - ) { - currentNs = nextTknText.slice(1, -1).toUpperCase(); - if (currentNs != baseNs) { - nsNestedBlockLevel = 1; - } else { - nsNestedBlockLevel = 0; - } + if (j < parsed[i].length - 1) { + const nextTknText = doc.getText( + Range.create(i, parsed[i][j + 1].p, i, parsed[i][j + 1].p + parsed[i][j + 1].c), + ); + if ( + parsed[i][j + 1].l == ld.cos_langindex && + parsed[i][j + 1].s == ld.cos_str_attrindex && + validNsRegex.test(nextTknText) + ) { + nsContext.currentNs = nextTknText.slice(1, -1).toUpperCase(); + if (nsContext.currentNs != nsContext.baseNs) { + nsContext.nsNestedBlockLevel = 1; } else { - // We can't determine what namespace we are in - currentNs = ""; - nsNestedBlockLevel = 1; + nsContext.nsNestedBlockLevel = 0; } + } else { + // We can't determine what namespace we are in + nsContext.currentNs = ""; + nsContext.nsNestedBlockLevel = 1; } - } else if ( - j == 0 && - parsed[i][j].l == ld.cls_langindex && - parsed[i][j].s == ld.cls_keyword_attrindex && - isPersistent && - parsed[i].length > 2 && - ["property", "relationship"].includes( - doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase(), - ) - ) { - // This is the start of a UDL Property definition + } + } else if ( + j == 0 && + parsed[i][j].l == ld.cls_langindex && + parsed[i][j].s == ld.cls_keyword_attrindex && + isPersistent && + parsed[i].length > 2 && + ["property", "relationship"].includes( + doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)).toLowerCase(), + ) + ) { + // This is the start of a UDL Property definition - const propRange = Range.create(i, parsed[i][1].p, i, parsed[i][1].p + parsed[i][1].c); - const propName = quoteUDLIdentifier(doc.getText(propRange), 0); + const propRange = Range.create(i, parsed[i][1].p, i, parsed[i][1].p + parsed[i][1].c); + const propName = quoteUDLIdentifier(doc.getText(propRange), 0); - // Check if a SqlFieldName is present - let sqlFieldName: Range | undefined, - hasSqlFieldName = false, - inKeywords = false, - brk = false; - for (let ln = i; ln < parsed.length; ln++) { - if ( - ln != i && - parsed[ln]?.length && - parsed[ln][0].l == ld.cls_langindex && - (parsed[ln][0].s == ld.cls_desc_attrindex || - (parsed[ln][0].s == ld.cls_keyword_attrindex && - isClassMember(doc.getText(Range.create(ln, parsed[ln][0].p, ln, parsed[ln][0].p + parsed[ln][0].c))))) - ) { - // This is the start of the next class member - break; - } - for (let k = 0; k < parsed[ln].length; k++) { - if (hasSqlFieldName) { - if ( - parsed[ln][k].l == ld.cls_langindex && - (parsed[ln][k].s == ld.cls_sqliden_attrindex || - parsed[ln][k].s == ld.error_attrindex || - (parsed[ln][k].s == ld.cls_delim_attrindex && - inKeywords && - [",", "]"].includes( - doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)), - ))) - ) { - if (parsed[ln][k].s == ld.cls_sqliden_attrindex) { - sqlFieldName = Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c); - } - brk = true; - break; - } - } else if ( - parsed[ln][k].l == ld.cls_langindex && - parsed[ln][k].s == ld.cls_keyword_attrindex && - doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)).toLowerCase() == - "sqlfieldname" - ) { - hasSqlFieldName = true; - } else if ( + // Check if a SqlFieldName is present + let sqlFieldName: Range | undefined, + hasSqlFieldName = false, + inKeywords = false, + brk = false; + for (let ln = i; ln < parsed.length; ln++) { + if ( + ln != i && + parsed[ln]?.length && + parsed[ln][0].l == ld.cls_langindex && + (parsed[ln][0].s == ld.cls_desc_attrindex || + (parsed[ln][0].s == ld.cls_keyword_attrindex && + isClassMember(doc.getText(Range.create(ln, parsed[ln][0].p, ln, parsed[ln][0].p + parsed[ln][0].c))))) + ) { + // This is the start of the next class member + break; + } + for (let k = 0; k < parsed[ln].length; k++) { + if (hasSqlFieldName) { + if ( parsed[ln][k].l == ld.cls_langindex && - parsed[ln][k].s == ld.cls_delim_attrindex && - doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)) == "[" + (parsed[ln][k].s == ld.cls_sqliden_attrindex || + parsed[ln][k].s == ld.error_attrindex || + (parsed[ln][k].s == ld.cls_delim_attrindex && + inKeywords && + [",", "]"].includes( + doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)), + ))) ) { - inKeywords = true; + if (parsed[ln][k].s == ld.cls_sqliden_attrindex) { + sqlFieldName = Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c); + } + brk = true; + break; } + } else if ( + parsed[ln][k].l == ld.cls_langindex && + parsed[ln][k].s == ld.cls_keyword_attrindex && + doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)).toLowerCase() == + "sqlfieldname" + ) { + hasSqlFieldName = true; + } else if ( + parsed[ln][k].l == ld.cls_langindex && + parsed[ln][k].s == ld.cls_delim_attrindex && + doc.getText(Range.create(ln, parsed[ln][k].p, ln, parsed[ln][k].p + parsed[ln][k].c)) == "[" + ) { + inKeywords = true; } - if (brk) break; } - if (hasSqlFieldName) { - if (sqlFieldName && sqlReservedWords.includes(doc.getText(sqlFieldName).toUpperCase())) { - // The SqlFieldName is a reserved word - diagnostics.push({ - severity: DiagnosticSeverity.Warning, - range: sqlFieldName, - message: "SqlFieldName is a SQL reserved word", - source: "InterSystems Language Server", - }); - } - } else if (sqlReservedWords.includes(propName.toUpperCase())) { - // The property name is a reserved word, and it's not corrected by a SqlFieldName + if (brk) break; + } + if (hasSqlFieldName) { + if (sqlFieldName && sqlReservedWords.includes(doc.getText(sqlFieldName).toUpperCase())) { + // The SqlFieldName is a reserved word diagnostics.push({ severity: DiagnosticSeverity.Warning, - range: propRange, - message: "Property name is a SQL reserved word", + range: sqlFieldName, + message: "SqlFieldName is a SQL reserved word", source: "InterSystems Language Server", }); } + } else if (sqlReservedWords.includes(propName.toUpperCase())) { + // The property name is a reserved word, and it's not corrected by a SqlFieldName + diagnostics.push({ + severity: DiagnosticSeverity.Warning, + range: propRange, + message: "Property name is a SQL reserved word", + source: "InterSystems Language Server", + }); } - if (nsNestedBlockLevel > 0) { - // Determine if we're still in the different namespace + } + if (nsContext && nsContext.nsNestedBlockLevel > 0) { + // Determine if we're still in the different namespace - if (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_brace_attrindex) { - const brace = doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)); - if (brace == "{") { - nsNestedBlockLevel++; - } else { - nsNestedBlockLevel--; - if (nsNestedBlockLevel == 0) { - // Ran off the end of that stack - currentNs = baseNs; - } + if (parsed[i][j].l == ld.cos_langindex && parsed[i][j].s == ld.cos_brace_attrindex) { + const brace = doc.getText(Range.create(i, parsed[i][j].p, i, parsed[i][j].p + parsed[i][j].c)); + if (brace == "{") { + nsContext.nsNestedBlockLevel++; + } else { + nsContext.nsNestedBlockLevel--; + if (nsContext.nsNestedBlockLevel == 0) { + // Ran off the end of that stack + nsContext.currentNs = nsContext.baseNs; } - } else if ( - // Ran off the end of the implementation - parsed[i][j].l == ld.cls_langindex || - // Ran off the end of the method - // In a routine - (/^objectscript(-int)?$/.test(doc.languageId) && - // This is the first token and it's at the start of the line - j == 0 && - parsed[i][j].p == 0 && - // This token is a label - parsed[i][j].l == ld.cos_langindex && - parsed[i][j].s == ld.cos_label_attrindex) || - // Exited the script - (doc.languageId == "objectscript-csp" && parsed[i][j].l == ld.html_langindex) - ) { - currentNs = baseNs; - nsNestedBlockLevel = 0; } + } else if ( + // Ran off the end of the implementation + parsed[i][j].l == ld.cls_langindex || + // Ran off the end of the method + // In a routine + (/^objectscript(-int)?$/.test(doc.languageId) && + // This is the first token and it's at the start of the line + j == 0 && + parsed[i][j].p == 0 && + // This token is a label + parsed[i][j].l == ld.cos_langindex && + parsed[i][j].s == ld.cos_label_attrindex) || + // Exited the script + (doc.languageId == "objectscript-csp" && parsed[i][j].l == ld.html_langindex) + ) { + nsContext.currentNs = nsContext.baseNs; + nsContext.nsNestedBlockLevel = 0; } } } } + } - if ( - settings.diagnostics.deprecation && - (methods.size > 0 || parameters.size > 0 || properties.size > 0 || classes.size > 0) - ) { - // Query the database for all Deprecated members or classes that we're referencing + if ( + settings.diagnostics.deprecation && + (methods.size > 0 || parameters.size > 0 || properties.size > 0 || classes.size > 0) + ) { + // Query the database for all Deprecated members or classes that we're referencing - // Build the query - const querydata: QueryData = { - query: - "SELECT Name, Parent AS Class, 'method' AS MemberType FROM %Dictionary.CompiledMethod WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + - "SELECT Name, Parent AS Class, 'parameter' AS MemberType FROM %Dictionary.CompiledParameter WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + - "SELECT Name, Parent AS Class, 'property' AS MemberType FROM %Dictionary.CompiledProperty WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + - "SELECT Name, NULL AS Class, 'class' AS MemberType FROM %Dictionary.CompiledClass WHERE Deprecated = 1 AND Name %INLIST $LISTFROMSTRING(?)", - parameters: [ - [ - ...new Set( - [...methods.keys()].map((elem) => { - return elem.split(":::")[0]; - }), - ), - ].join(","), - [ - ...new Set( - [...parameters.keys()].map((elem) => { - return elem.split(":::")[0]; - }), - ), - ].join(","), - [ - ...new Set( - [...properties.keys()].map((elem) => { - return elem.split(":::")[0]; - }), - ), - ].join(","), - [...classes.keys()].join(","), - ], - }; + // Build the query + const querydata: QueryData = { + query: + "SELECT Name, Parent AS Class, 'method' AS MemberType FROM %Dictionary.CompiledMethod WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + + "SELECT Name, Parent AS Class, 'parameter' AS MemberType FROM %Dictionary.CompiledParameter WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + + "SELECT Name, Parent AS Class, 'property' AS MemberType FROM %Dictionary.CompiledProperty WHERE Deprecated = 1 AND Parent %INLIST $LISTFROMSTRING(?) UNION ALL %PARALLEL " + + "SELECT Name, NULL AS Class, 'class' AS MemberType FROM %Dictionary.CompiledClass WHERE Deprecated = 1 AND Name %INLIST $LISTFROMSTRING(?)", + parameters: [ + [ + ...new Set( + [...methods.keys()].map((elem) => { + return elem.split(":::")[0]; + }), + ), + ].join(","), + [ + ...new Set( + [...parameters.keys()].map((elem) => { + return elem.split(":::")[0]; + }), + ), + ].join(","), + [ + ...new Set( + [...properties.keys()].map((elem) => { + return elem.split(":::")[0]; + }), + ), + ].join(","), + [...classes.keys()].join(","), + ], + }; - // Make the request - const respdata = await makeRESTRequest("POST", 1, "/action/query", server, querydata); - if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { - // We got data back + // Make the request + const respdata = server && (await makeRESTRequest("POST", 1, "/action/query", server, querydata)); - for (const row of respdata.data.result.content) { - // Create a Diagnostic for each Range that this class or member appears in the document + if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { + // We got data back - const memberstr: string = row.Class + ":::" + row.Name; - let ranges: Range[] | undefined; - if (row.MemberType === "method") { - ranges = methods.get(memberstr); - } else if (row.MemberType === "parameter") { - ranges = parameters.get(memberstr); - } else if (row.MemberType === "class") { - ranges = classes.get(row.Name); - } else { - ranges = properties.get(memberstr); - } - if (ranges !== undefined) { - for (const range of ranges) { - diagnostics.push({ - range: range, - severity: DiagnosticSeverity.Warning, - source: "InterSystems Language Server", - tags: [DiagnosticTag.Deprecated], - message: "Deprecated " + row.MemberType, - }); - } + for (const row of respdata.data.result.content) { + // Create a Diagnostic for each Range that this class or member appears in the document + + const memberstr: string = row.Class + ":::" + row.Name; + let ranges: Range[] | undefined; + if (row.MemberType === "method") { + ranges = methods.get(memberstr); + } else if (row.MemberType === "parameter") { + ranges = parameters.get(memberstr); + } else if (row.MemberType === "class") { + ranges = classes.get(row.Name); + } else { + ranges = properties.get(memberstr); + } + if (ranges !== undefined) { + for (const range of ranges) { + diagnostics.push({ + range: range, + severity: DiagnosticSeverity.Warning, + source: "InterSystems Language Server", + tags: [DiagnosticTag.Deprecated], + message: "Deprecated " + row.MemberType, + }); } } } } - if ((settings.diagnostics.classes || settings.diagnostics.routines) && otherNsDocs.size > 0) { - // Query the database for the existence of documents in other namespaces + } + if ((settings.diagnostics.classes || settings.diagnostics.routines) && otherNsDocs.size > 0) { + // Query the database for the existence of documents in other namespaces - const namespaces = new Set(); - otherNsDocs.forEach((v, k) => namespaces.add(k.split(":::")[0])); - for (const namespace of namespaces) { - // Build the query - let querydata: QueryData; - const otherClasses: string[] = []; - const otherRtns: string[] = []; + const namespaces = new Set(); + otherNsDocs.forEach((v, k) => namespaces.add(k.split(":::")[0])); + for (const namespace of namespaces) { + // Build the query + let querydata: QueryData; + const otherClasses: string[] = []; + const otherRtns: string[] = []; + otherNsDocs.forEach((v, k) => { + const [ns, doc] = k.split(":::"); + if (ns == namespace) { + switch (doc.slice(-3)) { + case "cls": + otherClasses.push(doc.slice(0, -4)); + break; + case "inc": + otherRtns.push(doc); + break; + default: + otherRtns.push(doc); + otherRtns.push(`${doc.slice(0, -3)}int`); + otherRtns.push(`${doc.slice(0, -3)}obj`); + } + } + }); + if (otherClasses.length && otherRtns.length) { + // Check for both classes and routines + querydata = { + query: + "SELECT Name||'.cls' AS Name FROM %Dictionary.ClassDefinition WHERE Name %INLIST $LISTFROMSTRING(?) " + + "UNION ALL %PARALLEL " + + "SELECT Name FROM %Library.RoutineMgr_StudioOpenDialog(?,?,?,?,?,?,?) WHERE Name %INLIST $LISTFROMSTRING(?)", + parameters: [otherClasses.join(","), "*.mac,*.inc,*.int,*.obj", 1, 1, 1, 1, 1, 0, otherRtns.join(",")], + }; + } else if (otherClasses.length) { + // Check for just classes + querydata = { + query: "SELECT Name||'.cls' AS Name FROM %Dictionary.ClassDefinition WHERE Name %INLIST $LISTFROMSTRING(?)", + parameters: [otherClasses.join(",")], + }; + } else { + // Check for just routines + querydata = { + query: + "SELECT Name FROM %Library.RoutineMgr_StudioOpenDialog(?,?,?,?,?,?,?) WHERE Name %INLIST $LISTFROMSTRING(?)", + parameters: ["*.mac,*.inc,*.int,*.obj", 1, 1, 1, 1, 1, 0, otherRtns.join(",")], + }; + } + + // Make the request + const respdata = + server && (await makeRESTRequest("POST", 1, "/action/query", { ...server, namespace }, querydata)); + if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { + // We got data back + + // Report Diagnostics for files that aren't in the returned data + respdata.data.result.content.forEach((e) => + otherNsDocs.delete( + `${namespace}:::${e.Name.endsWith(".int") || e.Name.endsWith(".obj") ? `${e.Name.slice(0, -3)}mac` : e.Name}`, + ), + ); otherNsDocs.forEach((v, k) => { const [ns, doc] = k.split(":::"); if (ns == namespace) { - switch (doc.slice(-3)) { - case "cls": - otherClasses.push(doc.slice(0, -4)); - break; - case "inc": - otherRtns.push(doc); - break; - default: - otherRtns.push(doc); - otherRtns.push(`${doc.slice(0, -3)}int`); - otherRtns.push(`${doc.slice(0, -3)}obj`); - } + v.forEach((range) => + diagnostics.push({ + severity: DiagnosticSeverity.Error, + range, + message: `${doc.endsWith("cls") ? "Class" : doc.endsWith("inc") ? "Include file" : "Routine"} "${doc.slice(0, -4)}" does not exist in namespace "${ns}"`, + source: "InterSystems Language Server", + }), + ); } }); - if (otherClasses.length && otherRtns.length) { - // Check for both classes and routines - querydata = { - query: - "SELECT Name||'.cls' AS Name FROM %Dictionary.ClassDefinition WHERE Name %INLIST $LISTFROMSTRING(?) " + - "UNION ALL %PARALLEL " + - "SELECT Name FROM %Library.RoutineMgr_StudioOpenDialog(?,?,?,?,?,?,?) WHERE Name %INLIST $LISTFROMSTRING(?)", - parameters: [otherClasses.join(","), "*.mac,*.inc,*.int,*.obj", 1, 1, 1, 1, 1, 0, otherRtns.join(",")], - }; - } else if (otherClasses.length) { - // Check for just classes - querydata = { - query: "SELECT Name||'.cls' AS Name FROM %Dictionary.ClassDefinition WHERE Name %INLIST $LISTFROMSTRING(?)", - parameters: [otherClasses.join(",")], - }; - } else { - // Check for just routines - querydata = { - query: - "SELECT Name FROM %Library.RoutineMgr_StudioOpenDialog(?,?,?,?,?,?,?) WHERE Name %INLIST $LISTFROMSTRING(?)", - parameters: ["*.mac,*.inc,*.int,*.obj", 1, 1, 1, 1, 1, 0, otherRtns.join(",")], - }; - } - - // Make the request - const respdata = await makeRESTRequest("POST", 1, "/action/query", { ...server, namespace }, querydata); - if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { - // We got data back - - // Report Diagnostics for files that aren't in the returned data - respdata.data.result.content.forEach((e) => - otherNsDocs.delete( - `${namespace}:::${e.Name.endsWith(".int") || e.Name.endsWith(".obj") ? `${e.Name.slice(0, -3)}mac` : e.Name}`, - ), - ); - otherNsDocs.forEach((v, k) => { - const [ns, doc] = k.split(":::"); - if (ns == namespace) { - v.forEach((range) => - diagnostics.push({ - severity: DiagnosticSeverity.Error, - range, - message: `${doc.endsWith("cls") ? "Class" : doc.endsWith("inc") ? "Include file" : "Routine"} "${doc.slice(0, -4)}" does not exist in namespace "${ns}"`, - source: "InterSystems Language Server", - }), - ); - } - }); - } } } } diff --git a/server/src/providers/documentLink.ts b/server/src/providers/documentLink.ts index 063b7d2..cc89055 100644 --- a/server/src/providers/documentLink.ts +++ b/server/src/providers/documentLink.ts @@ -2,7 +2,6 @@ import { DocumentLink, DocumentLinkParams, Range } from "vscode-languageserver/n import { documents } from "../utils/variables"; import * as ld from "../utils/languageDefinitions"; import { createDefinitionUri, getParsedDocument, getServerSpec, normalizeClassname } from "../utils/functions"; -import { ServerSpec } from "../utils/types"; export async function onDocumentLinks(params: DocumentLinkParams): Promise { const doc = documents.get(params.textDocument.uri); diff --git a/server/src/providers/formatting.ts b/server/src/providers/formatting.ts index ffd17c2..a8b4494 100644 --- a/server/src/providers/formatting.ts +++ b/server/src/providers/formatting.ts @@ -15,7 +15,7 @@ import { makeRESTRequest, normalizeClassname, } from "../utils/functions"; -import { CommandDoc, StudioOpenDialogFile, ServerSpec } from "../utils/types"; +import { CommandDoc, StudioOpenDialogFile } from "../utils/types"; import { documents } from "../utils/variables"; import * as ld from "../utils/languageDefinitions"; import commands from "../documentation/commands.json"; diff --git a/server/src/providers/refactoring.ts b/server/src/providers/refactoring.ts index 9ff0d1e..397a132 100644 --- a/server/src/providers/refactoring.ts +++ b/server/src/providers/refactoring.ts @@ -14,7 +14,7 @@ import { TextDocument } from "vscode-languageserver-textdocument"; import parameterTypes from "../documentation/parameterTypes.json"; import * as ld from "../utils/languageDefinitions"; -import { compressedline, QueryData, ServerSpec } from "../utils/types"; +import { compressedline, QueryData } from "../utils/types"; import { getServerSpec, findFullRange, diff --git a/server/src/providers/signatureHelp.ts b/server/src/providers/signatureHelp.ts index edd99b3..ed6156e 100644 --- a/server/src/providers/signatureHelp.ts +++ b/server/src/providers/signatureHelp.ts @@ -22,7 +22,7 @@ import { quoteUDLIdentifier, determineActiveParam, } from "../utils/functions"; -import { ServerSpec, SignatureHelpDocCache, SignatureHelpMacroContext } from "../utils/types"; +import { SignatureHelpDocCache, SignatureHelpMacroContext } from "../utils/types"; import { documents } from "../utils/variables"; import * as ld from "../utils/languageDefinitions"; diff --git a/server/src/providers/typeDefinition.ts b/server/src/providers/typeDefinition.ts index 2489a5f..4cc9dab 100644 --- a/server/src/providers/typeDefinition.ts +++ b/server/src/providers/typeDefinition.ts @@ -11,7 +11,6 @@ import { currentClass, getMemberType, } from "../utils/functions"; -import { ServerSpec } from "../utils/types"; import { documents } from "../utils/variables"; import * as ld from "../utils/languageDefinitions"; From 0b53ef2d7e449403f229d72c347eaa0a8c72a650 Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Mon, 24 Aug 2026 09:57:12 -0400 Subject: [PATCH 10/21] simp --- server/src/providers/diagnostic.ts | 9 ++++----- server/src/utils/functions.ts | 4 ++-- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/server/src/providers/diagnostic.ts b/server/src/providers/diagnostic.ts index 343b0f7..308961a 100644 --- a/server/src/providers/diagnostic.ts +++ b/server/src/providers/diagnostic.ts @@ -133,7 +133,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise 0) { // We got data back @@ -1431,8 +1431,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise 0) { // We got data back diff --git a/server/src/utils/functions.ts b/server/src/utils/functions.ts index 8e50925..aec3815 100644 --- a/server/src/utils/functions.ts +++ b/server/src/utils/functions.ts @@ -1210,13 +1210,13 @@ export async function makeRESTRequest( method: "GET" | "POST", api: number, path: string, - server: ServerSpec, + server?: ServerSpec, data?: any, checksum?: string, params?: any, ): Promise { // As of version 2.0.0, REST requests are made on the client side - return connection + return server && connection .sendRequest("intersystems/server/makeRESTRequest", { method, api, From c998f84a8611239487762e782113ed833f8b6df5 Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Mon, 24 Aug 2026 09:59:27 -0400 Subject: [PATCH 11/21] simplify --- server/src/providers/diagnostic.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/server/src/providers/diagnostic.ts b/server/src/providers/diagnostic.ts index 308961a..9bc4c48 100644 --- a/server/src/providers/diagnostic.ts +++ b/server/src/providers/diagnostic.ts @@ -615,11 +615,11 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise file.Name === classname + ".cls"); - if (filtered.length !== 1 && !classname.startsWith("%SYSTEM.")) { + if (nsContext && filtered.length !== 1 && !classname.startsWith("%SYSTEM.")) { diagnostics.push({ severity: DiagnosticSeverity.Warning, range: valrange, - message: `Class "${classname}" does not exist in namespace "${nsContext?.baseNs ?? ""}"`, + message: `Class "${classname}" does not exist in namespace "${nsContext.baseNs}"`, source: "InterSystems Language Server", }); } @@ -698,6 +698,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise 0 && settings.diagnostics.classes && lastpkgend != pkgrange.end.character && @@ -707,7 +708,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise 0) { // We got data back From 0527aadfc02d341f63bf0d9ff52ba1689367b6ab Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Mon, 24 Aug 2026 10:01:04 -0400 Subject: [PATCH 12/21] simp --- server/src/providers/hover.ts | 6 +++--- server/src/utils/functions.ts | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/server/src/providers/hover.ts b/server/src/providers/hover.ts index 75e408f..342493a 100644 --- a/server/src/providers/hover.ts +++ b/server/src/providers/hover.ts @@ -373,7 +373,7 @@ export async function onHover(params: TextDocumentPositionParams): Promise iden.lastIndexOf(".")) { + if (iden.lastIndexOf("_") > iden.lastIndexOf(".")) { // This table is projected from a multi-dimensional property // Split the identifier into the class and property @@ -1092,7 +1092,7 @@ export async function onHover(params: TextDocumentPositionParams): Promise { let result: string[] = []; @@ -780,7 +780,7 @@ export async function normalizeClassname( doc: TextDocument, parsed: compressedline[], clsname: string, - server: ServerSpec, + server: ServerSpec | undefined, line: number, allfiles?: StudioOpenDialogFile[], possiblecls?: PossibleClasses, From ba526521858f5fbfa7f2d02bd16209c8641225ca Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Mon, 24 Aug 2026 10:06:48 -0400 Subject: [PATCH 13/21] simp --- server/src/providers/completion.ts | 17 ++++++----------- server/src/providers/diagnostic.ts | 4 ++-- server/src/providers/hover.ts | 1 - server/src/utils/functions.ts | 11 +++++++---- 4 files changed, 15 insertions(+), 18 deletions(-) diff --git a/server/src/providers/completion.ts b/server/src/providers/completion.ts index 8202e7d..5d080ad 100644 --- a/server/src/providers/completion.ts +++ b/server/src/providers/completion.ts @@ -633,7 +633,7 @@ async function completionFullClassName( * * @param server The server that this document is associated with. */ -async function completionPackage(server: ServerSpec, settings: LanguageServerConfiguration): Promise { +async function completionPackage(server: ServerSpec | undefined, settings: LanguageServerConfiguration): Promise { const result: CompletionItem[] = []; // Get all the packages @@ -661,7 +661,7 @@ async function completionPackage(server: ServerSpec, settings: LanguageServerCon * * @param server The server that this document is associated with. */ -async function completionInclude(server: ServerSpec): Promise { +async function completionInclude(server?: ServerSpec): Promise { const result: CompletionItem[] = []; // Get all inc files @@ -689,7 +689,7 @@ async function globalsOrRoutines( line: number, token: number, settings: LanguageServerConfiguration, - server: ServerSpec, + server: ServerSpec | undefined, lineText: string, prefix: string = "", ): Promise { @@ -847,7 +847,7 @@ export async function onCompletion(params: CompletionParams): Promise closeParenCount && parenAndCommaRegex.test(prevline) && @@ -2380,7 +2375,7 @@ export async function onCompletion(params: CompletionParams): Promise { @@ -1035,7 +1035,7 @@ export async function getClassMemberContext( // Get the base class that this member is in const membercontext = await getClassMemberContext(doc, parsed, opentkn - 2, openln, server); if (membercontext.baseclass != "") { - const cls = await getMemberType(parsed, openln, opentkn - 1, membercontext.baseclass, member, server); + const cls = server && await getMemberType(parsed, openln, opentkn - 1, membercontext.baseclass, member, server); if (cls) { result = { baseclass: cls, @@ -1091,7 +1091,7 @@ export async function getClassMemberContext( ) == ","))) ) { // The token before the dot is a parameter, local variable, public variable or warning variable - const varClass = await determineVariableClass(doc, parsed, line, dot - 1, server, allfiles, inheritedpackages); + const varClass = server && await determineVariableClass(doc, parsed, line, dot - 1, server, allfiles, inheritedpackages); if (varClass) result = { baseclass: varClass, context: "instance" }; } else if ( dot > 0 && @@ -3499,7 +3499,10 @@ export function determineActiveParam(text: string): number { const showInternalCache: Map = new Map(); /** Determine if class members with the `Internal` keyword and system globals should be shown in the completion list */ -export async function showInternalForServer(server: ServerSpec): Promise { +export async function showInternalForServer(server?: ServerSpec): Promise { + if (! server) { + return false; + } const key = `${server.host}::${server.port}::${server.pathPrefix}::${server.username}`; let result = showInternalCache.get(key); if (result != undefined) return result; From 9a9016649f1db2787606f04236e84e71615fea92 Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Mon, 24 Aug 2026 10:09:54 -0400 Subject: [PATCH 14/21] simp --- server/src/providers/completion.ts | 142 ++++++++++++++--------------- 1 file changed, 69 insertions(+), 73 deletions(-) diff --git a/server/src/providers/completion.ts b/server/src/providers/completion.ts index 5d080ad..beae50a 100644 --- a/server/src/providers/completion.ts +++ b/server/src/providers/completion.ts @@ -567,7 +567,7 @@ class SchemaCache { async function completionFullClassName( doc: TextDocument, parsed: compressedline[], - server: ServerSpec, + server: ServerSpec | undefined, line: number, settings: LanguageServerConfiguration, ): Promise { @@ -1177,16 +1177,14 @@ export async function onCompletion(params: CompletionParams): Promise 0) { - // We got data back - - for (const method of respdata.data.result.content) { - const item: CompletionItem = { - label: method.Name, - kind: CompletionItemKind.Method, - data: "member", - documentation: { - kind: MarkupKind.Markdown, - value: documaticHtmlToMarkdown(method.Description), - }, - }; - if (method.Origin === method.baseclass) { - // Members from the base class should appear first - item.sortText = sortPrefix + method.Name; - } else { - item.sortText = item.label; - } - result.push(item); + } + const querydata = { + query: `SELECT Name, Description, Origin FROM %Dictionary.CompiledMethod WHERE Parent = ?${ + !(await showInternalForServer(server)) ? " AND Internal = 0" : "" + }`, + parameters: [thisclass], + }; + const respdata = await makeRESTRequest("POST", 1, "/action/query", server, querydata); + if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { + // We got data back + + for (const method of respdata.data.result.content) { + const item: CompletionItem = { + label: method.Name, + kind: CompletionItemKind.Method, + data: "member", + documentation: { + kind: MarkupKind.Markdown, + value: documaticHtmlToMarkdown(method.Description), + }, + }; + if (method.Origin === method.baseclass) { + // Members from the base class should appear first + item.sortText = sortPrefix + method.Name; + } else { + item.sortText = item.label; } + result.push(item); } } } From feaf2630b65fe3a9bb64af850ecc538b301f4ad5 Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Mon, 24 Aug 2026 10:14:52 -0400 Subject: [PATCH 15/21] simp --- server/src/providers/hover.ts | 50 +++++++++++++++++------------------ server/src/utils/functions.ts | 6 ++--- 2 files changed, 27 insertions(+), 29 deletions(-) diff --git a/server/src/providers/hover.ts b/server/src/providers/hover.ts index dfb635d..1bae0d6 100644 --- a/server/src/providers/hover.ts +++ b/server/src/providers/hover.ts @@ -433,7 +433,7 @@ export async function onHover(params: TextDocumentPositionParams): Promise tblname.lastIndexOf(".")) { // This table is projected from a multi-dimensional property, so we can't provide any info - } else if (server) { + } else { // Normalize the class name if there are imports const normalizedname = await normalizeClassname( doc, @@ -1233,31 +1233,29 @@ export async function onHover(params: TextDocumentPositionParams): Promise 0) { - // We got data back + // Determine the normalized class name + const normalizedcls = await normalizeClassname(doc, parsed, clsName, server, params.position.line); + if (normalizedcls !== "") { + const respdata = await makeRESTRequest("POST", 1, "/action/query", server, { + query: + "SELECT Description, Type FROM %Dictionary.CompiledParameter WHERE Name = ? AND (Parent = ? OR " + + "Parent %INLIST (SELECT $LISTFROMSTRING(PropertyClass) FROM %Dictionary.CompiledClass WHERE Name = ?))", + parameters: [param, normalizedcls, currentClass(doc, parsed)], + }); + if (respdata !== undefined) { + if (Array.isArray(respdata?.data?.result?.content) && respdata.data.result.content.length > 0) { + // We got data back - const header = `(**${normalizedcls}**) **${param}**${ - respdata.data.result.content[0].Type != "" ? ` As **${respdata.data.result.content[0].Type}**` : "" - }`; - return { - contents: { - kind: MarkupKind.Markdown, - value: markupValue(header, documaticHtmlToMarkdown(respdata.data.result.content[0].Description)), - }, - range: paramrange, - }; - } + const header = `(**${normalizedcls}**) **${param}**${ + respdata.data.result.content[0].Type != "" ? ` As **${respdata.data.result.content[0].Type}**` : "" + }`; + return { + contents: { + kind: MarkupKind.Markdown, + value: markupValue(header, documaticHtmlToMarkdown(respdata.data.result.content[0].Description)), + }, + range: paramrange, + }; } } } diff --git a/server/src/utils/functions.ts b/server/src/utils/functions.ts index 888fb89..b41c103 100644 --- a/server/src/utils/functions.ts +++ b/server/src/utils/functions.ts @@ -1035,7 +1035,7 @@ export async function getClassMemberContext( // Get the base class that this member is in const membercontext = await getClassMemberContext(doc, parsed, opentkn - 2, openln, server); if (membercontext.baseclass != "") { - const cls = server && await getMemberType(parsed, openln, opentkn - 1, membercontext.baseclass, member, server); + const cls = await getMemberType(parsed, openln, opentkn - 1, membercontext.baseclass, member, server); if (cls) { result = { baseclass: cls, @@ -3255,13 +3255,13 @@ export async function getMemberType( tkn: number, cls: string, member: string, - server: ServerSpec, + server?: ServerSpec, ): Promise { if ( // We assume these methods always return an instance of the class (["%New", "%Open", "%OpenId"].includes(member) && parsed[line][tkn].s != ld.cos_attr_attrindex) || // Config class Open methods function like %Open(Id) - (cls.startsWith("Config.") && member == "Open" && server.namespace.toUpperCase() == "%SYS") + (cls.startsWith("Config.") && member == "Open" && server?.namespace.toUpperCase() == "%SYS") ) { return cls; } From d715794a0c707006ef7d88a1860b5deaf3a6040c Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Mon, 24 Aug 2026 10:25:23 -0400 Subject: [PATCH 16/21] simp --- server/src/providers/hover.ts | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/server/src/providers/hover.ts b/server/src/providers/hover.ts index 1bae0d6..d0f7dc2 100644 --- a/server/src/providers/hover.ts +++ b/server/src/providers/hover.ts @@ -77,7 +77,6 @@ export async function onHover(params: TextDocumentPositionParams): Promise Date: Tue, 25 Aug 2026 11:24:03 -0400 Subject: [PATCH 17/21] namespace is potentially undefined --- common/src/types.ts | 2 +- server/src/providers/diagnostic.ts | 3 +-- server/src/providers/hover.ts | 2 +- server/src/utils/functions.ts | 2 +- 4 files changed, 4 insertions(+), 5 deletions(-) diff --git a/common/src/types.ts b/common/src/types.ts index 19a03b1..6c4ca6d 100644 --- a/common/src/types.ts +++ b/common/src/types.ts @@ -9,7 +9,7 @@ export interface ServerSpec { port: number; superserverPort?: number; pathPrefix: string; - namespace: string; + namespace?: string; username: string; credentials?: { auth?: { username: string; password: string }; diff --git a/server/src/providers/diagnostic.ts b/server/src/providers/diagnostic.ts index 5892314..8eec696 100644 --- a/server/src/providers/diagnostic.ts +++ b/server/src/providers/diagnostic.ts @@ -263,8 +263,7 @@ export async function onDiagnostics(params: DocumentDiagnosticParams): Promise = new Map(); // Keep track of current namespace for class/routine existence checks. - // Only meaningful when we have a server to check against. - const nsContext = server && { + const nsContext = server?.namespace && { server, baseNs: server.namespace.toUpperCase(), currentNs: server.namespace.toUpperCase(), diff --git a/server/src/providers/hover.ts b/server/src/providers/hover.ts index d0f7dc2..f4318f1 100644 --- a/server/src/providers/hover.ts +++ b/server/src/providers/hover.ts @@ -46,7 +46,7 @@ import xdataKeywords from "../documentation/keywords/XData.json"; function documaticLink(server: ServerSpec, cls: string): string { return `[${cls}](${server.scheme}://${server.host}:${server.port}${server.pathPrefix}/csp/documatic/%25CSP.Documatic.cls?LIBRARY=${encodeURIComponent( - server.namespace.toUpperCase(), + server.namespace?.toUpperCase() || "", )}&CLASSNAME=${encodeURIComponent(cls)})`; } diff --git a/server/src/utils/functions.ts b/server/src/utils/functions.ts index b41c103..110be26 100644 --- a/server/src/utils/functions.ts +++ b/server/src/utils/functions.ts @@ -3261,7 +3261,7 @@ export async function getMemberType( // We assume these methods always return an instance of the class (["%New", "%Open", "%OpenId"].includes(member) && parsed[line][tkn].s != ld.cos_attr_attrindex) || // Config class Open methods function like %Open(Id) - (cls.startsWith("Config.") && member == "Open" && server?.namespace.toUpperCase() == "%SYS") + (cls.startsWith("Config.") && member == "Open" && server?.namespace?.toUpperCase() == "%SYS") ) { return cls; } From 9ca0b5842aa39ad8d4ce5902780310cfe660df2f Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Tue, 25 Aug 2026 11:26:43 -0400 Subject: [PATCH 18/21] more fixes --- client/src/makeRESTRequest.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/makeRESTRequest.ts b/client/src/makeRESTRequest.ts index f53a0c7..5a62cc8 100644 --- a/client/src/makeRESTRequest.ts +++ b/client/src/makeRESTRequest.ts @@ -47,7 +47,7 @@ export async function makeRESTRequest( // Build the URL const url = encodeURI( - `${server.scheme}://${server.host}:${server.port}${server.pathPrefix}/api/atelier/${api ? `v${server.apiVersion}/${server.namespace}${path}` : ""}`, + `${server.scheme}://${server.host}:${server.port}${server.pathPrefix}/api/atelier/${api ? `v${server.apiVersion}/${server.namespace || ""}${path}` : ""}`, ); // Create the HTTPS agent From c1cf895033c943d0af2fbc817a77dd4bde4abd8c Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Tue, 25 Aug 2026 15:38:08 -0400 Subject: [PATCH 19/21] clean --- server/src/utils/functions.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/server/src/utils/functions.ts b/server/src/utils/functions.ts index 110be26..e9f3b10 100644 --- a/server/src/utils/functions.ts +++ b/server/src/utils/functions.ts @@ -1240,11 +1240,10 @@ export async function getServerSpec(uri: string): Promise Date: Tue, 25 Aug 2026 16:12:56 -0400 Subject: [PATCH 20/21] simp --- common/src/types.ts | 2 +- server/src/providers/hover.ts | 2 +- server/src/utils/functions.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/common/src/types.ts b/common/src/types.ts index 6c4ca6d..19a03b1 100644 --- a/common/src/types.ts +++ b/common/src/types.ts @@ -9,7 +9,7 @@ export interface ServerSpec { port: number; superserverPort?: number; pathPrefix: string; - namespace?: string; + namespace: string; username: string; credentials?: { auth?: { username: string; password: string }; diff --git a/server/src/providers/hover.ts b/server/src/providers/hover.ts index f4318f1..d0f7dc2 100644 --- a/server/src/providers/hover.ts +++ b/server/src/providers/hover.ts @@ -46,7 +46,7 @@ import xdataKeywords from "../documentation/keywords/XData.json"; function documaticLink(server: ServerSpec, cls: string): string { return `[${cls}](${server.scheme}://${server.host}:${server.port}${server.pathPrefix}/csp/documatic/%25CSP.Documatic.cls?LIBRARY=${encodeURIComponent( - server.namespace?.toUpperCase() || "", + server.namespace.toUpperCase(), )}&CLASSNAME=${encodeURIComponent(cls)})`; } diff --git a/server/src/utils/functions.ts b/server/src/utils/functions.ts index e9f3b10..ede6ae8 100644 --- a/server/src/utils/functions.ts +++ b/server/src/utils/functions.ts @@ -3260,7 +3260,7 @@ export async function getMemberType( // We assume these methods always return an instance of the class (["%New", "%Open", "%OpenId"].includes(member) && parsed[line][tkn].s != ld.cos_attr_attrindex) || // Config class Open methods function like %Open(Id) - (cls.startsWith("Config.") && member == "Open" && server?.namespace?.toUpperCase() == "%SYS") + (cls.startsWith("Config.") && member == "Open" && server?.namespace.toUpperCase() == "%SYS") ) { return cls; } From 4a6cea389d8625f958672f12b01af5cf771615a3 Mon Sep 17 00:00:00 2001 From: "Kuang-Chen (KC) Lu" Date: Tue, 25 Aug 2026 16:14:55 -0400 Subject: [PATCH 21/21] simp --- client/src/makeRESTRequest.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/makeRESTRequest.ts b/client/src/makeRESTRequest.ts index 5a62cc8..f53a0c7 100644 --- a/client/src/makeRESTRequest.ts +++ b/client/src/makeRESTRequest.ts @@ -47,7 +47,7 @@ export async function makeRESTRequest( // Build the URL const url = encodeURI( - `${server.scheme}://${server.host}:${server.port}${server.pathPrefix}/api/atelier/${api ? `v${server.apiVersion}/${server.namespace || ""}${path}` : ""}`, + `${server.scheme}://${server.host}:${server.port}${server.pathPrefix}/api/atelier/${api ? `v${server.apiVersion}/${server.namespace}${path}` : ""}`, ); // Create the HTTPS agent