/** Creating and modifying scripts and renaming symbols. */ import { existsSync } from 'node:fs'; import type { ToolResponse } from '../answer-json.js'; import { cachedClassesAsync, isToolScript } from '../class-cache.js'; import { errorMessage } from '../errors.js'; import { type GodotLSPClient, LSPTimeout, normalizeLSPError } from '../lsp_client.js'; import { resolveWithinProject } from '../paths.js'; import { applyRewrites } from '../rename.js'; import { type NameTaken, type RenameOutcome, renameSymbol, writeLeftAloneDetail } from '../rename-symbol.js'; import type { GodotServer } from '../server.js'; import { asParams, type OperationParams, readBoolean, readNonEmptyString, readString, readStringArray, } from '../tool-args.js'; import { editorHasOpen, settingKeysOf } from './editor-connection.js'; import { headlessOperation, headlessOutcomeAnswer, runHeadless } from './headless-ops.js'; import { lsp, waitForTheEditorOpenedHere } from './language-servers.js'; import { alsoSayWhatTheEditorCannotSee, asksForAPreview, classesAMemberRenameCannotType, editorTakesSettingsWritten, noteOfASettling, settleRenameInEditor, settleRenameOnDisk, } from './move-file.js'; import { checkedProject, containProjectFiles } from './project-checks.js'; import { withRemedyBehindALink } from './refusals.js'; import { rebuildClassCache, reloadInEditor, unsavedInEditorNote } from './reload.js'; import { handleRescanFilesystem } from './rescan.js'; import { writtenOutThroughALink } from './scene-writes.js'; import { compileScripts, editorWritesAShortList, missingScript, sourceOfClass, } from './script-diagnostics.js'; /** * Why the editor still answers from the script it compiled before a write, for [param problem], the * reason its reload failed. The reasons are written with and without a full stop of their own. */ export function staleCopyNote(problem: string): string { return `The editor serving the project still holds the copy of the script it compiled before, since reloading it failed: ${problem.replace(/\.$/, '')}.`; } /** * script_edit create, and the class it declares put in the class list. * * The engine resolves a `class_name` from the list, not from the file, so a script written with * one is not a class to anything that starts next until the list is rebuilt. The answer said * `registered: true` on the strength of the argument alone, and nothing had written the list. */ export async function handleCreateScript(server: GodotServer, args: OperationParams): Promise { const project = checkedProject(server, args); if (!project.ok) { return project.response; } const contained = containProjectFiles(server, args); if (!contained.ok) { return contained.response; } const behindALink = writtenOutThroughALink(server, project.value.path, contained.value, ['scriptPath']); if (behindALink !== null) { return behindALink; } const { op: _op, projectPath: _projectPath, ...params } = contained.value; const created = await headlessOperation(server, 'create_script', params, project.value.path); const declared = created.ok ? (readString(created.payload, 'class_name') ?? '') : ''; if (!created.ok || declared === '') { return headlessOutcomeAnswer(server, created); } const rebuilt = await rebuildClassCache(server, project.value.path); const fullPath = readString(created.payload, 'full_path'); const registered = (await cachedClassesAsync(project.value.path))?.get(declared) === fullPath; // The engine that wrote the script compiled it against the list from before, which did not hold // its class, so a script naming its own class (a static constructor returning one) read as one // that does not parse. const parsesOnTheList = registered && created.payload['parses'] === false && (await parsesOnTheRebuiltList(server, project.value.path, fullPath)); const answered = headlessOutcomeAnswer(server, { ...created, payload: { ...created.payload, ...(parsesOnTheList ? { parses: true, parsesNote: `The engine that wrote it compiled it against the class list from before, which did not hold ${declared}, so the errors it printed naming ${declared} are its own and not the script's. An engine started on the rebuilt list compiles it.`, } : {}), registered, ...registrationNoteOf(registered, declared, rebuilt), }, }); if (!server.godotBridge.isConnected()) { return answered; } // The editor holding the project takes its class list in at a scan rather than from the file, // so the class written here stayed a name it could not resolve until somebody called // editor_rescan. Scanned here, as modify reloads the script there, unless this editor's scans // write a list shorter than the file: a scan there loses classes, and the note says what loads them. // An editor with another project open has no scan of this one to run. const scanned = answered.isError === true || !editorHasOpen(server, project.value.path) || editorWritesAShortList(server, project.value.path) ? null : await handleRescanFilesystem(server, { projectPath: project.value.path }); return await alsoSayWhatTheEditorCannotSee( server, scanned === null ? answered : withEditorScan(server, answered, scanned), args, ); } /** Whether the script at [param fullPath] compiles without a failure against the rebuilt class list. */ async function parsesOnTheRebuiltList( server: GodotServer, projectPath: string, fullPath: string | undefined, ): Promise { if (fullPath === undefined) { return false; } const recompiled = await compileScripts(server, projectPath, [fullPath]); return recompiled.ok && recompiled.payload.failed.length === 0; } /** Why the class [param declared] is not in the class list, when it is not [param registered]. */ function registrationNoteOf( registered: boolean, declared: string, rebuilt: { ok: true } | { ok: false; message: string }, ): { registrationNote?: string } { if (registered) { return {}; } return { registrationNote: rebuilt.ok ? `The class list was rebuilt and does not hold ${declared} at this script, so nothing started next resolves it by name. project_import refresh_classes says what the list holds and why.` : `The class list could not be rebuilt, so nothing started next resolves ${declared} by name: ${rebuilt.message}`, }; } /** [param answered] with what the editor's scan after it brought in, or why it did not. */ function withEditorScan(server: GodotServer, answered: ToolResponse, scanned: ToolResponse): ToolResponse { const payload = asParams(JSON.parse(answered.content[0]?.text ?? '{}')); const scan = scanned.isError === true ? null : asParams(JSON.parse(scanned.content[0]?.text ?? '{}')); const broughtIn = scan === null ? undefined : readStringArray(scan, 'broughtIn'); return server.jsonTextResponse({ ...payload, editorRescanned: scan !== null && readBoolean(scan, 'ok') === true, ...(broughtIn === undefined ? {} : { broughtIn }), ...(scan === null ? { editorRescanNote: `The editor was asked to scan for the new class and answered: ${scanned.content[0]?.text ?? 'nothing'}`, } : readBoolean(scan, 'ok') === true ? {} : { editorRescanNote: readString(scan, 'note') ?? JSON.stringify(scan) }), }); } /** * script_edit modify, and the editor serving the project given the script it now is. * * A headless engine writes the file, and an editor that had loaded the script keeps the copy it * compiled until something reloads it: Godot rereads a changed script when its window takes the * focus, which a hidden editor never does. scene_signal connect then answered methodFound false * for a method just added, while the game it played ran that method. */ export async function handleModifyScript(server: GodotServer, args: OperationParams): Promise { const project = checkedProject(server, args); if (project.ok) { const contained = containProjectFiles(server, args); if (!contained.ok) { return contained.response; } const behindALink = writtenOutThroughALink(server, project.value.path, contained.value, ['scriptPath']); if (behindALink !== null) { return behindALink; } } const written = await runHeadless(server, 'modify_script', args); const scriptPath = readNonEmptyString(args, 'scriptPath'); if ( written.isError === true || !project.ok || scriptPath === undefined || !editorHasOpen(server, project.value.path) ) { return written; } const answer = asParams(JSON.parse(written.content[0]?.text ?? '{}')); const source = sourceOfClass(project.value.path, scriptPath); const done = await reloadInEditor( server, [{ script: scriptPath, tool: source !== null && isToolScript(source) }], project.value.path, ); const problem = done.notReloaded[0]?.problem; const notes = [ ...(problem === undefined ? [] : [staleCopyNote(problem)]), ...(done.unsavedInEditor.length > 0 ? [unsavedInEditorNote(done.unsavedInEditor)] : []), ]; return server.jsonTextResponse({ ...answer, editorReloaded: done.reloaded.length > 0, ...(done.reloadedFirst.length > 0 ? { reloadedFirst: done.reloadedFirst } : {}), ...(done.unsavedInEditor.length > 0 ? { unsavedInEditor: true } : {}), ...(notes.length > 0 ? { editorNote: notes.join(' ') } : {}), }); } /** * script_edit rename: a class or a member renamed wherever the engine uses it, every other * occurrence of the word answered rather than changed, and the editor or the class cache brought * up to the new name so nothing started next resolves the old one. */ export async function handleRenameSymbol(server: GodotServer, given: OperationParams): Promise { const project = checkedProject(server, given); if (!project.ok) { return project.response; } const contained = containProjectFiles(server, given); if (!contained.ok) { return contained.response; } const args = contained.value; const projectPath = project.value.path; const scriptPath = resolveWithinProject(projectPath, readNonEmptyString(args, 'scriptPath') ?? ''); if (!scriptPath.ok) { return server.createErrorResponse( withRemedyBehindALink(scriptPath, 'Rename it in the project that holds the script.'), ); } if (!existsSync(scriptPath.absolutePath)) { return missingScript(server, projectPath, scriptPath.relativePath); } const asked = readNonEmptyString(args, 'newScriptPath'); const moveTo = asked === undefined ? null : resolveWithinProject(projectPath, asked); if (moveTo !== null && !moveTo.ok) { return server.createErrorResponse(moveTo.reason); } const waited = await waitForTheEditorOpenedHere(server, args, []); if (waited !== null) { return waited; } const symbol = readNonEmptyString(args, 'symbol') ?? ''; const newName = readNonEmptyString(args, 'newName') ?? ''; const unseen = await classesAMemberRenameCannotType(server, args, scriptPath.absolutePath, symbol); if (unseen !== null) { return unseen; } return await renameInTheProject(server, args, { projectPath, scriptAbsolute: scriptPath.absolutePath, newScriptAbsolute: moveTo === null ? null : moveTo.absolutePath, symbol, newName, }); } /** Works out a rename of a symbol that the checks have let through, and has it written. */ async function renameInTheProject( server: GodotServer, args: OperationParams, rename: { projectPath: string; scriptAbsolute: string; newScriptAbsolute: string | null; symbol: string; newName: string; }, ): Promise { const { projectPath, scriptAbsolute, newScriptAbsolute, symbol, newName } = rename; // Held in an object rather than a variable, because it is set inside the calls below and read // after them, which a narrowed `let` would type as never having been set. const languageServer: { problem: string | null; initialized: boolean } = { problem: null, initialized: false, }; const askTheLanguageServer = async (question: (client: GodotLSPClient) => Promise): Promise => { const client = await lsp(server); try { if (!languageServer.initialized) { await client.initialize(projectPath); languageServer.initialized = true; } return await question(client); } catch (error) { // A server that took the request in is there. The rename says what ran out instead. if (!(error instanceof LSPTimeout)) { languageServer.problem = normalizeLSPError(error, client.port); } throw error; } }; const outcome = await renameSymbol( { projectPath, scriptPath: scriptAbsolute, symbol, newName, newScriptPath: newScriptAbsolute, }, { namesTaken: async (names, base) => { const answer = await headlessOperation( server, 'names_taken', { names: [...names], base: base ?? '' }, projectPath, ); if (!answer.ok) { throw new Error( `the engine could not be asked whether ${names.join(' or ')} is taken: ${answer.message}`, ); } return Object.fromEntries( Object.entries(asParams(answer.payload['taken'])).map(([name, entry]): [string, NameTaken] => { const read = asParams(entry); return [ name, { as: readStringArray(read, 'as') ?? [], declaredBy: readString(read, 'declaredBy') ?? null }, ]; }), ); }, references: async (absolute, text, at) => await askTheLanguageServer((client) => client.getReferences(absolute, text, at.line, at.character)), definitions: async (absolute, text, at) => await askTheLanguageServer((client) => client.getDefinitions(absolute, text, at.line, at.character)), }, ).catch((error: unknown): RenameOutcome => ({ ok: false, reason: errorMessage(error) })); return await writeTheRename(server, args, rename, outcome, languageServer.problem); } /** Writes the rename [param outcome] worked out, or answers why it could not be, and settles the editor. */ async function writeTheRename( server: GodotServer, args: OperationParams, rename: { projectPath: string; symbol: string; newName: string }, outcome: RenameOutcome, languageServerProblem: string | null, ): Promise { const { projectPath, symbol, newName } = rename; if (!outcome.ok) { return renameRefused(server, outcome, languageServerProblem); } foldTheLeftAloneDetail(projectPath, symbol, outcome); if (asksForAPreview(args)) { return server.jsonTextResponse({ preview: true, ...outcome.report }); } // A script moved under an autoload is renamed in project.godot too, which an editor serving the // project has to take up or it saves the old path back. const settingsBefore = editorHasOpen(server, projectPath) ? settingKeysOf(projectPath) : null; try { applyRewrites(outcome.rewrites); } catch (error) { return server.createErrorResponse(`Nothing was renamed: ${errorMessage(error)}`); } const editorSettled = editorHasOpen(server, projectPath) ? await settleRenameInEditor(server, projectPath, outcome.scriptsInOrder, { gone: outcome.moved === null ? [] : [outcome.moved.from], oldClass: outcome.isClass ? symbol : null, newClass: outcome.isClass ? newName : null, }) : await settleRenameOnDisk(server, projectPath, outcome.scriptsInOrder, { rebuildCache: outcome.isClass || outcome.moved !== null, moved: outcome.moved !== null, }); return await answerTheRename(server, outcome, editorSettled, projectPath, settingsBefore); } /** Writes the lines a rename left alone to a file and points the report at it, when there are too many to list. */ function foldTheLeftAloneDetail( projectPath: string, symbol: string, outcome: Extract, ): void { if (outcome.detail === null) { return; } const file = writeLeftAloneDetail(projectPath, symbol, outcome.detail); const folded = asParams(outcome.report['leftAloneDetail']); outcome.report['leftAloneDetail'] = { file, note: `Too many lines were left alone to list here, and none of them is a use: every comment, documentation line, string and text file line that only shares the word, and every other symbol of the same name, is in ${file} with its text. The newest ten of these files are kept and older ones removed as new ones are written.`, ...folded, }; } /** The refusal for a rename that could not be worked out, naming the language server's problem when it had one. */ function renameRefused( server: GodotServer, outcome: Extract, languageServerProblem: string | null, ): ToolResponse { if (languageServerProblem !== null) { return server.createErrorResponse( `Renaming a member needs the editor's language server, because which uses of the name are this class's depends on the types only the engine's analyser knows. ${languageServerProblem}`, [ 'editor_launch opens the editor, whose language server this uses', 'A class_name is renamed from the files and needs no editor', ], ); } const said = outcome.conflicts === undefined ? '' : ` ${outcome.conflicts.join('; ')}.`; return server.createErrorResponse(`${outcome.reason}${said}`, outcome.advice ?? []); } /** The answer of a rename that was written, with the editor's settling and its settings folded in. */ async function answerTheRename( server: GodotServer, outcome: Extract, editorSettled: { ok: boolean; report: Record }, projectPath: string, settingsBefore: ReturnType | null, ): Promise { const settings = settingsBefore === null ? null : await editorTakesSettingsWritten(server, projectPath, settingsBefore); const settled = settings === null ? editorSettled : { ok: editorSettled.ok && settings.ok, report: { ...editorSettled.report, editor: { ...asParams(editorSettled.report['editor']), ...Object.fromEntries( Object.entries(settings.report).filter(([key]) => key !== 'settingsNote'), ), }, ...(typeof settings.report['settingsNote'] === 'string' ? { note: [readString(editorSettled.report, 'note'), settings.report['settingsNote']] .filter((one) => one !== undefined) .join(' '), } : {}), }, }; // ok answers for the whole rename, the compile included, so a false one beside a list of // changed files has to say that the files were still written, or it reads as nothing done. const leftChanged = noteOfASettling( settled, 'The rename was written: every file under changed now reads as shown there and is left that way. ok is false for what came after the write, said under editor or compiled.', ); return server.jsonTextResponse({ ok: settled.ok, written: true, ...outcome.report, ...settled.report, ...(leftChanged === undefined ? {} : { note: leftChanged }), }); }