/** Script diagnostics through the language server and the engine. */ import { type Dirent, existsSync, readdirSync, readFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import type { ToolResponse } from '../answer-json.js'; import { callProgress, callSignal } from '../call-signal.js'; import { cachedClasses, cachedClassesAsync, classesNamedIn, contradictedDiagnostics, declaredClasses, EXTERNAL_MEMBER, externalMemberIn, type MissingMember, missingMemberIn, staleAnalysisNote, uncachedClassNote, uncachedFor, uncachedForTheEngineNote, unknownTypeIn, unloadedTypes, } from '../class-cache.js'; import { readClassNote, updateClassNote } from '../class-note.js'; import type { LogEntry } from '../game-log.js'; import { engineExtras } from '../headless.js'; import { notAScript } from '../lsp_client.js'; import { withNearestFiles } from '../nearest.js'; import { resolveWithinProject } from '../paths.js'; import { folderFiles, projectFiles, steppedOverIn } from '../project-scan.js'; import { type LeftOut, leftOutAt } from '../project-walk.js'; import type { GodotServer } from '../server.js'; import { asParams, type OperationParams, readArray, readString, readStringArray } from '../tool-args.js'; import { editorHasOpen } from './editor-connection.js'; import { headlessOperation } from './headless-ops.js'; import { handleLSP, languageServerRefusal, languageServerSolutions, waitForTheEditorOpenedHere, } from './language-servers.js'; import { nonEmpty } from './notes.js'; import { type Checked, checkedProject } from './project-checks.js'; import { isDirectory, PATH_SOLUTIONS } from './refusals.js'; import { describeValue } from './validation.js'; /** * The scripts a script_diagnostics call names, each as its res:// path, or null for one file named * alone, which is answered in the single-script shape it always was. * * Several are named as a list, a folder, or both: a change across seventeen scripts was one call * each, so four were asked about and thirteen waited for the unit tier, which says less about a * parse error and says it minutes later. A folder is its `.gd` files at any depth, without the * directories the engine skips (a `.gdignore`, a hidden name) and without reading behind a link out * of the project. A link to a folder of the project is followed. * * No count is refused. A cap of three hundred told a flat test folder of 1192 scripts to name * narrower folders, which it had none of, or to call again for the rest, which nothing could name. * A script costs one round trip, a few tens of milliseconds, and the call reports progress, which * is what keeps a client from giving up on it. */ export function scriptsToDiagnose( projectPath: string, given: unknown, ): { ok: true; value: string[] | null } | { ok: false; reason: string } { const listed = Array.isArray(given); if (!listed) { const one = typeof given === 'string' ? resolveWithinProject(projectPath, given, { root: true }) : null; if (one === null || !one.ok || !isDirectory(one.absolutePath)) { return { ok: true, value: null }; } } const entries: unknown[] = listed ? given : [given]; if (entries.length === 0) { return { ok: false, reason: 'scriptPath is an empty list: name a script, a folder, or a list of either.', }; } const found: string[] = []; const empty: string[] = []; for (const [index, entry] of entries.entries()) { const entryScripts = scriptsNamedBy(projectPath, entry, listed ? `[${index}]` : ''); if (!entryScripts.ok) { return entryScripts; } found.push(...entryScripts.scripts); empty.push(...entryScripts.empty); } const unique = [...new Set(found)]; if (unique.length === 0) { return { ok: false, reason: empty.join(' ') }; } return { ok: true, value: unique }; } /** * The scripts one entry of a script_diagnostics call names: the script itself, or the `.gd` files of * a folder, with a sentence for a folder that holds none. [param at] is the entry's place in a list. */ function scriptsNamedBy( projectPath: string, entry: unknown, at: string, ): { ok: true; scripts: string[]; empty: string[] } | { ok: false; reason: string } { if (typeof entry !== 'string' || entry.trim() === '') { return { ok: false, reason: `scriptPath${at} is ${typeof entry === 'string' ? 'empty' : describeValue(entry)}, not a script or a folder in the project.`, }; } const location = resolveWithinProject(projectPath, entry, { root: true }); if (!location.ok) { return { ok: false, reason: location.reason }; } const fromRoot = location.relativePath.replace(/\/+$/, ''); if (!isDirectory(location.absolutePath)) { return { ok: true, scripts: [`res://${fromRoot}`], empty: [] }; } const inside = folderFiles(projectPath, location.absolutePath, ['.gd']).map((script) => fromRoot === '' ? `res://${script}` : `res://${fromRoot}/${script}`, ); return { ok: true, scripts: inside, empty: inside.length === 0 ? [noScriptUnder(projectPath, entry, location.absolutePath, fromRoot)] : [], }; } /** * Why [param scriptPath], one script of a script_diagnostics list, cannot be read by either the * language server or an engine, or null when it can. */ function unreadableScript(projectPath: string, scriptPath: string): string | null { const location = resolveWithinProject(projectPath, scriptPath); if (!location.ok) { return location.reason; } if (!existsSync(location.absolutePath)) { return missingScriptReason( projectPath, location.relativePath, `Script file does not exist: res://${location.relativePath}`, ); } return notAScript(location.relativePath); } /** [param said], the refusal for [param relativePath], a script the project does not hold, with the nearest it does. */ function missingScriptReason(projectPath: string, relativePath: string, said: string): string { const scripts = projectFiles(projectPath, ['.gd']).map((script) => `res://${script}`); const folder = dirname(relativePath.replaceAll('\\', '/')); const inFolder = join(projectPath, folder); // A step of the path can be a file or a ring of links, which cannot be listed. let listed: Dirent[]; try { listed = readdirSync(inFolder, { withFileTypes: true }); } catch { listed = []; } const beside = listed .filter((entry) => entry.isFile()) .map((entry) => `res://${folder === '.' ? '' : `${folder}/`}${entry.name}`); return withNearestFiles(said, `res://${relativePath}`, scripts, beside); } /** * The scripts of [param scripts], project-relative or res:// paths, that sit under a `.gdignore` or * in a nested project. Named on purpose they are checked like any other, and an error in one read * as the project's, although the engine never loads it: a class renamed elsewhere left one failing * to compile. gdharness's addons are loaded, and a link left out holds no script to read. */ function scriptsTheEngineNeverLoads( projectPath: string, scripts: readonly string[], ): Record { const ignored: string[] = []; const nested: string[] = []; for (const script of scripts.map((one) => one.replace(/^res:\/\//, ''))) { const why = leftOutAt(projectPath, script.split('/').slice(0, -1).join('/'))?.why; if (why === 'gdignore') { ignored.push(`res://${script}`); } else if (why === 'project') { nested.push(`res://${script}`); } } return { ...(ignored.length === 0 ? {} : { underGdignore: ignored, underGdignoreNote: 'The engine never loads a script under a folder holding a .gdignore, so what is reported for these does not stop the project from compiling or running.', }), ...(nested.length === 0 ? {} : { inNestedProject: nested, inNestedProjectNote: 'The engine never loads a script in a folder holding a project.godot of its own as part of this project, so what is reported for these does not stop the project from compiling or running.', }), }; } /** Why a folder named gave no script, with each folder below it that the walk stepped over. */ function noScriptUnder(projectPath: string, entry: string, absolute: string, fromRoot: string): string { const said = (stepped: LeftOut): string => { const folder = [fromRoot, stepped.folder].filter((step) => step !== '').join('/') || entry; const checkedWhenNamed = 'and a script there is checked when the script is named'; const reasons: Record = { gdharness: `is an addon gdharness installed, whose scripts are checked when it is named`, project: `holds a project.godot of its own, so the engine never loads what is under it as part of this project, ${checkedWhenNamed}`, link: 'is a link back up the tree or to nothing, so nothing behind it is read', outside: 'is a link that leads out of the project, so nothing behind it is read', gdignore: `holds a .gdignore, so the engine never loads what is under it, ${checkedWhenNamed}`, }; return `${folder} ${reasons[stepped.why]}`; }; const stepped = steppedOverIn(projectPath, absolute); return stepped.length === 0 ? `No .gd script is under ${entry}.` : `No .gd script is under ${entry} that a folder walk takes in: ${stepped.map(said).join('; ')}.`; } /** Why no language server of the project answered, and what the refusal would have offered. */ interface Unanswered { readonly reason: string; readonly solutions: string[]; } /** * What diagnostics compiled by a headless engine say beside them: why no language server answered, * in [param why], and what the engine's check leaves out, so that warnings: null and a diagnostic * without a column are not read as a script with nothing to warn about. */ function engineChecked(why: string): OperationParams { return { checkedBy: 'engine', languageServer: why, note: "No editor of this project is open to ask, so a headless engine compiled the scripts the way loading them does. It reports every error that stops a script compiling, at its line and without a column, but stops reading a script at its first syntax error, so an error after one shows once it is fixed, and so do its warnings, since a script that does not parse is not checked for any. A second engine reports the warnings, at the levels the project sets, by raising each warning set to warn as an error for that run only, since the engine tells a warning as one only to an editor. Each comes at its line without a column, and warnings is null when that engine could not answer. editor_launch with hidden: true opens this project's editor without a window, and its language server reports both with their columns.", }; } /** * What the engine puts around a warning it raised as an error. Kept in step with `RAISED` in * src/godot/operations/script_check.gd. */ const RAISED_WARNING = ' (Warning treated as error.)'; const PARSE_ERROR = 'Parse Error: '; /** [param raised], a warning the engine raised as an error, in the words the editor gives it. */ function asWarning(raised: string): string { const bare = raised.endsWith(RAISED_WARNING) ? raised.slice(0, -RAISED_WARNING.length) : raised; return bare.startsWith(PARSE_ERROR) ? bare.slice(PARSE_ERROR.length) : bare; } /** What a check of several scripts has found so far, added to as each script is answered. */ interface DiagnosticsTally { readonly reported: OperationParams[]; readonly nothingReported: string[]; errors: number; warnings: number; engineWarned: number | null; unread: number; byEngine: string | null; rebuilt: string[]; byServer: number; } /** The answer of a check of several scripts, from what [param tally] found in [param checked] of them. */ function diagnosticsSummary(tally: DiagnosticsTally, checked: number): Record { return { clean: tally.errors === 0 && tally.unread === 0, scriptsChecked: checked, errors: tally.errors, warnings: tally.engineWarned === null ? null : tally.warnings + tally.engineWarned, ...(tally.unread > 0 ? { scriptsNotRead: tally.unread } : {}), scripts: tally.reported, nothingReported: tally.nothingReported, ...(tally.byEngine === null ? { checkedBy: 'language server' } : engineChecked(tally.byEngine)), ...nonEmpty({ classesRebuiltFirst: tally.rebuilt }), ...(tally.byEngine !== null && tally.byServer > 0 ? { checkedBy: 'language server, then engine', checkedByLanguageServer: tally.byServer } : {}), }; } /** A script the language server refused, counted as unread, or the refusal when it ends the whole check. */ function tallyRefusedScript( tally: DiagnosticsTally, scriptPath: string, one: { readonly refusal: ToolResponse; readonly perScript: boolean }, ): ToolResponse | null { if (!one.perScript) { return one.refusal; } tally.unread += 1; tally.reported.push({ scriptPath, error: one.refusal.content[0]?.text ?? 'not read' }); return null; } /** What the language server said of one script, added to [param tally]. */ function tallyLanguageServerAnswer( tally: DiagnosticsTally, scriptPath: string, answer: OperationParams, ): void { tally.byServer += 1; tally.errors += Number(answer['errors']); tally.warnings += Number(answer['warnings']); // Every note an answer can carry is about a diagnostic, so none means nothing else either. if (readArray(answer, 'diagnostics')?.length === 0) { tally.nothingReported.push(scriptPath); } else { tally.reported.push(answer); } } /** What the engine said of one script, added to [param tally]. */ function tallyEngineAnswer(tally: DiagnosticsTally, answer: OperationParams): void { tally.errors += Number(answer['errors']); tally.engineWarned = answer['warnings'] === null || tally.engineWarned === null ? null : tally.engineWarned + Number(answer['warnings']); if (readArray(answer, 'diagnostics')?.length === 0) { tally.nothingReported.push(String(answer['scriptPath'])); } else { tally.reported.push(answer); } } /** The members the diagnostics name without a class, read against the line of the diagnosed script they are on. */ function deniedExternalMembers( diagnostics: readonly unknown[], scriptPath: string, cached: ReturnType, sourceOf: (resourcePath: string) => string | null, ): MissingMember[] { const external = diagnostics.filter((entry) => String(asParams(entry)['message']).includes(EXTERNAL_MEMBER), ); if (cached === null) { return []; } const diagnosed = external.length === 0 ? null : sourceOf(scriptPath); const lines = diagnosed?.split('\n') ?? []; return external .map((entry) => { const { message, line } = asParams(entry); return externalMemberIn( String(message), typeof line === 'number' ? lines[line - 1] : undefined, cached, ); }) .filter((missing): missing is MissingMember => missing !== null); } /** Counts [param scriptPath] as unread and says so when neither the language server nor an engine can read it. */ function tallyUnreadableScript(tally: DiagnosticsTally, projectPath: string, scriptPath: string): boolean { const unreadable = unreadableScript(projectPath, scriptPath); if (unreadable === null) { return false; } tally.unread += 1; tally.reported.push({ scriptPath, error: unreadable }); return true; } /** * script_diagnostics: what the language server reports, and the verdict that follows, for one * script or for several. Of several, a script with nothing to report is named under * `nothingReported` and every other is answered under `scripts`, in the shape one script is * answered in, with the counts summed beside them. A script the server would not read is named * there with why, and the rest are still asked about. The editor's language server being out of * reach is the same answer for every script, so it ends the call on the first. * * The scripts with something are what a folder is asked about for: answered in full, a clean * folder of 164 scripts came back as 164 identical entries around nothing. */ export async function handleScriptDiagnostics( server: GodotServer, args: OperationParams, ): Promise { const project = checkedProject(server, args); const scripts = project.ok ? scriptsToDiagnose(project.value.path, args['scriptPath']) : null; if (scripts !== null && !scripts.ok) { return server.createErrorResponse(scripts.reason); } if (scripts?.value == null) { return await diagnoseOneScript(server, args, project); } return await diagnoseSeveralScripts(server, args, project, scripts.value); } /** The diagnostics of the one script a call names, or of the scripts it names none of. */ async function diagnoseOneScript( server: GodotServer, args: OperationParams, project: Checked<{ path: string; file: string }>, ): Promise { // Judged here rather than by whichever half answers, which named a missing script by its // absolute path and refused a path outside the project with no remedy, while every other // tool given either gave the res:// path and the remedies. const asked = readString(args, 'scriptPath'); let ignored: Record = {}; if (project.ok && asked !== undefined) { const location = resolveWithinProject(project.value.path, asked); if (!location.ok) { return server.createErrorResponse(location.reason, PATH_SOLUTIONS); } if (!existsSync(location.absolutePath)) { return missingScript(server, project.value.path, location.relativePath); } ignored = scriptsTheEngineNeverLoads(project.value.path, [location.relativePath]); } const one = await diagnosticsOf(server, args); if ('noLanguageServer' in one) { const checked = project.ok ? await engineDiagnostics( server, project.value.path, [readString(args, 'scriptPath') ?? ''], one.noLanguageServer, ) : { refusal: project.response }; return 'refusal' in checked ? checked.refusal : server.jsonTextResponse({ ...checked.answers[0], ...engineChecked(one.noLanguageServer.reason), ...nonEmpty({ classesRebuiltFirst: checked.classesRebuiltFirst }), ...ignored, }); } return 'refusal' in one ? one.refusal : server.jsonTextResponse({ ...one.answer, checkedBy: 'language server', ...ignored, }); } /** The diagnostics of each of several scripts, the rest handed to one engine when the language server stops answering. */ async function diagnoseSeveralScripts( server: GodotServer, args: OperationParams, project: Checked<{ path: string; file: string }>, scripts: readonly string[], ): Promise { const progress = callProgress(); const cancelled = callSignal(); const tally: DiagnosticsTally = { reported: [], nothingReported: [], errors: 0, warnings: 0, // The engine's count of the scripts it checked, null when its warnings could not be read. engineWarned: 0, unread: 0, byEngine: null, rebuilt: [], // How many the language server answered before it stopped answering, if it did, so a check // that went on in the engine does not call every script the engine's. byServer: 0, }; for (const [at, scriptPath] of scripts.entries()) { // Nobody is left to read the answer, and a folder can take minutes. if (cancelled?.aborted === true) { return server.createErrorResponse(`Cancelled after ${at} of ${scripts.length} scripts.`); } progress?.(at + 1, `${at + 1} of ${scripts.length}: ${scriptPath}`); if (project.ok && tallyUnreadableScript(tally, project.value.path, scriptPath)) { continue; } const one = await diagnosticsOf(server, { ...args, scriptPath }); if ('noLanguageServer' in one) { const refusal = await diagnoseTheRestByEngine( server, project, scripts.slice(at), one.noLanguageServer, tally, at + 1, ); return refusal ?? severalScriptsAnswer(server, project, scripts, tally); } if ('refusal' in one) { const stop = tallyRefusedScript(tally, scriptPath, one); if (stop !== null) { return stop; } continue; } tallyLanguageServerAnswer(tally, scriptPath, one.answer); } return severalScriptsAnswer(server, project, scripts, tally); } /** The answer of a check of several scripts: the tally, and the scripts under a `.gdignore`. */ function severalScriptsAnswer( server: GodotServer, project: Checked<{ path: string; file: string }>, scripts: readonly string[], tally: DiagnosticsTally, ): ToolResponse { return server.jsonTextResponse({ ...diagnosticsSummary(tally, scripts.length), ...(project.ok ? scriptsTheEngineNeverLoads(project.value.path, scripts) : {}), }); } /** * The scripts [param left] checked in one engine, since what kept the language server from * answering the first keeps it from answering the others, and their answers added to [param tally]. * The refusal when the engine could not run, else null. */ async function diagnoseTheRestByEngine( server: GodotServer, project: Checked<{ path: string; file: string }>, left: readonly string[], noLanguageServer: Parameters[3], tally: DiagnosticsTally, position: number, ): Promise { // The engine answers a missing file as one it could not load, which reads as a broken script, // so those are named as the language server names them. const rest: string[] = []; const refusedHere = new Map(); for (const script of left) { const refused = project.ok ? unreadableScript(project.value.path, script) : null; if (refused === null) { rest.push(script); } else { refusedHere.set(script, refused); } } callProgress()?.(position, `${rest.length} script(s) left, compiled by a headless engine`); const checked = await engineDiagnostics( server, project.ok ? project.value.path : '', rest, noLanguageServer, ); if ('refusal' in checked) { return checked.refusal; } tally.rebuilt = checked.classesRebuiltFirst; for (const [script, error] of refusedHere) { tally.unread += 1; tally.reported.push({ scriptPath: script, error }); } for (const answer of checked.answers) { tallyEngineAnswer(tally, answer); } tally.byEngine = noLanguageServer.reason; return null; } /** The refusal for [param relativePath], a script the project does not hold, with the nearest it does. */ export function missingScript(server: GodotServer, projectPath: string, relativePath: string): ToolResponse { return server.createErrorResponse( missingScriptReason(projectPath, relativePath, `Script file does not exist: res://${relativePath}`), ); } /** * Whether each of [param paths], res:// paths, compiles, by as many headless engines as it takes: * an engine stops at the first script that raises an error, since every script after it that * depends on the failed one compiles in silence there, and the rest go to the next. One engine for * a project that compiles, and one more for each script that does not. */ export async function compileScripts( server: GodotServer, projectPath: string, paths: readonly string[], ): Promise< | { ok: true; payload: { checked: string[]; failed: string[]; scripts: unknown[] }; extras: OperationParams; classesRebuiltFirst: string[]; } | { ok: false; message: string } > { const payload = { checked: [] as string[], failed: [] as string[], scripts: [] as unknown[] }; const rebuilt: string[] = []; const messages: LogEntry[] = []; let left = [...paths]; while (left.length > 0) { const ran = await headlessOperation(server, 'check_scripts', { paths: left }, projectPath); if (!ran.ok) { return { ok: false, message: ran.message }; } const checked = (readArray(ran.payload, 'checked') ?? []).map(String); // An engine that read nothing would be asked the same again for ever. if (checked.length === 0) { return { ok: false, message: `check_scripts read none of ${left.length} script(s)` }; } payload.checked.push(...checked); payload.failed.push(...(readArray(ran.payload, 'failed') ?? []).map(String)); payload.scripts.push(...(readArray(ran.payload, 'scripts') ?? [])); rebuilt.push(...(readStringArray(ran.payload, 'classesRebuiltFirst') ?? [])); messages.push(...ran.messages); left = left.slice(checked.length); } return { ok: true, payload, extras: engineExtras({ messages }), classesRebuiltFirst: rebuilt }; } /** * The warnings of each of [param paths], res:// paths, by a headless engine that raises every * warning the project sets to warn as an error, which is how the engine reports one outside an * editor: each with its line and the engine's message as raised, by path. Null when the engine * could not answer, which leaves the warnings unknown rather than none. */ async function engineWarnings( server: GodotServer, projectPath: string, paths: readonly string[], ): Promise | null> { const ran = await headlessOperation(server, 'check_warnings', { paths: [...paths] }, projectPath); if (!ran.ok) { server.logDebug(`check_warnings did not answer: ${ran.message}`); return null; } return new Map( (readArray(ran.payload, 'scripts') ?? []).map((entry) => [ String(asParams(entry)['path']), (readArray(asParams(entry), 'warnings') ?? []).map((warning) => ({ line: Number(asParams(warning)['line']), message: String(asParams(warning)['message']), })), ]), ); } /** * [param scripts], paths inside the project, compiled by headless engines and answered each in * the shape the language server's diagnostics are, for a project whose editor's language server * cannot answer. Without an editor open the tool answered nothing at all, while the engine the * other headless tools start reports every error that stops a script compiling, at its line, up * to the first syntax error in each. * Warnings come from a second engine raising them as errors, and are null when it could not * answer, since none counted is then not none found. [param why] is what the language server answered, which a * refusal gives first, since it is the reason the engine was asked at all. */ async function engineDiagnostics( server: GodotServer, projectPath: string, scripts: readonly string[], why: Unanswered, ): Promise<{ answers: OperationParams[]; classesRebuiltFirst: string[] } | { refusal: ToolResponse }> { const resPaths = scripts.map((script) => { const contained = resolveWithinProject(projectPath, script); return contained.ok ? `res://${contained.relativePath}` : script; }); const checked = await compileScripts(server, projectPath, resPaths); if (!checked.ok) { return { refusal: server.createErrorResponse( `Diagnostics unavailable: ${why.reason.replace(/\.?$/, '.')} No headless engine could compile the scripts instead: ${checked.message}`, why.solutions, ), }; } const failures = new Map( (readArray(checked.payload, 'scripts') ?? []).map((entry) => [ String(asParams(entry)['path']), asParams(entry), ]), ); const errorsOf = scripts.map((_, at) => readArray(failures.get(resPaths[at] ?? '') ?? {}, 'errors') ?? []); const warned = await engineWarnings(server, projectPath, resPaths); const uncachedPer = uncachedFor( projectPath, errorsOf.map((errors) => errors.map((entry) => String(asParams(entry)['message']))), ); return { classesRebuiltFirst: checked.classesRebuiltFirst, answers: scripts.map((scriptPath, at) => { const failure = failures.get(resPaths[at] ?? ''); const errors = (errorsOf[at] ?? []).map((entry) => { const { line, message } = asParams(entry); // Line 0 is the engine's for the whole script, a dependency that failed to compile. return { severity: 'error', message, ...(typeof line === 'number' && line > 0 ? { line } : {}) }; }); // A warning the project already raises as an error was reported as one by the compile. const raised = new Set(errors.map(({ message, line }) => `${line ?? 0}:${String(message)}`)); const warnings = warned === null ? [] : (warned.get(resPaths[at] ?? '') ?? []) .filter(({ line, message }) => !raised.has(`${line}:${message}`)) .map(({ line, message }) => ({ severity: 'warning', message: asWarning(message), line })); const diagnostics = [...errors, ...warnings].toSorted((a, b) => (a.line ?? 0) - (b.line ?? 0)); const dependencies = readArray(failure ?? {}, 'dependencies_with_errors'); const uncached = uncachedPer[at] ?? []; return { scriptPath, clean: errors.length === 0, errors: errors.length, warnings: warned === null ? null : warnings.length, diagnostics, ...(dependencies === undefined ? {} : { dependenciesWithErrors: dependencies }), ...(uncached.length === 0 ? {} : { typesMissingFromTheClassCache: uncached.map(({ type, declaredIn }) => ({ type, declaredIn })), staleAnalysis: uncachedForTheEngineNote(projectPath, uncached), }), }; }), }; } /** * One script's diagnostics and verdict, or the refusal. `perScript` says whether the * refusal is about this script, such as a path that is not there, rather than about the * language server, which would refuse every script the same way. */ async function diagnosticsOf( server: GodotServer, args: OperationParams, ): Promise< | { answer: OperationParams } | { refusal: ToolResponse; perScript: boolean } | { noLanguageServer: Unanswered } > { const waited = await waitForTheEditorOpenedHere(server, args, []); if (waited !== null) { return { refusal: waited, perScript: false }; } const answer = await handleLSP(server, 'lsp_get_diagnostics', args); const payload = asParams(JSON.parse(answer.content[0]?.text ?? '{}')); const refused = languageServerRefusal(server, payload, 'Diagnostics'); // Compiled by an engine only when no editor of this project is on the bridge. A server still // reading the project is the right one and answers a call made again, and this project's own // editor is the authority on its scripts, so a language server of it that does not answer is // that editor's fault to name. An engine started beside it also waits on its next scan. const project = checkedProject(server, args); const ownEditor = project.ok && editorHasOpen(server, project.value.path); if (refused !== null && !refused.perScript && payload['stillReading'] !== true && !ownEditor) { return { noLanguageServer: { reason: typeof payload['error'] === 'string' ? payload['error'] : JSON.stringify(payload['error']), solutions: languageServerSolutions(server, payload), }, }; } if (refused !== null) { return refused; } const diagnostics = readArray(payload, 'diagnostics') ?? []; const errors = diagnostics.filter((entry) => asParams(entry)['severity'] === 'error').length; return { answer: { scriptPath: readString(args, 'scriptPath'), clean: errors === 0, errors, warnings: diagnostics.length - errors, diagnostics, ...(await whereTheFileDisagrees(server, diagnostics, args)), }, }; } /** * What the project's own files disagree with in a set of diagnostics, and what clears it. * * Two shapes, because a caller meets both for the same underlying reason and the text connects * them not at all. A method added to an existing `class_name` comes back as "is not present on the * inferred type" at every caller, while `script_info symbols` lists it from that same language * server a moment later. A class the editor has never loaded comes back as a base class it cannot * find or an identifier not declared, and mentions no type at all. Both read exactly like real * findings, and the only way past either is to decide the tool is wrong, which is a decision that * gets cheaper every time it is made. * * The remedies differ, which is why they are answered separately rather than as one list. An * analysed type that has gone stale is only cleared by restarting the editor. A class missing from * the cache is what `refresh_classes` rewrites, and a class in the cache that the editor still * cannot see is the editor's loaded list being behind. A launched game reads that cache, so these * are also the states where the game runs and the diagnostics deny it. * * Nothing is claimed that the files do not show. A member not found says nothing, since it may be * inherited or the diagnostic may simply be right, and calling a real finding stale is the * expensive direction. No engine is asked and nothing is re-analysed. */ async function whereTheFileDisagrees( server: GodotServer, diagnostics: unknown[], args: OperationParams, ): Promise { const messages = diagnostics .map((entry) => asParams(entry)['message']) .filter((message): message is string => typeof message === 'string'); // Before the project is resolved and anything is read, because a clean script is the ordinary // answer and this tool is called in a loop over a directory. Nothing below can find anything // when no message is of a shape that can be checked at all. const worthChecking = messages.some( (message) => missingMemberIn(message) !== null || unknownTypeIn(message) !== null || message.includes(EXTERNAL_MEMBER), ); const project = worthChecking ? checkedProject(server, args) : null; if (project === null || !project.ok) { return {}; } const projectPath = project.value.path; const cached = await cachedClassesAsync(projectPath); const sourceOf = (resourcePath: string): string | null => { const contained = resolveWithinProject(projectPath, resourcePath); if (!contained.ok || !existsSync(contained.absolutePath)) { return null; } try { return readFileSync(contained.absolutePath, 'utf8'); } catch { // A script the cache names and the disk will not hand over contradicts nothing, and the // diagnostics beside it are still worth answering with. return null; } }; // The diagnostics that name only a member, read against the line of the diagnosed script they // are on to find the class it was looked up on. const alsoDenied = deniedExternalMembers( diagnostics, readString(args, 'scriptPath') ?? '', cached, sourceOf, ); const contradicted = cached === null ? [] : contradictedDiagnostics(messages, cached, sourceOf, alsoDenied); // The walk of the project is the expensive half, so it happens only for a message that could // name a class at all rather than on every call that reached this far. const unloaded = messages.some((message) => unknownTypeIn(message) !== null) ? unloadedTypes(messages, declaredClasses(projectPath), cached) : []; return staleAnalysisAnswer(server, projectPath, cached, contradicted, unloaded); } /** What the diagnostics the file contradicts and the types the editor has not loaded add to an answer. */ function staleAnalysisAnswer( server: GodotServer, projectPath: string, cached: ReturnType, contradicted: ReturnType, unloaded: ReturnType, ): OperationParams { const notes: string[] = []; if (contradicted.length > 0) { notes.push(staleAnalysisNote(contradicted, staleDependencies(projectPath, cached, contradicted))); } const uncached = unloaded.filter((type) => !type.inTheClassCache); if (uncached.length > 0) { notes.push(uncachedClassNote(uncached.map((type) => type.type))); } const stale = unloaded.filter((type) => type.inTheClassCache); if (stale.length > 0) { // The remedy depends on which editor this is. One whose last scan wrote a shorter list than // the file holds a list behind the files and writes it again on every scan, so the scan // that clears this on a healthy editor does nothing on it: a caller was sent to a rescan // that had just told them not to rescan again. const remedy = editorWritesAShortList(server, projectPath) ? 'editor_rescan will not clear it here: this editor wrote the class cache from a list shorter than the file on its last scan and writes the same list on every scan, so editor_launch restart is what loads it.' : 'editor_rescan clears it, measured against a real editor with waiting the same length ruled out. editor_launch restart also does, and costs more.'; notes.push( `${stale.map((type) => type.type).join(', ')} ${stale.length === 1 ? 'is' : 'are'} in the class cache and still unresolved here, which is the editor's loaded list being behind rather than anything on disk. A game launched now reads the cache and resolves ${stale.length === 1 ? 'it' : 'them'}, so the run and the diagnostics disagree. ${remedy}`, ); } return { ...(contradicted.length === 0 ? {} : { contradictedByTheFile: contradicted }), ...(unloaded.length === 0 ? {} : { typesTheEditorHasNotLoaded: unloaded }), ...(notes.length === 0 ? {} : { staleAnalysis: notes.join(' ') }), }; } /** * What the stale types are built from, which is the lever rather than a detail: a held copy * is refreshed when one of its own dependencies changes and not when it changes itself, so * the useful thing to hand a caller is the list of files worth touching. Only the methods' and * properties' scripts, which are the ones the lever is offered for. */ function staleDependencies( projectPath: string, cached: ReturnType, contradicted: ReturnType, ): string[] { const dependsOn = new Set(); for (const one of contradicted.filter((entry) => entry.kind === 'method' || entry.kind === 'property')) { const source = cached === null ? null : sourceOfClass(projectPath, one.declaredIn); if (source === null || cached === null) { continue; } for (const name of classesNamedIn(source, cached)) { if (name !== one.type) { dependsOn.add(name); } } } return [...dependsOn]; } /** * Whether the editor connected now is the one whose last scan or save of [param projectPath] * wrote a class cache shorter than the file. Such an editor holds a class list behind the files * and writes it over the cache every time, so a rescan cannot load the class the diagnostics * cannot resolve. Only a restart does, and the advice has to say so rather than send the caller * back to the scan that just refused. Read from the project's note, so a server that replaced * the one that saw the loss knows too. Kept by pid, so a restarted editor starts clean. */ export function editorWritesAShortList(server: GodotServer, projectPath: string): boolean { const recorded = readClassNote(projectPath)?.shortListEditorPid; return recorded !== undefined && recorded === (server.godotBridge.getStatus().editorPid ?? null); } /** * The classes the editor connected now could not see before a scan whose end no rescan saw, from * the note any server on [param projectPath] left. By pid, because a restarted editor compiles * every script afresh and holds nothing compiled without them. */ export function unseenBeforeAnUnfinishedScan(server: GodotServer, projectPath: string): string[] { const noted = readClassNote(projectPath)?.unseenBeforeAnUnfinishedScan; if (noted === undefined || noted.editorPid !== (server.godotBridge.getStatus().editorPid ?? null)) { return []; } return [...noted.classes]; } /** * Notes [param classes] as unseen by the editor connected now before a scan whose end this rescan * did not see, or takes the note down when [param classes] is empty. Written only when it changes. */ export async function noteUnseenBeforeAnUnfinishedScan( server: GodotServer, projectPath: string, classes: readonly string[], ): Promise { const editorPid = server.godotBridge.getStatus().editorPid ?? null; await updateClassNote(projectPath, (note) => { if (classes.length === 0 && note?.unseenBeforeAnUnfinishedScan === undefined) { return null; } const { unseenBeforeAnUnfinishedScan: _replaced, ...rest } = note ?? { rebuiltWith: [] }; return { ...rest, ...(classes.length === 0 ? {} : { unseenBeforeAnUnfinishedScan: { editorPid, classes: [...classes].toSorted() } }), }; }); } /** Records that the editor connected now wrote [param projectPath]'s class cache short. */ export async function noteAShortListEditor(server: GodotServer, projectPath: string): Promise { const editorPid = server.godotBridge.getStatus().editorPid ?? null; await updateClassNote(projectPath, (note) => ({ ...note, rebuiltWith: note?.rebuiltWith ?? [], shortListEditorPid: editorPid, })); } /** * The project's global classes [param scriptPath] names in its file, other than its own. * * Compared in the `res://` form the cache writes, since reloadScript also takes `core/rules.gd`, * and spelled that way the script's own class would pass for one it names, and a failed reload of * it would be told to reload itself first. */ export function classesAScriptNames(projectPath: string, scriptPath: string): string[] { const resourcePath = scriptPath.startsWith('res://') ? scriptPath : `res://${scriptPath.replace(/^\/+/, '')}`; const source = sourceOfClass(projectPath, resourcePath); const known = cachedClasses(projectPath) ?? declaredClasses(projectPath); return source === null ? [] : classesNamedIn(source, known).filter((name) => known.get(name) !== resourcePath); } /** A declaring script's text, or null when the path will not open. */ export function sourceOfClass(projectPath: string, resourcePath: string): string | null { const contained = resolveWithinProject(projectPath, resourcePath); if (!contained.ok || !existsSync(contained.absolutePath)) { return null; } try { return readFileSync(contained.absolutePath, 'utf8'); } catch { return null; } }