2691: Cleanup imports r=matklad a=matklad



Co-authored-by: Aleksey Kladov <aleksey.kladov@gmail.com>
This commit is contained in:
bors[bot] 2019-12-30 18:08:23 +00:00 committed by GitHub
commit 7c1634a9c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 241 additions and 281 deletions

@ -19,7 +19,7 @@
"vscode:prepublish": "rollup -c",
"package": "vsce package",
"watch": "tsc -watch -p ./",
"prettier": "prettier --write **/*.ts"
"prettier": "prettier --write '**/*.ts'"
},
"dependencies": {
"jsonc-parser": "^2.1.0",

@ -1,4 +1,5 @@
import * as vscode from 'vscode';
import { Ctx, Cmd } from '../ctx';
// Shows status of rust-analyzer (for debugging)
@ -23,10 +24,7 @@ export function analyzerStatus(ctx: Ctx): Cmd {
return async function handle() {
if (poller == null) {
poller = setInterval(
() => tdcp.eventEmitter.fire(tdcp.uri),
1000,
);
poller = setInterval(() => tdcp.eventEmitter.fire(tdcp.uri), 1000);
}
const document = await vscode.workspace.openTextDocument(tdcp.uri);
return vscode.window.showTextDocument(
@ -39,23 +37,20 @@ export function analyzerStatus(ctx: Ctx): Cmd {
class TextDocumentContentProvider
implements vscode.TextDocumentContentProvider {
ctx: Ctx;
uri = vscode.Uri.parse('rust-analyzer-status://status');
eventEmitter = new vscode.EventEmitter<vscode.Uri>();
ctx: Ctx
constructor(ctx: Ctx) {
this.ctx = ctx
this.ctx = ctx;
}
provideTextDocumentContent(
_uri: vscode.Uri,
): vscode.ProviderResult<string> {
const editor = vscode.window.activeTextEditor;
if (editor == null) {
return '';
}
if (editor == null) return '';
return this.ctx.client.sendRequest<string>(
'rust-analyzer/analyzerStatus',
null,

@ -1,23 +1,23 @@
import { Ctx, Cmd } from '../ctx'
import { Ctx, Cmd } from '../ctx';
import { analyzerStatus } from './analyzer_status';
import { matchingBrace } from './matching_brace';
import * as applySourceChange from './apply_source_change';
import { joinLines } from './join_lines';
import { onEnter } from './on_enter';
import { parentModule } from './parent_module';
import { syntaxTree } from './syntax_tree';
import * as expandMacro from './expand_macro';
import * as inlayHints from './inlay_hints';
import * as joinLines from './join_lines';
import * as onEnter from './on_enter';
import * as parentModule from './parent_module';
import * as runnables from './runnables';
import * as syntaxTree from './syntaxTree';
function collectGarbage(ctx: Ctx): Cmd {
return async () => { ctx.client.sendRequest<null>('rust-analyzer/collectGarbage', null) }
return async () => {
ctx.client.sendRequest<null>('rust-analyzer/collectGarbage', null);
};
}
export {
analyzerStatus,
applySourceChange,
expandMacro,
joinLines,
matchingBrace,
@ -26,5 +26,5 @@ export {
syntaxTree,
onEnter,
inlayHints,
collectGarbage
collectGarbage,
};

@ -1,29 +1,26 @@
import * as vscode from 'vscode';
import * as lc from 'vscode-languageclient';
import { Range, TextDocumentIdentifier } from 'vscode-languageclient';
import { Server } from '../server';
import {
handle as applySourceChange,
SourceChange,
} from './apply_source_change';
import { Ctx, Cmd } from '../ctx';
import { applySourceChange, SourceChange } from '../source_change';
export function joinLines(ctx: Ctx): Cmd {
return async () => {
const editor = ctx.activeRustEditor;
if (!editor) return;
const request: JoinLinesParams = {
range: ctx.client.code2ProtocolConverter.asRange(editor.selection),
textDocument: { uri: editor.document.uri.toString() },
};
const change = await ctx.client.sendRequest<SourceChange>(
'rust-analyzer/joinLines',
request,
);
await applySourceChange(ctx, change);
};
}
interface JoinLinesParams {
textDocument: TextDocumentIdentifier;
range: Range;
}
export async function handle() {
const editor = vscode.window.activeTextEditor;
if (editor == null || editor.document.languageId !== 'rust') {
return;
}
const request: JoinLinesParams = {
range: Server.client.code2ProtocolConverter.asRange(editor.selection),
textDocument: { uri: editor.document.uri.toString() },
};
const change = await Server.client.sendRequest<SourceChange>(
'rust-analyzer/joinLines',
request,
);
await applySourceChange(change);
textDocument: lc.TextDocumentIdentifier;
range: lc.Range;
}

@ -1,5 +1,6 @@
import * as vscode from 'vscode';
import { Position, TextDocumentIdentifier } from 'vscode-languageclient';
import * as lc from 'vscode-languageclient';
import { Ctx, Cmd } from '../ctx';
export function matchingBrace(ctx: Ctx): Cmd {
@ -10,9 +11,11 @@ export function matchingBrace(ctx: Ctx): Cmd {
}
const request: FindMatchingBraceParams = {
textDocument: { uri: editor.document.uri.toString() },
offsets: editor.selections.map(s => ctx.client.code2ProtocolConverter.asPosition(s.active)),
offsets: editor.selections.map(s =>
ctx.client.code2ProtocolConverter.asPosition(s.active),
),
};
const response = await ctx.client.sendRequest<Position[]>(
const response = await ctx.client.sendRequest<lc.Position[]>(
'rust-analyzer/findMatchingBrace',
request,
);
@ -24,10 +27,10 @@ export function matchingBrace(ctx: Ctx): Cmd {
return new vscode.Selection(anchor, active);
});
editor.revealRange(editor.selection);
}
};
}
interface FindMatchingBraceParams {
textDocument: TextDocumentIdentifier;
offsets: Position[];
textDocument: lc.TextDocumentIdentifier;
offsets: lc.Position[];
}

@ -1,33 +1,26 @@
import * as vscode from 'vscode';
import * as lc from 'vscode-languageclient';
import { Server } from '../server';
import {
handle as applySourceChange,
SourceChange,
} from './apply_source_change';
export async function handle(event: { text: string }): Promise<boolean> {
const editor = vscode.window.activeTextEditor;
if (
editor == null ||
editor.document.languageId !== 'rust' ||
event.text !== '\n'
) {
return false;
}
const request: lc.TextDocumentPositionParams = {
textDocument: { uri: editor.document.uri.toString() },
position: Server.client.code2ProtocolConverter.asPosition(
editor.selection.active,
),
import { applySourceChange, SourceChange } from '../source_change';
import { Cmd, Ctx } from '../ctx';
export function onEnter(ctx: Ctx): Cmd {
return async (event: { text: string }) => {
const editor = ctx.activeRustEditor;
if (!editor || event.text !== '\n') return false;
const request: lc.TextDocumentPositionParams = {
textDocument: { uri: editor.document.uri.toString() },
position: ctx.client.code2ProtocolConverter.asPosition(
editor.selection.active,
),
};
const change = await ctx.client.sendRequest<undefined | SourceChange>(
'rust-analyzer/onEnter',
request,
);
if (!change) return false;
await applySourceChange(ctx, change);
return true;
};
const change = await Server.client.sendRequest<undefined | SourceChange>(
'rust-analyzer/onEnter',
request,
);
if (!change) {
return false;
}
await applySourceChange(change);
return true;
}

@ -1,32 +1,32 @@
import * as vscode from 'vscode';
import * as lc from 'vscode-languageclient';
import { Server } from '../server';
export async function handle() {
const editor = vscode.window.activeTextEditor;
if (editor == null || editor.document.languageId !== 'rust') {
return;
}
const request: lc.TextDocumentPositionParams = {
textDocument: { uri: editor.document.uri.toString() },
position: Server.client.code2ProtocolConverter.asPosition(
editor.selection.active,
),
import { Ctx, Cmd } from '../ctx';
export function parentModule(ctx: Ctx): Cmd {
return async () => {
const editor = ctx.activeRustEditor;
if (!editor) return;
const request: lc.TextDocumentPositionParams = {
textDocument: { uri: editor.document.uri.toString() },
position: ctx.client.code2ProtocolConverter.asPosition(
editor.selection.active,
),
};
const response = await ctx.client.sendRequest<lc.Location[]>(
'rust-analyzer/parentModule',
request,
);
const loc = response[0];
if (loc == null) return;
const uri = ctx.client.protocol2CodeConverter.asUri(loc.uri);
const range = ctx.client.protocol2CodeConverter.asRange(loc.range);
const doc = await vscode.workspace.openTextDocument(uri);
const e = await vscode.window.showTextDocument(doc);
e.selection = new vscode.Selection(range.start, range.start);
e.revealRange(range, vscode.TextEditorRevealType.InCenter);
};
const response = await Server.client.sendRequest<lc.Location[]>(
'rust-analyzer/parentModule',
request,
);
const loc = response[0];
if (loc == null) {
return;
}
const uri = Server.client.protocol2CodeConverter.asUri(loc.uri);
const range = Server.client.protocol2CodeConverter.asRange(loc.range);
const doc = await vscode.workspace.openTextDocument(uri);
const e = await vscode.window.showTextDocument(doc);
e.selection = new vscode.Selection(range.start, range.start);
e.revealRange(range, vscode.TextEditorRevealType.InCenter);
}

@ -1,76 +0,0 @@
import * as vscode from 'vscode';
import { Range, TextDocumentIdentifier } from 'vscode-languageclient';
import { Server } from '../server';
export const syntaxTreeUri = vscode.Uri.parse('rust-analyzer://syntaxtree');
export class SyntaxTreeContentProvider
implements vscode.TextDocumentContentProvider {
public eventEmitter = new vscode.EventEmitter<vscode.Uri>();
public syntaxTree: string = 'Not available';
public provideTextDocumentContent(
uri: vscode.Uri,
): vscode.ProviderResult<string> {
const editor = vscode.window.activeTextEditor;
if (editor == null) {
return '';
}
let range: Range | undefined;
// When the range based query is enabled we take the range of the selection
if (uri.query === 'range=true') {
range = editor.selection.isEmpty
? undefined
: Server.client.code2ProtocolConverter.asRange(
editor.selection,
);
}
const request: SyntaxTreeParams = {
textDocument: { uri: editor.document.uri.toString() },
range,
};
return Server.client.sendRequest<SyntaxTreeResult>(
'rust-analyzer/syntaxTree',
request,
);
}
get onDidChange(): vscode.Event<vscode.Uri> {
return this.eventEmitter.event;
}
}
interface SyntaxTreeParams {
textDocument: TextDocumentIdentifier;
range?: Range;
}
type SyntaxTreeResult = string;
// Opens the virtual file that will show the syntax tree
//
// The contents of the file come from the `TextDocumentContentProvider`
export function createHandle(provider: SyntaxTreeContentProvider) {
return async () => {
const editor = vscode.window.activeTextEditor;
const rangeEnabled = !!(editor && !editor.selection.isEmpty);
const uri = rangeEnabled
? vscode.Uri.parse(`${syntaxTreeUri.toString()}?range=true`)
: syntaxTreeUri;
const document = await vscode.workspace.openTextDocument(uri);
provider.eventEmitter.fire(uri);
return vscode.window.showTextDocument(
document,
vscode.ViewColumn.Two,
true,
);
};
}

@ -0,0 +1,106 @@
import * as vscode from 'vscode';
import * as lc from 'vscode-languageclient';
import { Ctx, Cmd } from '../ctx';
// Opens the virtual file that will show the syntax tree
//
// The contents of the file come from the `TextDocumentContentProvider`
export function syntaxTree(ctx: Ctx): Cmd {
const stcp = new SyntaxTreeContentProvider(ctx);
ctx.pushCleanup(
vscode.workspace.registerTextDocumentContentProvider(
'rust-analyzer',
stcp,
),
);
vscode.workspace.onDidChangeTextDocument(
(event: vscode.TextDocumentChangeEvent) => {
const doc = event.document;
if (doc.languageId !== 'rust') return;
afterLs(() => stcp.eventEmitter.fire(stcp.uri));
},
ctx.subscriptions,
);
vscode.window.onDidChangeActiveTextEditor(
(editor: vscode.TextEditor | undefined) => {
if (!editor || editor.document.languageId !== 'rust') return;
stcp.eventEmitter.fire(stcp.uri);
},
ctx.subscriptions,
);
return async () => {
const editor = vscode.window.activeTextEditor;
const rangeEnabled = !!(editor && !editor.selection.isEmpty);
const uri = rangeEnabled
? vscode.Uri.parse(`${stcp.uri.toString()}?range=true`)
: stcp.uri;
const document = await vscode.workspace.openTextDocument(uri);
stcp.eventEmitter.fire(uri);
return vscode.window.showTextDocument(
document,
vscode.ViewColumn.Two,
true,
);
};
}
// We need to order this after LS updates, but there's no API for that.
// Hence, good old setTimeout.
function afterLs(f: () => any) {
setTimeout(f, 10);
}
interface SyntaxTreeParams {
textDocument: lc.TextDocumentIdentifier;
range?: lc.Range;
}
export class SyntaxTreeContentProvider
implements vscode.TextDocumentContentProvider {
ctx: Ctx;
uri = vscode.Uri.parse('rust-analyzer://syntaxtree');
eventEmitter = new vscode.EventEmitter<vscode.Uri>();
syntaxTree: string = 'Not available';
constructor(ctx: Ctx) {
this.ctx = ctx;
}
provideTextDocumentContent(uri: vscode.Uri): vscode.ProviderResult<string> {
const editor = vscode.window.activeTextEditor;
if (editor == null) return '';
let range: lc.Range | undefined;
// When the range based query is enabled we take the range of the selection
if (uri.query === 'range=true') {
range = editor.selection.isEmpty
? undefined
: this.ctx.client.code2ProtocolConverter.asRange(
editor.selection,
);
}
const request: SyntaxTreeParams = {
textDocument: { uri: editor.document.uri.toString() },
range,
};
return this.ctx.client.sendRequest<string>(
'rust-analyzer/syntaxTree',
request,
);
}
get onDidChange(): vscode.Event<vscode.Uri> {
return this.eventEmitter.event;
}
}

@ -27,6 +27,32 @@ export class Ctx {
this.pushCleanup(d);
}
overrideCommand(name: string, factory: (ctx: Ctx) => Cmd) {
const defaultCmd = `default:${name}`;
const override = factory(this);
const original = (...args: any[]) =>
vscode.commands.executeCommand(defaultCmd, ...args);
try {
const d = vscode.commands.registerCommand(
name,
async (...args: any[]) => {
if (!(await override(...args))) {
return await original(...args);
}
},
);
this.pushCleanup(d);
} catch (_) {
vscode.window.showWarningMessage(
'Enhanced typing feature is disabled because of incompatibility with VIM extension, consider turning off rust-analyzer.enableEnhancedTyping: https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/user/README.md#settings',
);
}
}
get subscriptions(): { dispose(): any }[] {
return this.extCtx.subscriptions;
}
pushCleanup(d: { dispose(): any }) {
this.extCtx.subscriptions.push(d);
}

@ -1,21 +1,14 @@
import { TextEditor } from 'vscode';
import { TextDocumentIdentifier } from 'vscode-languageclient';
import {
SyntaxTreeContentProvider,
syntaxTreeUri,
} from '../commands/syntaxTree';
import { Decoration } from '../highlighting';
import { Server } from '../server';
export function makeHandler(syntaxTreeProvider: SyntaxTreeContentProvider) {
export function makeHandler() {
return async function handle(editor: TextEditor | undefined) {
if (!editor || editor.document.languageId !== 'rust') {
return;
}
syntaxTreeProvider.eventEmitter.fire(syntaxTreeUri);
if (!Server.config.highlightingOn) {
return;
}

@ -1,24 +0,0 @@
import * as vscode from 'vscode';
import {
SyntaxTreeContentProvider,
syntaxTreeUri,
} from '../commands/syntaxTree';
export function createHandler(syntaxTreeProvider: SyntaxTreeContentProvider) {
return (event: vscode.TextDocumentChangeEvent) => {
const doc = event.document;
if (doc.languageId !== 'rust') {
return;
}
afterLs(() => {
syntaxTreeProvider.eventEmitter.fire(syntaxTreeUri);
});
};
}
// We need to order this after LS updates, but there's no API for that.
// Hence, good old setTimeout.
function afterLs(f: () => any) {
setTimeout(f, 10);
}

@ -1,4 +1,3 @@
import * as changeActiveTextEditor from './change_active_text_editor';
import * as changeTextDocument from './change_text_document';
export { changeActiveTextEditor, changeTextDocument };
export { changeActiveTextEditor };

@ -4,7 +4,6 @@ import * as lc from 'vscode-languageclient';
import * as commands from './commands';
import { ExpandMacroContentProvider } from './commands/expand_macro';
import { HintsUpdater } from './commands/inlay_hints';
import { SyntaxTreeContentProvider } from './commands/syntaxTree';
import { StatusDisplay } from './commands/watch_status';
import * as events from './events';
import * as notifications from './notifications';
@ -18,6 +17,9 @@ export async function activate(context: vscode.ExtensionContext) {
ctx.registerCommand('analyzerStatus', commands.analyzerStatus);
ctx.registerCommand('collectGarbage', commands.collectGarbage);
ctx.registerCommand('matchingBrace', commands.matchingBrace);
ctx.registerCommand('joinLines', commands.joinLines);
ctx.registerCommand('parentModule', commands.parentModule);
ctx.registerCommand('syntaxTree', commands.syntaxTree);
function disposeOnDeactivation(disposable: vscode.Disposable) {
context.subscriptions.push(disposable);
@ -26,45 +28,11 @@ export async function activate(context: vscode.ExtensionContext) {
function registerCommand(name: string, f: any) {
disposeOnDeactivation(vscode.commands.registerCommand(name, f));
}
function overrideCommand(
name: string,
f: (...args: any[]) => Promise<boolean>,
) {
const defaultCmd = `default:${name}`;
const original = (...args: any[]) =>
vscode.commands.executeCommand(defaultCmd, ...args);
try {
registerCommand(name, async (...args: any[]) => {
const editor = vscode.window.activeTextEditor;
if (
!editor ||
!editor.document ||
editor.document.languageId !== 'rust'
) {
return await original(...args);
}
if (!(await f(...args))) {
return await original(...args);
}
});
} catch (_) {
vscode.window.showWarningMessage(
'Enhanced typing feature is disabled because of incompatibility with VIM extension, consider turning off rust-analyzer.enableEnhancedTyping: https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/user/README.md#settings',
);
}
}
// Commands are requests from vscode to the language server
registerCommand('rust-analyzer.joinLines', commands.joinLines.handle);
registerCommand('rust-analyzer.parentModule', commands.parentModule.handle);
registerCommand('rust-analyzer.run', commands.runnables.handle);
// Unlike the above this does not send requests to the language server
registerCommand('rust-analyzer.runSingle', commands.runnables.handleSingle);
registerCommand(
'rust-analyzer.applySourceChange',
commands.applySourceChange.handle,
);
registerCommand(
'rust-analyzer.showReferences',
(uri: string, position: lc.Position, locations: lc.Location[]) => {
@ -78,7 +46,7 @@ export async function activate(context: vscode.ExtensionContext) {
);
if (Server.config.enableEnhancedTyping) {
overrideCommand('type', commands.onEnter.handle);
ctx.overrideCommand('type', commands.onEnter);
}
const watchStatus = new StatusDisplay(
@ -87,10 +55,7 @@ export async function activate(context: vscode.ExtensionContext) {
disposeOnDeactivation(watchStatus);
// Notifications are events triggered by the language server
const allNotifications: Iterable<[
string,
lc.GenericNotificationHandler,
]> = [
const allNotifications: [string, lc.GenericNotificationHandler][] = [
[
'rust-analyzer/publishDecorations',
notifications.publishDecorations.handle,
@ -100,20 +65,13 @@ export async function activate(context: vscode.ExtensionContext) {
params => watchStatus.handleProgressNotification(params),
],
];
const syntaxTreeContentProvider = new SyntaxTreeContentProvider();
const expandMacroContentProvider = new ExpandMacroContentProvider();
// The events below are plain old javascript events, triggered and handled by vscode
vscode.window.onDidChangeActiveTextEditor(
events.changeActiveTextEditor.makeHandler(syntaxTreeContentProvider),
events.changeActiveTextEditor.makeHandler(),
);
disposeOnDeactivation(
vscode.workspace.registerTextDocumentContentProvider(
'rust-analyzer',
syntaxTreeContentProvider,
),
);
disposeOnDeactivation(
vscode.workspace.registerTextDocumentContentProvider(
'rust-analyzer',
@ -121,21 +79,11 @@ export async function activate(context: vscode.ExtensionContext) {
),
);
registerCommand(
'rust-analyzer.syntaxTree',
commands.syntaxTree.createHandle(syntaxTreeContentProvider),
);
registerCommand(
'rust-analyzer.expandMacro',
commands.expandMacro.createHandle(expandMacroContentProvider),
);
vscode.workspace.onDidChangeTextDocument(
events.changeTextDocument.createHandler(syntaxTreeContentProvider),
null,
context.subscriptions,
);
const startServer = () => Server.start(allNotifications);
const reloadCommand = () => reloadServer(startServer);

@ -1,7 +1,7 @@
import * as vscode from 'vscode';
import * as lc from 'vscode-languageclient';
import { Server } from '../server';
import { Ctx } from './ctx';
export interface SourceChange {
label: string;
@ -9,8 +9,8 @@ export interface SourceChange {
cursorPosition?: lc.TextDocumentPositionParams;
}
export async function handle(change: SourceChange) {
const wsEdit = Server.client.protocol2CodeConverter.asWorkspaceEdit(
export async function applySourceChange(ctx: Ctx, change: SourceChange) {
const wsEdit = ctx.client.protocol2CodeConverter.asWorkspaceEdit(
change.workspaceEdit,
);
let created;
@ -32,10 +32,10 @@ export async function handle(change: SourceChange) {
const doc = await vscode.workspace.openTextDocument(toOpenUri);
await vscode.window.showTextDocument(doc);
} else if (toReveal) {
const uri = Server.client.protocol2CodeConverter.asUri(
const uri = ctx.client.protocol2CodeConverter.asUri(
toReveal.textDocument.uri,
);
const position = Server.client.protocol2CodeConverter.asPosition(
const position = ctx.client.protocol2CodeConverter.asPosition(
toReveal.position,
);
const editor = vscode.window.activeTextEditor;