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

View File

@ -8,13 +8,13 @@ import { exec } from "child_process";
export async function bootstrap( export async function bootstrap(
context: vscode.ExtensionContext, context: vscode.ExtensionContext,
config: Config, config: Config,
state: PersistentState state: PersistentState,
): Promise<string> { ): Promise<string> {
const path = await getServer(context, config, state); const path = await getServer(context, config, state);
if (!path) { if (!path) {
throw new Error( throw new Error(
"Rust Analyzer Language Server is not available. " + "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( async function getServer(
context: vscode.ExtensionContext, context: vscode.ExtensionContext,
config: Config, config: Config,
state: PersistentState state: PersistentState,
): Promise<string | undefined> { ): Promise<string | undefined> {
const explicitPath = process.env["__RA_LSP_SERVER_DEBUG"] ?? config.serverPath; const explicitPath = process.env["__RA_LSP_SERVER_DEBUG"] ?? config.serverPath;
if (explicitPath) { if (explicitPath) {
@ -49,7 +49,7 @@ async function getServer(
const bundled = vscode.Uri.joinPath(context.extensionUri, "server", `rust-analyzer${ext}`); const bundled = vscode.Uri.joinPath(context.extensionUri, "server", `rust-analyzer${ext}`);
const bundledExists = await vscode.workspace.fs.stat(bundled).then( const bundledExists = await vscode.workspace.fs.stat(bundled).then(
() => true, () => true,
() => false () => false,
); );
if (bundledExists) { if (bundledExists) {
let server = bundled; let server = bundled;
@ -58,7 +58,7 @@ async function getServer(
const dest = vscode.Uri.joinPath(config.globalStorageUri, `rust-analyzer${ext}`); const dest = vscode.Uri.joinPath(config.globalStorageUri, `rust-analyzer${ext}`);
let exists = await vscode.workspace.fs.stat(dest).then( let exists = await vscode.workspace.fs.stat(dest).then(
() => true, () => true,
() => false () => false,
); );
if (exists && config.package.version !== state.serverVersion) { if (exists && config.package.version !== state.serverVersion) {
await vscode.workspace.fs.delete(dest); 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. " + "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 " + "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 " + "about that [here](https://github.com/rust-lang/rust-analyzer/issues) and we " +
"will consider it." "will consider it.",
); );
return undefined; return undefined;
} }
@ -131,7 +131,7 @@ async function patchelf(dest: vscode.Uri): Promise<void> {
} else { } else {
resolve(stdout); resolve(stdout);
} }
} },
); );
handle.stdin?.write(expression); handle.stdin?.write(expression);
handle.stdin?.end(); handle.stdin?.end();
@ -139,6 +139,6 @@ async function patchelf(dest: vscode.Uri): Promise<void> {
} finally { } finally {
await vscode.workspace.fs.delete(origFile); 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 // 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 // clicked, but assuming most links in hover sheets won't be clicked anyway
// this code won't change the overall memory use much. // this code won't change the overall memory use much.
setInterval(function cleanupOlderCommandLinks() { setInterval(
// keys are returned in insertion order, we'll keep a few function cleanupOlderCommandLinks() {
// of recent keys available, and clean the rest // keys are returned in insertion order, we'll keep a few
const keys = [...LINKED_COMMANDS.keys()]; // of recent keys available, and clean the rest
const keysToRemove = keys.slice(0, keys.length - 10); const keys = [...LINKED_COMMANDS.keys()];
for (const key of keysToRemove) { const keysToRemove = keys.slice(0, keys.length - 10);
LINKED_COMMANDS.delete(key); for (const key of keysToRemove) {
} LINKED_COMMANDS.delete(key);
}, 10 * 60 * 1000); }
},
10 * 60 * 1000,
);
function renderCommand(cmd: ra.CommandLink): string { function renderCommand(cmd: ra.CommandLink): string {
const commandId = randomUUID(); const commandId = randomUUID();
LINKED_COMMANDS.set(commandId, cmd); LINKED_COMMANDS.set(commandId, cmd);
return `[${cmd.title}](command:rust-analyzer.linkToCommand?${encodeURIComponent( return `[${cmd.title}](command:rust-analyzer.linkToCommand?${encodeURIComponent(
JSON.stringify([commandId]) JSON.stringify([commandId]),
)} '${cmd.tooltip}')`; )} '${cmd.tooltip}')`;
} }
@ -57,7 +60,7 @@ function renderHoverActions(actions: ra.CommandLinkGroup[]): vscode.MarkdownStri
.map( .map(
(group) => (group) =>
(group.title ? group.title + " " : "") + (group.title ? group.title + " " : "") +
group.commands.map(renderCommand).join(" | ") group.commands.map(renderCommand).join(" | "),
) )
.join("___"); .join("___");
@ -72,7 +75,7 @@ export async function createClient(
initializationOptions: vscode.WorkspaceConfiguration, initializationOptions: vscode.WorkspaceConfiguration,
serverOptions: lc.ServerOptions, serverOptions: lc.ServerOptions,
config: Config, config: Config,
unlinkedFiles: vscode.Uri[] unlinkedFiles: vscode.Uri[],
): Promise<lc.LanguageClient> { ): Promise<lc.LanguageClient> {
const clientOptions: lc.LanguageClientOptions = { const clientOptions: lc.LanguageClientOptions = {
documentSelector: [{ scheme: "file", language: "rust" }], documentSelector: [{ scheme: "file", language: "rust" }],
@ -93,7 +96,7 @@ export async function createClient(
async configuration( async configuration(
params: lc.ConfigurationParams, params: lc.ConfigurationParams,
token: vscode.CancellationToken, token: vscode.CancellationToken,
next: lc.ConfigurationRequest.HandlerSignature next: lc.ConfigurationRequest.HandlerSignature,
) { ) {
const resp = await next(params, token); const resp = await next(params, token);
if (resp && Array.isArray(resp)) { if (resp && Array.isArray(resp)) {
@ -117,7 +120,7 @@ export async function createClient(
async handleDiagnostics( async handleDiagnostics(
uri: vscode.Uri, uri: vscode.Uri,
diagnosticList: vscode.Diagnostic[], diagnosticList: vscode.Diagnostic[],
next: lc.HandleDiagnosticsSignature next: lc.HandleDiagnosticsSignature,
) { ) {
const preview = config.previewRustcOutput; const preview = config.previewRustcOutput;
const errorCode = config.useRustcErrorCode; const errorCode = config.useRustcErrorCode;
@ -137,20 +140,20 @@ export async function createClient(
const folder = vscode.workspace.getWorkspaceFolder(uri)?.uri.fsPath; const folder = vscode.workspace.getWorkspaceFolder(uri)?.uri.fsPath;
if (folder) { if (folder) {
const parentBackslash = uri.fsPath.lastIndexOf( const parentBackslash = uri.fsPath.lastIndexOf(
pathSeparator + "src" pathSeparator + "src",
); );
const parent = uri.fsPath.substring(0, parentBackslash); const parent = uri.fsPath.substring(0, parentBackslash);
if (parent.startsWith(folder)) { if (parent.startsWith(folder)) {
const path = vscode.Uri.file( const path = vscode.Uri.file(
parent + pathSeparator + "Cargo.toml" parent + pathSeparator + "Cargo.toml",
); );
void vscode.workspace.fs.stat(path).then(async () => { void vscode.workspace.fs.stat(path).then(async () => {
const choice = await vscode.window.showInformationMessage( 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?`, `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", "Yes",
"No", "No",
"Don't show this again" "Don't show this again",
); );
switch (choice) { switch (choice) {
case undefined: case undefined:
@ -168,14 +171,14 @@ export async function createClient(
config config
.get<any[]>("linkedProjects") .get<any[]>("linkedProjects")
?.concat(pathToInsert), ?.concat(pathToInsert),
false false,
); );
break; break;
case "Don't show this again": case "Don't show this again":
await config.update( await config.update(
"showUnlinkedFileNotification", "showUnlinkedFileNotification",
false, false,
false false,
); );
break; break;
} }
@ -222,7 +225,7 @@ export async function createClient(
document: vscode.TextDocument, document: vscode.TextDocument,
position: vscode.Position, position: vscode.Position,
token: vscode.CancellationToken, token: vscode.CancellationToken,
_next: lc.ProvideHoverSignature _next: lc.ProvideHoverSignature,
) { ) {
const editor = vscode.window.activeTextEditor; const editor = vscode.window.activeTextEditor;
const positionOrRange = editor?.selection?.contains(position) const positionOrRange = editor?.selection?.contains(position)
@ -236,7 +239,7 @@ export async function createClient(
client.code2ProtocolConverter.asTextDocumentIdentifier(document), client.code2ProtocolConverter.asTextDocumentIdentifier(document),
position: positionOrRange, position: positionOrRange,
}, },
token token,
) )
.then( .then(
(result) => { (result) => {
@ -250,7 +253,7 @@ export async function createClient(
(error) => { (error) => {
client.handleFailedRequest(lc.HoverRequest.type, token, error, null); client.handleFailedRequest(lc.HoverRequest.type, token, error, null);
return Promise.resolve(null); return Promise.resolve(null);
} },
); );
}, },
// Using custom handling of CodeActions to support action groups and snippet edits. // Using custom handling of CodeActions to support action groups and snippet edits.
@ -260,14 +263,14 @@ export async function createClient(
range: vscode.Range, range: vscode.Range,
context: vscode.CodeActionContext, context: vscode.CodeActionContext,
token: vscode.CancellationToken, token: vscode.CancellationToken,
_next: lc.ProvideCodeActionsSignature _next: lc.ProvideCodeActionsSignature,
) { ) {
const params: lc.CodeActionParams = { const params: lc.CodeActionParams = {
textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document), textDocument: client.code2ProtocolConverter.asTextDocumentIdentifier(document),
range: client.code2ProtocolConverter.asRange(range), range: client.code2ProtocolConverter.asRange(range),
context: await client.code2ProtocolConverter.asCodeActionContext( context: await client.code2ProtocolConverter.asCodeActionContext(
context, context,
token token,
), ),
}; };
return client.sendRequest(lc.CodeActionRequest.type, params, token).then( return client.sendRequest(lc.CodeActionRequest.type, params, token).then(
@ -283,21 +286,21 @@ export async function createClient(
if (lc.CodeAction.is(item)) { if (lc.CodeAction.is(item)) {
assert( assert(
!item.command, !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( const action = await client.protocol2CodeConverter.asCodeAction(
item, item,
token token,
); );
result.push(action); result.push(action);
continue; continue;
} }
assert( assert(
isCodeActionWithoutEditsAndCommands(item), isCodeActionWithoutEditsAndCommands(item),
"We don't expect edits or commands here" "We don't expect edits or commands here",
); );
const kind = client.protocol2CodeConverter.asCodeActionKind( const kind = client.protocol2CodeConverter.asCodeActionKind(
(item as any).kind (item as any).kind,
); );
const action = new vscode.CodeAction(item.title, kind); const action = new vscode.CodeAction(item.title, kind);
const group = (item as any).group; const group = (item as any).group;
@ -351,7 +354,7 @@ export async function createClient(
} }
return result; return result;
}, },
(_error) => undefined (_error) => undefined,
); );
}, },
}, },
@ -364,7 +367,7 @@ export async function createClient(
"rust-analyzer", "rust-analyzer",
"Rust Analyzer Language Server", "Rust Analyzer Language Server",
serverOptions, serverOptions,
clientOptions clientOptions,
); );
// To turn on all proposed features use: client.registerProposedFeatures(); // To turn on all proposed features use: client.registerProposedFeatures();
@ -400,7 +403,7 @@ class ExperimentalFeatures implements lc.StaticFeature {
} }
initialize( initialize(
_capabilities: lc.ServerCapabilities, _capabilities: lc.ServerCapabilities,
_documentSelector: lc.DocumentSelector | undefined _documentSelector: lc.DocumentSelector | undefined,
): void {} ): void {}
dispose(): void {} dispose(): void {}
} }
@ -419,7 +422,7 @@ class OverrideFeatures implements lc.StaticFeature {
} }
initialize( initialize(
_capabilities: lc.ServerCapabilities, _capabilities: lc.ServerCapabilities,
_documentSelector: lc.DocumentSelector | undefined _documentSelector: lc.DocumentSelector | undefined,
): void {} ): void {}
dispose(): void {} dispose(): void {}
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -17,7 +17,9 @@ export async function applySnippetWorkspaceEdit(edit: vscode.WorkspaceEdit) {
for (const indel of edits) { for (const indel of edits) {
assert( assert(
!parseSnippet(indel.newText), !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); 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, {}); await vscode.window.showTextDocument(uri, {});
} }
return vscode.window.visibleTextEditors.find( 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( selections.push(
new vscode.Selection( new vscode.Selection(
new vscode.Position(startLine, startColumn), new vscode.Position(startLine, startColumn),
new vscode.Position(startLine, endColumn) new vscode.Position(startLine, endColumn),
) ),
); );
builder.replace(indel.range, newText); builder.replace(indel.range, newText);
} else { } else {

View File

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

View File

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

View File

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