editor/code: Re-apply code format

This commit is contained in:
Tetsuharu Ohzeki 2023-07-11 22:35:10 +09:00
parent 9d06aa55b4
commit f7823f3106
17 changed files with 180 additions and 175 deletions

View File

@ -37,23 +37,23 @@ export class AstInspector implements vscode.HoverProvider, vscode.DefinitionProv
constructor(ctx: Ctx) {
ctx.pushExtCleanup(
vscode.languages.registerHoverProvider({ scheme: "rust-analyzer" }, this)
vscode.languages.registerHoverProvider({ scheme: "rust-analyzer" }, this),
);
ctx.pushExtCleanup(vscode.languages.registerDefinitionProvider({ language: "rust" }, this));
vscode.workspace.onDidCloseTextDocument(
this.onDidCloseTextDocument,
this,
ctx.subscriptions
ctx.subscriptions,
);
vscode.workspace.onDidChangeTextDocument(
this.onDidChangeTextDocument,
this,
ctx.subscriptions
ctx.subscriptions,
);
vscode.window.onDidChangeVisibleTextEditors(
this.onDidChangeVisibleTextEditors,
this,
ctx.subscriptions
ctx.subscriptions,
);
}
dispose() {
@ -85,7 +85,7 @@ export class AstInspector implements vscode.HoverProvider, vscode.DefinitionProv
private findAstTextEditor(): undefined | vscode.TextEditor {
return vscode.window.visibleTextEditors.find(
(it) => it.document.uri.scheme === "rust-analyzer"
(it) => it.document.uri.scheme === "rust-analyzer",
);
}
@ -100,7 +100,7 @@ export class AstInspector implements vscode.HoverProvider, vscode.DefinitionProv
// additional positional params are omitted
provideDefinition(
doc: vscode.TextDocument,
pos: vscode.Position
pos: vscode.Position,
): vscode.ProviderResult<vscode.DefinitionLink[]> {
if (!this.rustEditor || doc.uri.toString() !== this.rustEditor.document.uri.toString()) {
return;
@ -132,7 +132,7 @@ export class AstInspector implements vscode.HoverProvider, vscode.DefinitionProv
// additional positional params are omitted
provideHover(
doc: vscode.TextDocument,
hoverPosition: vscode.Position
hoverPosition: vscode.Position,
): vscode.ProviderResult<vscode.Hover> {
if (!this.rustEditor) return;
@ -159,7 +159,7 @@ export class AstInspector implements vscode.HoverProvider, vscode.DefinitionProv
private parseRustTextRange(
doc: vscode.TextDocument,
astLine: string
astLine: string,
): undefined | vscode.Range {
const parsedRange = /(\d+)\.\.(\d+)/.exec(astLine);
if (!parsedRange) return;

View File

@ -8,13 +8,13 @@ import { exec } from "child_process";
export async function bootstrap(
context: vscode.ExtensionContext,
config: Config,
state: PersistentState
state: PersistentState,
): Promise<string> {
const path = await getServer(context, config, state);
if (!path) {
throw new Error(
"Rust Analyzer Language Server is not available. " +
"Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
"Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation).",
);
}
@ -34,7 +34,7 @@ export async function bootstrap(
async function getServer(
context: vscode.ExtensionContext,
config: Config,
state: PersistentState
state: PersistentState,
): Promise<string | undefined> {
const explicitPath = process.env["__RA_LSP_SERVER_DEBUG"] ?? config.serverPath;
if (explicitPath) {
@ -49,7 +49,7 @@ async function getServer(
const bundled = vscode.Uri.joinPath(context.extensionUri, "server", `rust-analyzer${ext}`);
const bundledExists = await vscode.workspace.fs.stat(bundled).then(
() => true,
() => false
() => false,
);
if (bundledExists) {
let server = bundled;
@ -58,7 +58,7 @@ async function getServer(
const dest = vscode.Uri.joinPath(config.globalStorageUri, `rust-analyzer${ext}`);
let exists = await vscode.workspace.fs.stat(dest).then(
() => true,
() => false
() => false,
);
if (exists && config.package.version !== state.serverVersion) {
await vscode.workspace.fs.delete(dest);
@ -81,7 +81,7 @@ async function getServer(
"run `cargo xtask install --server` to build the language server from sources. " +
"If you feel that your platform should be supported, please create an issue " +
"about that [here](https://github.com/rust-lang/rust-analyzer/issues) and we " +
"will consider it."
"will consider it.",
);
return undefined;
}
@ -131,7 +131,7 @@ async function patchelf(dest: vscode.Uri): Promise<void> {
} else {
resolve(stdout);
}
}
},
);
handle.stdin?.write(expression);
handle.stdin?.end();
@ -139,6 +139,6 @@ async function patchelf(dest: vscode.Uri): Promise<void> {
} finally {
await vscode.workspace.fs.delete(origFile);
}
}
},
);
}

View File

@ -34,21 +34,24 @@ export const LINKED_COMMANDS = new Map<string, ra.CommandLink>();
// add code to remove a target command from the map after the link is
// clicked, but assuming most links in hover sheets won't be clicked anyway
// this code won't change the overall memory use much.
setInterval(function cleanupOlderCommandLinks() {
// keys are returned in insertion order, we'll keep a few
// of recent keys available, and clean the rest
const keys = [...LINKED_COMMANDS.keys()];
const keysToRemove = keys.slice(0, keys.length - 10);
for (const key of keysToRemove) {
LINKED_COMMANDS.delete(key);
}
}, 10 * 60 * 1000);
setInterval(
function cleanupOlderCommandLinks() {
// keys are returned in insertion order, we'll keep a few
// of recent keys available, and clean the rest
const keys = [...LINKED_COMMANDS.keys()];
const keysToRemove = keys.slice(0, keys.length - 10);
for (const key of keysToRemove) {
LINKED_COMMANDS.delete(key);
}
},
10 * 60 * 1000,
);
function renderCommand(cmd: ra.CommandLink): string {
const commandId = randomUUID();
LINKED_COMMANDS.set(commandId, cmd);
return `[${cmd.title}](command:rust-analyzer.linkToCommand?${encodeURIComponent(
JSON.stringify([commandId])
JSON.stringify([commandId]),
)} '${cmd.tooltip}')`;
}
@ -57,7 +60,7 @@ function renderHoverActions(actions: ra.CommandLinkGroup[]): vscode.MarkdownStri
.map(
(group) =>
(group.title ? group.title + " " : "") +
group.commands.map(renderCommand).join(" | ")
group.commands.map(renderCommand).join(" | "),
)
.join("___");
@ -72,7 +75,7 @@ export async function createClient(
initializationOptions: vscode.WorkspaceConfiguration,
serverOptions: lc.ServerOptions,
config: Config,
unlinkedFiles: vscode.Uri[]
unlinkedFiles: vscode.Uri[],
): Promise<lc.LanguageClient> {
const clientOptions: lc.LanguageClientOptions = {
documentSelector: [{ scheme: "file", language: "rust" }],
@ -93,7 +96,7 @@ export async function createClient(
async configuration(
params: lc.ConfigurationParams,
token: vscode.CancellationToken,
next: lc.ConfigurationRequest.HandlerSignature
next: lc.ConfigurationRequest.HandlerSignature,
) {
const resp = await next(params, token);
if (resp && Array.isArray(resp)) {
@ -117,7 +120,7 @@ export async function createClient(
async handleDiagnostics(
uri: vscode.Uri,
diagnosticList: vscode.Diagnostic[],
next: lc.HandleDiagnosticsSignature
next: lc.HandleDiagnosticsSignature,
) {
const preview = config.previewRustcOutput;
const errorCode = config.useRustcErrorCode;
@ -137,20 +140,20 @@ export async function createClient(
const folder = vscode.workspace.getWorkspaceFolder(uri)?.uri.fsPath;
if (folder) {
const parentBackslash = uri.fsPath.lastIndexOf(
pathSeparator + "src"
pathSeparator + "src",
);
const parent = uri.fsPath.substring(0, parentBackslash);
if (parent.startsWith(folder)) {
const path = vscode.Uri.file(
parent + pathSeparator + "Cargo.toml"
parent + pathSeparator + "Cargo.toml",
);
void vscode.workspace.fs.stat(path).then(async () => {
const choice = await vscode.window.showInformationMessage(
`This rust file does not belong to a loaded cargo project. It looks like it might belong to the workspace at ${path.path}, do you want to add it to the linked Projects?`,
"Yes",
"No",
"Don't show this again"
"Don't show this again",
);
switch (choice) {
case undefined:
@ -168,14 +171,14 @@ export async function createClient(
config
.get<any[]>("linkedProjects")
?.concat(pathToInsert),
false
false,
);
break;
case "Don't show this again":
await config.update(
"showUnlinkedFileNotification",
false,
false
false,
);
break;
}
@ -222,7 +225,7 @@ export async function createClient(
document: vscode.TextDocument,
position: vscode.Position,
token: vscode.CancellationToken,
_next: lc.ProvideHoverSignature
_next: lc.ProvideHoverSignature,
) {
const editor = vscode.window.activeTextEditor;
const positionOrRange = editor?.selection?.contains(position)
@ -236,7 +239,7 @@ export async function createClient(
client.code2ProtocolConverter.asTextDocumentIdentifier(document),
position: positionOrRange,
},
token
token,
)
.then(
(result) => {
@ -250,7 +253,7 @@ export async function createClient(
(error) => {
client.handleFailedRequest(lc.HoverRequest.type, token, error, null);
return Promise.resolve(null);
}
},
);
},
// Using custom handling of CodeActions to support action groups and snippet edits.
@ -260,14 +263,14 @@ export async function createClient(
range: vscode.Range,
context: vscode.CodeActionContext,
token: vscode.CancellationToken,
_next: lc.ProvideCodeActionsSignature
_next: lc.ProvideCodeActionsSignature,
) {
const params: lc.CodeActionParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
range: client.code2ProtocolConverter.asRange(range),
context: await client.code2ProtocolConverter.asCodeActionContext(
context,
token
token,
),
};
return client.sendRequest(lc.CodeActionRequest.type, params, token).then(
@ -283,21 +286,21 @@ export async function createClient(
if (lc.CodeAction.is(item)) {
assert(
!item.command,
"We don't expect to receive commands in CodeActions"
"We don't expect to receive commands in CodeActions",
);
const action = await client.protocol2CodeConverter.asCodeAction(
item,
token
token,
);
result.push(action);
continue;
}
assert(
isCodeActionWithoutEditsAndCommands(item),
"We don't expect edits or commands here"
"We don't expect edits or commands here",
);
const kind = client.protocol2CodeConverter.asCodeActionKind(
(item as any).kind
(item as any).kind,
);
const action = new vscode.CodeAction(item.title, kind);
const group = (item as any).group;
@ -351,7 +354,7 @@ export async function createClient(
}
return result;
},
(_error) => undefined
(_error) => undefined,
);
},
},
@ -364,7 +367,7 @@ export async function createClient(
"rust-analyzer",
"Rust Analyzer Language Server",
serverOptions,
clientOptions
clientOptions,
);
// To turn on all proposed features use: client.registerProposedFeatures();
@ -400,7 +403,7 @@ class ExperimentalFeatures implements lc.StaticFeature {
}
initialize(
_capabilities: lc.ServerCapabilities,
_documentSelector: lc.DocumentSelector | undefined
_documentSelector: lc.DocumentSelector | undefined,
): void {}
dispose(): void {}
}
@ -419,7 +422,7 @@ class OverrideFeatures implements lc.StaticFeature {
}
initialize(
_capabilities: lc.ServerCapabilities,
_documentSelector: lc.DocumentSelector | undefined
_documentSelector: lc.DocumentSelector | undefined,
): void {}
dispose(): void {}
}

View File

@ -48,7 +48,7 @@ export function analyzerStatus(ctx: CtxInit): Cmd {
})();
ctx.pushExtCleanup(
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-status", tdcp)
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-status", tdcp),
);
return async () => {
@ -80,7 +80,7 @@ export function memoryUsage(ctx: CtxInit): Cmd {
})();
ctx.pushExtCleanup(
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-memory", tdcp)
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-memory", tdcp),
);
return async () => {
@ -126,7 +126,7 @@ export function matchingBrace(ctx: CtxInit): Cmd {
const response = await client.sendRequest(ra.matchingBrace, {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(editor.document),
positions: editor.selections.map((s) =>
client.code2ProtocolConverter.asPosition(s.active)
client.code2ProtocolConverter.asPosition(s.active),
),
});
editor.selections = editor.selections.map((sel, idx) => {
@ -196,7 +196,7 @@ export function onEnter(ctx: CtxInit): Cmd {
const lcEdits = await client
.sendRequest(ra.onEnter, {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(
editor.document
editor.document,
),
position: client.code2ProtocolConverter.asPosition(editor.selection.active),
})
@ -249,7 +249,7 @@ export function parentModule(ctx: CtxInit): Cmd {
client,
uri,
position,
locations.map((loc) => lc.Location.create(loc.targetUri, loc.targetRange))
locations.map((loc) => lc.Location.create(loc.targetUri, loc.targetRange)),
);
}
};
@ -357,7 +357,7 @@ export function ssr(ctx: CtxInit): Cmd {
const position = editor.selection.active;
const selections = editor.selections;
const textDocument = client.code2ProtocolConverter.asTextDocumentIdentifier(
editor.document
editor.document,
);
const options: vscode.InputBoxOptions = {
@ -397,9 +397,9 @@ export function ssr(ctx: CtxInit): Cmd {
});
await vscode.workspace.applyEdit(
await client.protocol2CodeConverter.asWorkspaceEdit(edit, token)
await client.protocol2CodeConverter.asWorkspaceEdit(edit, token),
);
}
},
);
};
}
@ -428,12 +428,12 @@ export function syntaxTree(ctx: CtxInit): Cmd {
vscode.workspace.onDidChangeTextDocument(
this.onDidChangeTextDocument,
this,
ctx.subscriptions
ctx.subscriptions,
);
vscode.window.onDidChangeActiveTextEditor(
this.onDidChangeActiveTextEditor,
this,
ctx.subscriptions
ctx.subscriptions,
);
}
@ -452,7 +452,7 @@ export function syntaxTree(ctx: CtxInit): Cmd {
async provideTextDocumentContent(
uri: vscode.Uri,
ct: vscode.CancellationToken
ct: vscode.CancellationToken,
): Promise<string> {
const rustEditor = ctx.activeRustEditor;
if (!rustEditor) return "";
@ -475,12 +475,12 @@ export function syntaxTree(ctx: CtxInit): Cmd {
ctx.pushExtCleanup(new AstInspector(ctx));
ctx.pushExtCleanup(
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-syntax-tree", tdcp)
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-syntax-tree", tdcp),
);
ctx.pushExtCleanup(
vscode.languages.setLanguageConfiguration("ra_syntax_tree", {
brackets: [["[", ")"]],
})
}),
);
return async () => {
@ -513,7 +513,7 @@ function viewFileUsingTextDocumentContentProvider(
requestType: lc.RequestType<lc.TextDocumentPositionParams, string, void>,
uri: string,
scheme: string,
shouldUpdate: boolean
shouldUpdate: boolean,
): Cmd {
const tdcp = new (class implements vscode.TextDocumentContentProvider {
readonly uri = vscode.Uri.parse(uri);
@ -522,12 +522,12 @@ function viewFileUsingTextDocumentContentProvider(
vscode.workspace.onDidChangeTextDocument(
this.onDidChangeTextDocument,
this,
ctx.subscriptions
ctx.subscriptions,
);
vscode.window.onDidChangeActiveTextEditor(
this.onDidChangeActiveTextEditor,
this,
ctx.subscriptions
ctx.subscriptions,
);
}
@ -546,7 +546,7 @@ function viewFileUsingTextDocumentContentProvider(
async provideTextDocumentContent(
_uri: vscode.Uri,
ct: vscode.CancellationToken
ct: vscode.CancellationToken,
): Promise<string> {
const rustEditor = ctx.activeRustEditor;
if (!rustEditor) return "";
@ -554,7 +554,7 @@ function viewFileUsingTextDocumentContentProvider(
const client = ctx.client;
const params = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(
rustEditor.document
rustEditor.document,
),
position: client.code2ProtocolConverter.asPosition(rustEditor.selection.active),
};
@ -602,7 +602,7 @@ export function interpretFunction(ctx: CtxInit): Cmd {
ra.interpretFunction,
uri,
`rust-analyzer-interpret-function`,
false
false,
);
}
@ -614,12 +614,12 @@ export function viewFileText(ctx: CtxInit): Cmd {
vscode.workspace.onDidChangeTextDocument(
this.onDidChangeTextDocument,
this,
ctx.subscriptions
ctx.subscriptions,
);
vscode.window.onDidChangeActiveTextEditor(
this.onDidChangeActiveTextEditor,
this,
ctx.subscriptions
ctx.subscriptions,
);
}
@ -638,14 +638,14 @@ export function viewFileText(ctx: CtxInit): Cmd {
async provideTextDocumentContent(
_uri: vscode.Uri,
ct: vscode.CancellationToken
ct: vscode.CancellationToken,
): Promise<string> {
const rustEditor = ctx.activeRustEditor;
if (!rustEditor) return "";
const client = ctx.client;
const params = client.code2ProtocolConverter.asTextDocumentIdentifier(
rustEditor.document
rustEditor.document,
);
return client.sendRequest(ra.viewFileText, params, ct);
}
@ -656,7 +656,7 @@ export function viewFileText(ctx: CtxInit): Cmd {
})();
ctx.pushExtCleanup(
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-file-text", tdcp)
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-file-text", tdcp),
);
return async () => {
@ -677,12 +677,12 @@ export function viewItemTree(ctx: CtxInit): Cmd {
vscode.workspace.onDidChangeTextDocument(
this.onDidChangeTextDocument,
this,
ctx.subscriptions
ctx.subscriptions,
);
vscode.window.onDidChangeActiveTextEditor(
this.onDidChangeActiveTextEditor,
this,
ctx.subscriptions
ctx.subscriptions,
);
}
@ -701,7 +701,7 @@ export function viewItemTree(ctx: CtxInit): Cmd {
async provideTextDocumentContent(
_uri: vscode.Uri,
ct: vscode.CancellationToken
ct: vscode.CancellationToken,
): Promise<string> {
const rustEditor = ctx.activeRustEditor;
if (!rustEditor) return "";
@ -709,7 +709,7 @@ export function viewItemTree(ctx: CtxInit): Cmd {
const params = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(
rustEditor.document
rustEditor.document,
),
};
return client.sendRequest(ra.viewItemTree, params, ct);
@ -721,7 +721,7 @@ export function viewItemTree(ctx: CtxInit): Cmd {
})();
ctx.pushExtCleanup(
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-item-tree", tdcp)
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-item-tree", tdcp),
);
return async () => {
@ -746,7 +746,7 @@ function crateGraph(ctx: CtxInit, full: boolean): Cmd {
enableScripts: true,
retainContextWhenHidden: true,
localResourceRoots: [nodeModulesPath],
}
},
);
const params = {
full: full,
@ -835,7 +835,7 @@ export function expandMacro(ctx: CtxInit): Cmd {
const expanded = await client.sendRequest(ra.expandMacro, {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(
editor.document
editor.document,
),
position,
});
@ -851,7 +851,7 @@ export function expandMacro(ctx: CtxInit): Cmd {
})();
ctx.pushExtCleanup(
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-expand-macro", tdcp)
vscode.workspace.registerTextDocumentContentProvider("rust-analyzer-expand-macro", tdcp),
);
return async () => {
@ -883,7 +883,7 @@ export function addProject(ctx: CtxInit): Cmd {
return discoverWorkspace([file], discoverProjectCommand, {
cwd: path.dirname(file.uri.fsPath),
});
})
}),
);
ctx.addToDiscoveredWorkspaces(workspaces);
@ -901,14 +901,14 @@ async function showReferencesImpl(
client: LanguageClient | undefined,
uri: string,
position: lc.Position,
locations: lc.Location[]
locations: lc.Location[],
) {
if (client) {
await vscode.commands.executeCommand(
"editor.action.showReferences",
vscode.Uri.parse(uri),
client.protocol2CodeConverter.asPosition(position),
locations.map(client.protocol2CodeConverter.asLocation)
locations.map(client.protocol2CodeConverter.asLocation),
);
}
}
@ -925,7 +925,7 @@ export function applyActionGroup(_ctx: CtxInit): Cmd {
if (!selectedAction) return;
await vscode.commands.executeCommand(
"rust-analyzer.resolveCodeAction",
selectedAction.arguments
selectedAction.arguments,
);
};
}
@ -1000,7 +1000,7 @@ export function resolveCodeAction(ctx: CtxInit): Cmd {
documentChanges: itemEdit.documentChanges?.filter((change) => "kind" in change),
};
const fileSystemEdit = await client.protocol2CodeConverter.asWorkspaceEdit(
lcFileSystemEdit
lcFileSystemEdit,
);
await vscode.workspace.applyEdit(fileSystemEdit);
await applySnippetWorkspaceEdit(edit);
@ -1053,12 +1053,12 @@ export function peekTests(ctx: CtxInit): Cmd {
const locations: lc.Location[] = tests.map((it) =>
lc.Location.create(
it.runnable.location!.targetUri,
it.runnable.location!.targetSelectionRange
)
it.runnable.location!.targetSelectionRange,
),
);
await showReferencesImpl(client, uri, position, locations);
}
},
);
};
}
@ -1146,7 +1146,7 @@ export function viewMemoryLayout(ctx: CtxInit): Cmd {
"memory_layout",
"[Memory Layout]",
vscode.ViewColumn.Two,
{ enableScripts: true }
{ enableScripts: true },
);
document.webview.html = `<!DOCTYPE html>

View File

@ -38,7 +38,7 @@ export class Config {
vscode.workspace.onDidChangeConfiguration(
this.onDidChangeConfiguration,
this,
ctx.subscriptions
ctx.subscriptions,
);
this.refreshLogging();
this.configureLanguage();
@ -64,7 +64,7 @@ export class Config {
this.configureLanguage();
const requiresReloadOpt = this.requiresReloadOpts.find((opt) =>
event.affectsConfiguration(opt)
event.affectsConfiguration(opt),
);
if (!requiresReloadOpt) return;
@ -210,8 +210,8 @@ export class Config {
Object.entries(extraEnv).map(([k, v]) => [
k,
typeof v !== "string" ? v.toString() : v,
])
)
]),
),
);
}
get traceExtension() {
@ -306,7 +306,7 @@ export class Config {
// to interact with.
export function prepareVSCodeConfig<T>(
resp: T,
cb?: (key: Extract<keyof T, string>, res: { [key: string]: any }) => void
cb?: (key: Extract<keyof T, string>, res: { [key: string]: any }) => void,
): T {
if (Is.string(resp)) {
return substituteVSCodeVariableInString(resp) as T;
@ -349,7 +349,7 @@ export function substituteVariablesInEnv(env: Env): Env {
}
}
return [`env:${key}`, { deps: [...deps], value }];
})
}),
);
const resolved = new Set<string>();
@ -457,7 +457,7 @@ function computeVscodeVar(varName: string): string | null {
if (varName in supportedVariables) {
const fn = expectNotUndefined(
supportedVariables[varName],
`${varName} should not be undefined here`
`${varName} should not be undefined here`,
);
return fn();
} else {

View File

@ -42,10 +42,10 @@ export type Workspace =
export function fetchWorkspace(): Workspace {
const folders = (vscode.workspace.workspaceFolders || []).filter(
(folder) => folder.uri.scheme === "file"
(folder) => folder.uri.scheme === "file",
);
const rustDocuments = vscode.workspace.textDocuments.filter((document) =>
isRustDocument(document)
isRustDocument(document),
);
return folders.length === 0
@ -61,7 +61,7 @@ export function fetchWorkspace(): Workspace {
export async function discoverWorkspace(
files: readonly vscode.TextDocument[],
command: string[],
options: ExecOptions
options: ExecOptions,
): Promise<JsonProject> {
const paths = files.map((f) => `"${f.uri.fsPath}"`).join(" ");
const joinedCommand = command.join(" ");
@ -110,7 +110,7 @@ export class Ctx {
constructor(
readonly extCtx: vscode.ExtensionContext,
commandFactories: Record<string, CommandFactory>,
workspace: Workspace
workspace: Workspace,
) {
extCtx.subscriptions.push(this);
this.statusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);
@ -186,7 +186,7 @@ export class Ctx {
log.error("Bootstrap error", err);
throw new Error(message);
}
},
);
const newEnv = Object.assign({}, process.env, this.config.serverExtraEnv);
const run: lc.Executable = {
@ -216,7 +216,7 @@ export class Ctx {
return discoverWorkspace([file], discoverProjectCommand, {
cwd: path.dirname(file.uri.fsPath),
});
})
}),
);
this.addToDiscoveredWorkspaces(workspaces);
@ -230,7 +230,7 @@ export class Ctx {
if (key === "linkedProjects" && this.config.discoveredWorkspaces.length > 0) {
obj["linkedProjects"] = this.config.discoveredWorkspaces;
}
}
},
);
this._client = await createClient(
@ -239,17 +239,17 @@ export class Ctx {
initializationOptions,
serverOptions,
this.config,
this.unlinkedFiles
this.unlinkedFiles,
);
this.pushClientCleanup(
this._client.onNotification(ra.serverStatus, (params) =>
this.setServerStatus(params)
)
this.setServerStatus(params),
),
);
this.pushClientCleanup(
this._client.onNotification(ra.openServerLogs, () => {
this.outputChannel!.show();
})
}),
);
}
return this._client;
@ -395,7 +395,7 @@ export class Ctx {
} else {
callback = () =>
vscode.window.showErrorMessage(
`command ${fullName} failed: rust-analyzer server is not running`
`command ${fullName} failed: rust-analyzer server is not running`,
);
}
@ -423,7 +423,7 @@ export class Ctx {
}
statusBar.color = new vscode.ThemeColor("statusBarItem.warningForeground");
statusBar.backgroundColor = new vscode.ThemeColor(
"statusBarItem.warningBackground"
"statusBarItem.warningBackground",
);
statusBar.command = "rust-analyzer.openLogs";
icon = "$(warning) ";
@ -440,7 +440,7 @@ export class Ctx {
case "stopped":
statusBar.tooltip.appendText("Server is stopped");
statusBar.tooltip.appendMarkdown(
"\n\n[Start server](command:rust-analyzer.startServer)"
"\n\n[Start server](command:rust-analyzer.startServer)",
);
statusBar.color = undefined;
statusBar.backgroundColor = undefined;
@ -453,13 +453,13 @@ export class Ctx {
}
statusBar.tooltip.appendMarkdown("\n\n[Open logs](command:rust-analyzer.openLogs)");
statusBar.tooltip.appendMarkdown(
"\n\n[Reload Workspace](command:rust-analyzer.reloadWorkspace)"
"\n\n[Reload Workspace](command:rust-analyzer.reloadWorkspace)",
);
statusBar.tooltip.appendMarkdown(
"\n\n[Rebuild Proc Macros](command:rust-analyzer.rebuildProcMacros)"
"\n\n[Rebuild Proc Macros](command:rust-analyzer.rebuildProcMacros)",
);
statusBar.tooltip.appendMarkdown(
"\n\n[Restart server](command:rust-analyzer.restartServer)"
"\n\n[Restart server](command:rust-analyzer.restartServer)",
);
statusBar.tooltip.appendMarkdown("\n\n[Stop server](command:rust-analyzer.stopServer)");
if (!status.quiescent) icon = "$(sync~spin) ";

View File

@ -13,7 +13,7 @@ type DebugConfigProvider = (
config: ra.Runnable,
executable: string,
env: Record<string, string>,
sourceFileMap?: Record<string, string>
sourceFileMap?: Record<string, string>,
) => vscode.DebugConfiguration;
export async function makeDebugConfig(ctx: Ctx, runnable: ra.Runnable): Promise<void> {
@ -31,7 +31,7 @@ export async function makeDebugConfig(ctx: Ctx, runnable: ra.Runnable): Promise<
const answer = await vscode.window.showErrorMessage(
`Launch configuration '${debugConfig.name}' already exists!`,
"Cancel",
"Update"
"Update",
);
if (answer === "Cancel") return;
@ -68,7 +68,7 @@ export async function startDebugSession(ctx: Ctx, runnable: ra.Runnable): Promis
async function getDebugConfiguration(
ctx: Ctx,
runnable: ra.Runnable
runnable: ra.Runnable,
): Promise<vscode.DebugConfiguration | undefined> {
const editor = ctx.activeRustEditor;
if (!editor) return;
@ -92,7 +92,7 @@ async function getDebugConfiguration(
if (!debugEngine) {
await vscode.window.showErrorMessage(
`Install [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb)` +
` or [MS C++ tools](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools) extension for debugging.`
` or [MS C++ tools](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools) extension for debugging.`,
);
return;
}
@ -157,7 +157,7 @@ async function getDebugConfiguration(
async function getDebugExecutable(
runnable: ra.Runnable,
env: Record<string, string>
env: Record<string, string>,
): Promise<string> {
const cargo = new Cargo(runnable.args.workspaceRoot || ".", debugOutput, env);
const executable = await cargo.executableFromArgs(runnable.args.cargoArgs);
@ -170,7 +170,7 @@ function getLldbDebugConfig(
runnable: ra.Runnable,
executable: string,
env: Record<string, string>,
sourceFileMap?: Record<string, string>
sourceFileMap?: Record<string, string>,
): vscode.DebugConfiguration {
return {
type: "lldb",
@ -189,7 +189,7 @@ function getCppvsDebugConfig(
runnable: ra.Runnable,
executable: string,
env: Record<string, string>,
sourceFileMap?: Record<string, string>
sourceFileMap?: Record<string, string>,
): vscode.DebugConfiguration {
return {
type: os.platform() === "win32" ? "cppvsdbg" : "cppdbg",

View File

@ -43,7 +43,7 @@ export class RustDependenciesProvider
}
getParent?(
element: Dependency | DependencyFile
element: Dependency | DependencyFile,
): vscode.ProviderResult<Dependency | DependencyFile> {
if (element instanceof Dependency) return undefined;
return element.parent;
@ -60,7 +60,7 @@ export class RustDependenciesProvider
}
getChildren(
element?: Dependency | DependencyFile
element?: Dependency | DependencyFile,
): vscode.ProviderResult<Dependency[] | DependencyFile[]> {
return new Promise((resolve, _reject) => {
if (!vscode.workspace.workspaceFolders) {
@ -87,7 +87,7 @@ export class RustDependenciesProvider
private async getRootDependencies(): Promise<Dependency[]> {
const dependenciesResult: FetchDependencyListResult = await this.ctx.client.sendRequest(
ra.fetchDependencyList,
{}
{},
);
const crates = dependenciesResult.crates;
@ -107,7 +107,7 @@ export class RustDependenciesProvider
moduleName,
version,
vscode.Uri.parse(path).fsPath,
vscode.TreeItemCollapsibleState.Collapsed
vscode.TreeItemCollapsibleState.Collapsed,
);
}
}
@ -117,7 +117,7 @@ export class Dependency extends vscode.TreeItem {
public override readonly label: string,
private version: string,
readonly dependencyPath: string,
public override readonly collapsibleState: vscode.TreeItemCollapsibleState
public override readonly collapsibleState: vscode.TreeItemCollapsibleState,
) {
super(label, collapsibleState);
this.resourceUri = vscode.Uri.file(dependencyPath);
@ -136,7 +136,7 @@ export class DependencyFile extends vscode.TreeItem {
override readonly label: string,
readonly dependencyPath: string,
readonly parent: Dependency | DependencyFile,
public override readonly collapsibleState: vscode.TreeItemCollapsibleState
public override readonly collapsibleState: vscode.TreeItemCollapsibleState,
) {
super(vscode.Uri.file(dependencyPath), collapsibleState);
this.id = this.resourceUri!.fsPath.toLowerCase();

View File

@ -89,7 +89,7 @@ export class AnsiDecorationProvider implements vscode.Disposable {
}
private _getDecorations(
uri: vscode.Uri
uri: vscode.Uri,
): ProviderResult<[TextEditorDecorationType, Range[]][]> {
const stringContents = getRenderedDiagnostic(this.ctx, uri);
const lines = stringContents.split("\n");
@ -117,7 +117,7 @@ export class AnsiDecorationProvider implements vscode.Disposable {
lineNumber,
offset - totalEscapeLength,
lineNumber,
offset + content.length - totalEscapeLength
offset + content.length - totalEscapeLength,
);
offset += content.length;
@ -183,7 +183,7 @@ export class AnsiDecorationProvider implements vscode.Disposable {
private static _convertColor(
color?: string,
truecolor?: string
truecolor?: string,
): ThemeColor | string | undefined {
if (!color) {
return undefined;

View File

@ -27,17 +27,17 @@ export type CommandLinkGroup = {
// rust-analyzer extensions
export const analyzerStatus = new lc.RequestType<AnalyzerStatusParams, string, void>(
"rust-analyzer/analyzerStatus"
"rust-analyzer/analyzerStatus",
);
export const cancelFlycheck = new lc.NotificationType0("rust-analyzer/cancelFlycheck");
export const clearFlycheck = new lc.NotificationType0("rust-analyzer/clearFlycheck");
export const expandMacro = new lc.RequestType<ExpandMacroParams, ExpandedMacro | null, void>(
"rust-analyzer/expandMacro"
"rust-analyzer/expandMacro",
);
export const memoryUsage = new lc.RequestType0<string, void>("rust-analyzer/memoryUsage");
export const openServerLogs = new lc.NotificationType0("rust-analyzer/openServerLogs");
export const relatedTests = new lc.RequestType<lc.TextDocumentPositionParams, TestInfo[], void>(
"rust-analyzer/relatedTests"
"rust-analyzer/relatedTests",
);
export const reloadWorkspace = new lc.RequestType0<null, void>("rust-analyzer/reloadWorkspace");
export const rebuildProcMacros = new lc.RequestType0<null, void>("rust-analyzer/rebuildProcMacros");
@ -47,25 +47,25 @@ export const runFlycheck = new lc.NotificationType<{
}>("rust-analyzer/runFlycheck");
export const shuffleCrateGraph = new lc.RequestType0<null, void>("rust-analyzer/shuffleCrateGraph");
export const syntaxTree = new lc.RequestType<SyntaxTreeParams, string, void>(
"rust-analyzer/syntaxTree"
"rust-analyzer/syntaxTree",
);
export const viewCrateGraph = new lc.RequestType<ViewCrateGraphParams, string, void>(
"rust-analyzer/viewCrateGraph"
"rust-analyzer/viewCrateGraph",
);
export const viewFileText = new lc.RequestType<lc.TextDocumentIdentifier, string, void>(
"rust-analyzer/viewFileText"
"rust-analyzer/viewFileText",
);
export const viewHir = new lc.RequestType<lc.TextDocumentPositionParams, string, void>(
"rust-analyzer/viewHir"
"rust-analyzer/viewHir",
);
export const viewMir = new lc.RequestType<lc.TextDocumentPositionParams, string, void>(
"rust-analyzer/viewMir"
"rust-analyzer/viewMir",
);
export const interpretFunction = new lc.RequestType<lc.TextDocumentPositionParams, string, void>(
"rust-analyzer/interpretFunction"
"rust-analyzer/interpretFunction",
);
export const viewItemTree = new lc.RequestType<ViewItemTreeParams, string, void>(
"rust-analyzer/viewItemTree"
"rust-analyzer/viewItemTree",
);
export type AnalyzerStatusParams = { textDocument?: lc.TextDocumentIdentifier };
@ -121,22 +121,22 @@ export type ViewItemTreeParams = { textDocument: lc.TextDocumentIdentifier };
// experimental extensions
export const joinLines = new lc.RequestType<JoinLinesParams, lc.TextEdit[], void>(
"experimental/joinLines"
"experimental/joinLines",
);
export const matchingBrace = new lc.RequestType<MatchingBraceParams, lc.Position[], void>(
"experimental/matchingBrace"
"experimental/matchingBrace",
);
export const moveItem = new lc.RequestType<MoveItemParams, lc.TextEdit[], void>(
"experimental/moveItem"
"experimental/moveItem",
);
export const onEnter = new lc.RequestType<lc.TextDocumentPositionParams, lc.TextEdit[], void>(
"experimental/onEnter"
"experimental/onEnter",
);
export const openCargoToml = new lc.RequestType<OpenCargoTomlParams, lc.Location, void>(
"experimental/openCargoToml"
"experimental/openCargoToml",
);
export const openDocs = new lc.RequestType<lc.TextDocumentPositionParams, string | void, void>(
"experimental/externalDocs"
"experimental/externalDocs",
);
export const parentModule = new lc.RequestType<
lc.TextDocumentPositionParams,
@ -144,10 +144,10 @@ export const parentModule = new lc.RequestType<
void
>("experimental/parentModule");
export const runnables = new lc.RequestType<RunnablesParams, Runnable[], void>(
"experimental/runnables"
"experimental/runnables",
);
export const serverStatus = new lc.NotificationType<ServerStatusParams>(
"experimental/serverStatus"
"experimental/serverStatus",
);
export const ssr = new lc.RequestType<SsrParams, lc.WorkspaceEdit, void>("experimental/ssr");
export const viewRecursiveMemoryLayout = new lc.RequestType<

View File

@ -18,7 +18,7 @@ export async function deactivate() {
}
export async function activate(
context: vscode.ExtensionContext
context: vscode.ExtensionContext,
): Promise<RustAnalyzerExtensionApi> {
if (vscode.extensions.getExtension("rust-lang.rust")) {
vscode.window
@ -26,7 +26,7 @@ export async function activate(
`You have both the rust-analyzer (rust-lang.rust-analyzer) and Rust (rust-lang.rust) ` +
"plugins enabled. These are known to conflict and cause various functions of " +
"both plugins to not work correctly. You should disable one of them.",
"Got it"
"Got it",
)
.then(() => {}, console.error);
}
@ -36,7 +36,7 @@ export async function activate(
// so we do it ourselves.
const api = await activateServer(ctx).catch((err) => {
void vscode.window.showErrorMessage(
`Cannot activate rust-analyzer extension: ${err.message}`
`Cannot activate rust-analyzer extension: ${err.message}`,
);
throw err;
});
@ -53,8 +53,8 @@ async function activateServer(ctx: Ctx): Promise<RustAnalyzerExtensionApi> {
ctx.pushExtCleanup(
vscode.workspace.registerTextDocumentContentProvider(
diagnostics.URI_SCHEME,
diagnosticProvider
)
diagnosticProvider,
),
);
const decorationProvider = new diagnostics.AnsiDecorationProvider(ctx);
@ -71,7 +71,7 @@ async function activateServer(ctx: Ctx): Promise<RustAnalyzerExtensionApi> {
vscode.workspace.onDidChangeTextDocument(
async (event) => await decorateVisibleEditors(event.document),
null,
ctx.subscriptions
ctx.subscriptions,
);
vscode.workspace.onDidOpenTextDocument(decorateVisibleEditors, null, ctx.subscriptions);
vscode.window.onDidChangeActiveTextEditor(
@ -82,7 +82,7 @@ async function activateServer(ctx: Ctx): Promise<RustAnalyzerExtensionApi> {
}
},
null,
ctx.subscriptions
ctx.subscriptions,
);
vscode.window.onDidChangeVisibleTextEditors(
async (visibleEditors) => {
@ -92,13 +92,13 @@ async function activateServer(ctx: Ctx): Promise<RustAnalyzerExtensionApi> {
}
},
null,
ctx.subscriptions
ctx.subscriptions,
);
vscode.workspace.onDidChangeWorkspaceFolders(
async (_) => ctx.onWorkspaceFolderChanges(),
null,
ctx.subscriptions
ctx.subscriptions,
);
vscode.workspace.onDidChangeConfiguration(
async (_) => {
@ -107,7 +107,7 @@ async function activateServer(ctx: Ctx): Promise<RustAnalyzerExtensionApi> {
});
},
null,
ctx.subscriptions
ctx.subscriptions,
);
await ctx.start();

View File

@ -16,7 +16,7 @@ export async function selectRunnable(
ctx: CtxInit,
prevRunnable?: RunnableQuickPick,
debuggeeOnly = false,
showButtons: boolean = true
showButtons: boolean = true,
): Promise<RunnableQuickPick | undefined> {
const editor = ctx.activeRustEditor;
if (!editor) return;
@ -84,7 +84,7 @@ export async function selectRunnable(
}
}
}),
quickPick
quickPick,
);
quickPick.show();
});
@ -103,7 +103,7 @@ export class RunnableQuickPick implements vscode.QuickPickItem {
export function prepareEnv(
runnable: ra.Runnable,
runnableEnvCfg: RunnableEnvCfg
runnableEnvCfg: RunnableEnvCfg,
): Record<string, string> {
const env: Record<string, string> = { RUST_BACKTRACE: "short" };
@ -156,7 +156,7 @@ export async function createTask(runnable: ra.Runnable, config: Config): Promise
args,
config.problemMatcher,
config.cargoRunner,
true
true,
);
cargoTask.presentationOptions.clear = true;

View File

@ -17,7 +17,9 @@ export async function applySnippetWorkspaceEdit(edit: vscode.WorkspaceEdit) {
for (const indel of edits) {
assert(
!parseSnippet(indel.newText),
`bad ws edit: snippet received with multiple edits: ${JSON.stringify(edit)}`
`bad ws edit: snippet received with multiple edits: ${JSON.stringify(
edit,
)}`,
);
builder.replace(indel.range, indel.newText);
}
@ -32,7 +34,7 @@ async function editorFromUri(uri: vscode.Uri): Promise<vscode.TextEditor | undef
await vscode.window.showTextDocument(uri, {});
}
return vscode.window.visibleTextEditors.find(
(it) => it.document.uri.toString() === uri.toString()
(it) => it.document.uri.toString() === uri.toString(),
);
}
@ -56,8 +58,8 @@ export async function applySnippetTextEdits(editor: vscode.TextEditor, edits: vs
selections.push(
new vscode.Selection(
new vscode.Position(startLine, startColumn),
new vscode.Position(startLine, endColumn)
)
new vscode.Position(startLine, endColumn),
),
);
builder.replace(indel.range, newText);
} else {

View File

@ -48,7 +48,7 @@ class CargoTaskProvider implements vscode.TaskProvider {
`cargo ${def.command}`,
[def.command],
this.config.problemMatcher,
this.config.cargoRunner
this.config.cargoRunner,
);
vscodeTask.group = def.group;
tasks.push(vscodeTask);
@ -73,7 +73,7 @@ class CargoTaskProvider implements vscode.TaskProvider {
task.name,
args,
this.config.problemMatcher,
this.config.cargoRunner
this.config.cargoRunner,
);
}
@ -88,7 +88,7 @@ export async function buildCargoTask(
args: string[],
problemMatcher: string[],
customRunner?: string,
throwOnError: boolean = false
throwOnError: boolean = false,
): Promise<vscode.Task> {
let exec: vscode.ProcessExecution | vscode.ShellExecution | undefined = undefined;
@ -133,7 +133,7 @@ export async function buildCargoTask(
name,
TASK_SOURCE,
exec,
problemMatcher
problemMatcher,
);
}

View File

@ -23,7 +23,7 @@ export class Cargo {
constructor(
readonly rootFolder: string,
readonly output: vscode.OutputChannel,
readonly env: Record<string, string>
readonly env: Record<string, string>,
) {}
// Made public for testing purposes
@ -76,7 +76,7 @@ export class Cargo {
this.output.append(message.message.rendered);
}
},
(stderr) => this.output.append(stderr)
(stderr) => this.output.append(stderr),
);
} catch (err) {
this.output.show(true);
@ -102,7 +102,7 @@ export class Cargo {
private async runCargo(
cargoArgs: string[],
onStdoutJson: (obj: any) => void,
onStderrString: (data: string) => void
onStderrString: (data: string) => void,
): Promise<number> {
const path = await cargoPath();
return await new Promise((resolve, reject) => {
@ -172,7 +172,7 @@ export const getPathForExecutable = memoizeAsync(
if (await isFileAtUri(standardPath)) return standardPath.fsPath;
}
return executableName;
}
},
);
async function lookupInPath(exec: string): Promise<boolean> {

View File

@ -114,7 +114,7 @@ export function setContextValue(key: string, value: any): Thenable<void> {
* underlying async function.
*/
export function memoizeAsync<Ret, TThis, Param extends string>(
func: (this: TThis, arg: Param) => Promise<Ret>
func: (this: TThis, arg: Param) => Promise<Ret>,
) {
const cache = new Map<string, Ret>();

View File

@ -63,7 +63,7 @@ export async function run(): Promise<void> {
const context = new Context();
const testFiles = (await readdir(path.resolve(__dirname))).filter((name) =>
name.endsWith(".test.js")
name.endsWith(".test.js"),
);
for (const testFile of testFiles) {
try {