diff options
author | Mikhail Rakhmanov <[email protected]> | 2020-06-03 19:10:54 +0100 |
---|---|---|
committer | Mikhail Rakhmanov <[email protected]> | 2020-06-03 19:10:54 +0100 |
commit | eefa10bc6bff3624ddd0bbb6bc89d8beb4bed186 (patch) | |
tree | 15c38c2993c52f4065d338090ca9185cc1fcd3da /editors/code/src | |
parent | a9d567584857b1be4ca8eaa5ef2c7d85f7b2845e (diff) | |
parent | 794f6da821c5d6e2490b996baffe162e4753262d (diff) |
Merge branch 'master' into assists_extract_enum
Diffstat (limited to 'editors/code/src')
22 files changed, 777 insertions, 792 deletions
diff --git a/editors/code/src/commands/syntax_tree.ts b/editors/code/src/ast_inspector.ts index a5446c327..4fdd167bd 100644 --- a/editors/code/src/commands/syntax_tree.ts +++ b/editors/code/src/ast_inspector.ts | |||
@@ -1,93 +1,15 @@ | |||
1 | import * as vscode from 'vscode'; | 1 | import * as vscode from 'vscode'; |
2 | import * as ra from '../rust-analyzer-api'; | ||
3 | |||
4 | import { Ctx, Cmd, Disposable } from '../ctx'; | ||
5 | import { isRustDocument, RustEditor, isRustEditor, sleep } from '../util'; | ||
6 | |||
7 | const AST_FILE_SCHEME = "rust-analyzer"; | ||
8 | |||
9 | // Opens the virtual file that will show the syntax tree | ||
10 | // | ||
11 | // The contents of the file come from the `TextDocumentContentProvider` | ||
12 | export function syntaxTree(ctx: Ctx): Cmd { | ||
13 | const tdcp = new TextDocumentContentProvider(ctx); | ||
14 | |||
15 | void new AstInspector(ctx); | ||
16 | |||
17 | ctx.pushCleanup(vscode.workspace.registerTextDocumentContentProvider(AST_FILE_SCHEME, tdcp)); | ||
18 | ctx.pushCleanup(vscode.languages.setLanguageConfiguration("ra_syntax_tree", { | ||
19 | brackets: [["[", ")"]], | ||
20 | })); | ||
21 | |||
22 | return async () => { | ||
23 | const editor = vscode.window.activeTextEditor; | ||
24 | const rangeEnabled = !!editor && !editor.selection.isEmpty; | ||
25 | |||
26 | const uri = rangeEnabled | ||
27 | ? vscode.Uri.parse(`${tdcp.uri.toString()}?range=true`) | ||
28 | : tdcp.uri; | ||
29 | |||
30 | const document = await vscode.workspace.openTextDocument(uri); | ||
31 | |||
32 | tdcp.eventEmitter.fire(uri); | ||
33 | |||
34 | void await vscode.window.showTextDocument(document, { | ||
35 | viewColumn: vscode.ViewColumn.Two, | ||
36 | preserveFocus: true | ||
37 | }); | ||
38 | }; | ||
39 | } | ||
40 | |||
41 | class TextDocumentContentProvider implements vscode.TextDocumentContentProvider { | ||
42 | readonly uri = vscode.Uri.parse('rust-analyzer://syntaxtree/tree.rast'); | ||
43 | readonly eventEmitter = new vscode.EventEmitter<vscode.Uri>(); | ||
44 | |||
45 | |||
46 | constructor(private readonly ctx: Ctx) { | ||
47 | vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, ctx.subscriptions); | ||
48 | vscode.window.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor, this, ctx.subscriptions); | ||
49 | } | ||
50 | |||
51 | private onDidChangeTextDocument(event: vscode.TextDocumentChangeEvent) { | ||
52 | if (isRustDocument(event.document)) { | ||
53 | // We need to order this after language server updates, but there's no API for that. | ||
54 | // Hence, good old sleep(). | ||
55 | void sleep(10).then(() => this.eventEmitter.fire(this.uri)); | ||
56 | } | ||
57 | } | ||
58 | private onDidChangeActiveTextEditor(editor: vscode.TextEditor | undefined) { | ||
59 | if (editor && isRustEditor(editor)) { | ||
60 | this.eventEmitter.fire(this.uri); | ||
61 | } | ||
62 | } | ||
63 | |||
64 | provideTextDocumentContent(uri: vscode.Uri, ct: vscode.CancellationToken): vscode.ProviderResult<string> { | ||
65 | const rustEditor = this.ctx.activeRustEditor; | ||
66 | if (!rustEditor) return ''; | ||
67 | |||
68 | // When the range based query is enabled we take the range of the selection | ||
69 | const range = uri.query === 'range=true' && !rustEditor.selection.isEmpty | ||
70 | ? this.ctx.client.code2ProtocolConverter.asRange(rustEditor.selection) | ||
71 | : null; | ||
72 | |||
73 | const params = { textDocument: { uri: rustEditor.document.uri.toString() }, range, }; | ||
74 | return this.ctx.client.sendRequest(ra.syntaxTree, params, ct); | ||
75 | } | ||
76 | |||
77 | get onDidChange(): vscode.Event<vscode.Uri> { | ||
78 | return this.eventEmitter.event; | ||
79 | } | ||
80 | } | ||
81 | 2 | ||
3 | import { Ctx, Disposable } from './ctx'; | ||
4 | import { RustEditor, isRustEditor } from './util'; | ||
82 | 5 | ||
83 | // FIXME: consider implementing this via the Tree View API? | 6 | // FIXME: consider implementing this via the Tree View API? |
84 | // https://code.visualstudio.com/api/extension-guides/tree-view | 7 | // https://code.visualstudio.com/api/extension-guides/tree-view |
85 | class AstInspector implements vscode.HoverProvider, vscode.DefinitionProvider, Disposable { | 8 | export class AstInspector implements vscode.HoverProvider, vscode.DefinitionProvider, Disposable { |
86 | private readonly astDecorationType = vscode.window.createTextEditorDecorationType({ | 9 | private readonly astDecorationType = vscode.window.createTextEditorDecorationType({ |
87 | borderColor: new vscode.ThemeColor('rust_analyzer.syntaxTreeBorder'), | 10 | borderColor: new vscode.ThemeColor('rust_analyzer.syntaxTreeBorder'), |
88 | borderStyle: "solid", | 11 | borderStyle: "solid", |
89 | borderWidth: "2px", | 12 | borderWidth: "2px", |
90 | |||
91 | }); | 13 | }); |
92 | private rustEditor: undefined | RustEditor; | 14 | private rustEditor: undefined | RustEditor; |
93 | 15 | ||
@@ -113,7 +35,7 @@ class AstInspector implements vscode.HoverProvider, vscode.DefinitionProvider, D | |||
113 | }); | 35 | }); |
114 | 36 | ||
115 | constructor(ctx: Ctx) { | 37 | constructor(ctx: Ctx) { |
116 | ctx.pushCleanup(vscode.languages.registerHoverProvider({ scheme: AST_FILE_SCHEME }, this)); | 38 | ctx.pushCleanup(vscode.languages.registerHoverProvider({ scheme: 'rust-analyzer' }, this)); |
117 | ctx.pushCleanup(vscode.languages.registerDefinitionProvider({ language: "rust" }, this)); | 39 | ctx.pushCleanup(vscode.languages.registerDefinitionProvider({ language: "rust" }, this)); |
118 | vscode.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, ctx.subscriptions); | 40 | vscode.workspace.onDidCloseTextDocument(this.onDidCloseTextDocument, this, ctx.subscriptions); |
119 | vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, ctx.subscriptions); | 41 | vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, ctx.subscriptions); |
@@ -146,7 +68,7 @@ class AstInspector implements vscode.HoverProvider, vscode.DefinitionProvider, D | |||
146 | } | 68 | } |
147 | 69 | ||
148 | private findAstTextEditor(): undefined | vscode.TextEditor { | 70 | private findAstTextEditor(): undefined | vscode.TextEditor { |
149 | return vscode.window.visibleTextEditors.find(it => it.document.uri.scheme === AST_FILE_SCHEME); | 71 | return vscode.window.visibleTextEditors.find(it => it.document.uri.scheme === 'rust-analyzer'); |
150 | } | 72 | } |
151 | 73 | ||
152 | private setRustEditor(newRustEditor: undefined | RustEditor) { | 74 | private setRustEditor(newRustEditor: undefined | RustEditor) { |
diff --git a/editors/code/src/commands.ts b/editors/code/src/commands.ts new file mode 100644 index 000000000..534d2a984 --- /dev/null +++ b/editors/code/src/commands.ts | |||
@@ -0,0 +1,416 @@ | |||
1 | import * as vscode from 'vscode'; | ||
2 | import * as lc from 'vscode-languageclient'; | ||
3 | import * as ra from './lsp_ext'; | ||
4 | |||
5 | import { Ctx, Cmd } from './ctx'; | ||
6 | import { applySnippetWorkspaceEdit, applySnippetTextEdits } from './snippets'; | ||
7 | import { spawnSync } from 'child_process'; | ||
8 | import { RunnableQuickPick, selectRunnable, createTask } from './run'; | ||
9 | import { AstInspector } from './ast_inspector'; | ||
10 | import { isRustDocument, sleep, isRustEditor } from './util'; | ||
11 | import { startDebugSession, makeDebugConfig } from './debug'; | ||
12 | |||
13 | export * from './ast_inspector'; | ||
14 | export * from './run'; | ||
15 | |||
16 | export function analyzerStatus(ctx: Ctx): Cmd { | ||
17 | const tdcp = new class implements vscode.TextDocumentContentProvider { | ||
18 | readonly uri = vscode.Uri.parse('rust-analyzer-status://status'); | ||
19 | readonly eventEmitter = new vscode.EventEmitter<vscode.Uri>(); | ||
20 | |||
21 | provideTextDocumentContent(_uri: vscode.Uri): vscode.ProviderResult<string> { | ||
22 | if (!vscode.window.activeTextEditor) return ''; | ||
23 | |||
24 | return ctx.client.sendRequest(ra.analyzerStatus, null); | ||
25 | } | ||
26 | |||
27 | get onDidChange(): vscode.Event<vscode.Uri> { | ||
28 | return this.eventEmitter.event; | ||
29 | } | ||
30 | }(); | ||
31 | |||
32 | let poller: NodeJS.Timer | undefined = undefined; | ||
33 | |||
34 | ctx.pushCleanup( | ||
35 | vscode.workspace.registerTextDocumentContentProvider( | ||
36 | 'rust-analyzer-status', | ||
37 | tdcp, | ||
38 | ), | ||
39 | ); | ||
40 | |||
41 | ctx.pushCleanup({ | ||
42 | dispose() { | ||
43 | if (poller !== undefined) { | ||
44 | clearInterval(poller); | ||
45 | } | ||
46 | }, | ||
47 | }); | ||
48 | |||
49 | return async () => { | ||
50 | if (poller === undefined) { | ||
51 | poller = setInterval(() => tdcp.eventEmitter.fire(tdcp.uri), 1000); | ||
52 | } | ||
53 | const document = await vscode.workspace.openTextDocument(tdcp.uri); | ||
54 | return vscode.window.showTextDocument(document, vscode.ViewColumn.Two, true); | ||
55 | }; | ||
56 | } | ||
57 | |||
58 | export function matchingBrace(ctx: Ctx): Cmd { | ||
59 | return async () => { | ||
60 | const editor = ctx.activeRustEditor; | ||
61 | const client = ctx.client; | ||
62 | if (!editor || !client) return; | ||
63 | |||
64 | const response = await client.sendRequest(ra.matchingBrace, { | ||
65 | textDocument: { uri: editor.document.uri.toString() }, | ||
66 | positions: editor.selections.map(s => | ||
67 | client.code2ProtocolConverter.asPosition(s.active), | ||
68 | ), | ||
69 | }); | ||
70 | editor.selections = editor.selections.map((sel, idx) => { | ||
71 | const active = client.protocol2CodeConverter.asPosition( | ||
72 | response[idx], | ||
73 | ); | ||
74 | const anchor = sel.isEmpty ? active : sel.anchor; | ||
75 | return new vscode.Selection(anchor, active); | ||
76 | }); | ||
77 | editor.revealRange(editor.selection); | ||
78 | }; | ||
79 | } | ||
80 | |||
81 | export function joinLines(ctx: Ctx): Cmd { | ||
82 | return async () => { | ||
83 | const editor = ctx.activeRustEditor; | ||
84 | const client = ctx.client; | ||
85 | if (!editor || !client) return; | ||
86 | |||
87 | const items: lc.TextEdit[] = await client.sendRequest(ra.joinLines, { | ||
88 | ranges: editor.selections.map((it) => client.code2ProtocolConverter.asRange(it)), | ||
89 | textDocument: { uri: editor.document.uri.toString() }, | ||
90 | }); | ||
91 | editor.edit((builder) => { | ||
92 | client.protocol2CodeConverter.asTextEdits(items).forEach((edit) => { | ||
93 | builder.replace(edit.range, edit.newText); | ||
94 | }); | ||
95 | }); | ||
96 | }; | ||
97 | } | ||
98 | |||
99 | export function onEnter(ctx: Ctx): Cmd { | ||
100 | async function handleKeypress() { | ||
101 | const editor = ctx.activeRustEditor; | ||
102 | const client = ctx.client; | ||
103 | |||
104 | if (!editor || !client) return false; | ||
105 | |||
106 | const lcEdits = await client.sendRequest(ra.onEnter, { | ||
107 | textDocument: { uri: editor.document.uri.toString() }, | ||
108 | position: client.code2ProtocolConverter.asPosition( | ||
109 | editor.selection.active, | ||
110 | ), | ||
111 | }).catch(_error => { | ||
112 | // client.logFailedRequest(OnEnterRequest.type, error); | ||
113 | return null; | ||
114 | }); | ||
115 | if (!lcEdits) return false; | ||
116 | |||
117 | const edits = client.protocol2CodeConverter.asTextEdits(lcEdits); | ||
118 | await applySnippetTextEdits(editor, edits); | ||
119 | return true; | ||
120 | } | ||
121 | |||
122 | return async () => { | ||
123 | if (await handleKeypress()) return; | ||
124 | |||
125 | await vscode.commands.executeCommand('default:type', { text: '\n' }); | ||
126 | }; | ||
127 | } | ||
128 | |||
129 | export function parentModule(ctx: Ctx): Cmd { | ||
130 | return async () => { | ||
131 | const editor = ctx.activeRustEditor; | ||
132 | const client = ctx.client; | ||
133 | if (!editor || !client) return; | ||
134 | |||
135 | const response = await client.sendRequest(ra.parentModule, { | ||
136 | textDocument: { uri: editor.document.uri.toString() }, | ||
137 | position: client.code2ProtocolConverter.asPosition( | ||
138 | editor.selection.active, | ||
139 | ), | ||
140 | }); | ||
141 | const loc = response[0]; | ||
142 | if (!loc) return; | ||
143 | |||
144 | const uri = client.protocol2CodeConverter.asUri(loc.targetUri); | ||
145 | const range = client.protocol2CodeConverter.asRange(loc.targetRange); | ||
146 | |||
147 | const doc = await vscode.workspace.openTextDocument(uri); | ||
148 | const e = await vscode.window.showTextDocument(doc); | ||
149 | e.selection = new vscode.Selection(range.start, range.start); | ||
150 | e.revealRange(range, vscode.TextEditorRevealType.InCenter); | ||
151 | }; | ||
152 | } | ||
153 | |||
154 | export function ssr(ctx: Ctx): Cmd { | ||
155 | return async () => { | ||
156 | const client = ctx.client; | ||
157 | if (!client) return; | ||
158 | |||
159 | const options: vscode.InputBoxOptions = { | ||
160 | value: "() ==>> ()", | ||
161 | prompt: "Enter request, for example 'Foo($a:expr) ==> Foo::new($a)' ", | ||
162 | validateInput: async (x: string) => { | ||
163 | try { | ||
164 | await client.sendRequest(ra.ssr, { query: x, parseOnly: true }); | ||
165 | } catch (e) { | ||
166 | return e.toString(); | ||
167 | } | ||
168 | return null; | ||
169 | } | ||
170 | }; | ||
171 | const request = await vscode.window.showInputBox(options); | ||
172 | if (!request) return; | ||
173 | |||
174 | const edit = await client.sendRequest(ra.ssr, { query: request, parseOnly: false }); | ||
175 | |||
176 | await vscode.workspace.applyEdit(client.protocol2CodeConverter.asWorkspaceEdit(edit)); | ||
177 | }; | ||
178 | } | ||
179 | |||
180 | export function serverVersion(ctx: Ctx): Cmd { | ||
181 | return async () => { | ||
182 | const { stdout } = spawnSync(ctx.serverPath, ["--version"], { encoding: "utf8" }); | ||
183 | const commitHash = stdout.slice(`rust-analyzer `.length).trim(); | ||
184 | const { releaseTag } = ctx.config.package; | ||
185 | |||
186 | void vscode.window.showInformationMessage( | ||
187 | `rust-analyzer version: ${releaseTag ?? "unreleased"} (${commitHash})` | ||
188 | ); | ||
189 | }; | ||
190 | } | ||
191 | |||
192 | export function toggleInlayHints(ctx: Ctx): Cmd { | ||
193 | return async () => { | ||
194 | await vscode | ||
195 | .workspace | ||
196 | .getConfiguration(`${ctx.config.rootSection}.inlayHints`) | ||
197 | .update('enable', !ctx.config.inlayHints.enable, vscode.ConfigurationTarget.Workspace); | ||
198 | }; | ||
199 | } | ||
200 | |||
201 | // Opens the virtual file that will show the syntax tree | ||
202 | // | ||
203 | // The contents of the file come from the `TextDocumentContentProvider` | ||
204 | export function syntaxTree(ctx: Ctx): Cmd { | ||
205 | const tdcp = new class implements vscode.TextDocumentContentProvider { | ||
206 | readonly uri = vscode.Uri.parse('rust-analyzer://syntaxtree/tree.rast'); | ||
207 | readonly eventEmitter = new vscode.EventEmitter<vscode.Uri>(); | ||
208 | constructor() { | ||
209 | vscode.workspace.onDidChangeTextDocument(this.onDidChangeTextDocument, this, ctx.subscriptions); | ||
210 | vscode.window.onDidChangeActiveTextEditor(this.onDidChangeActiveTextEditor, this, ctx.subscriptions); | ||
211 | } | ||
212 | |||
213 | private onDidChangeTextDocument(event: vscode.TextDocumentChangeEvent) { | ||
214 | if (isRustDocument(event.document)) { | ||
215 | // We need to order this after language server updates, but there's no API for that. | ||
216 | // Hence, good old sleep(). | ||
217 | void sleep(10).then(() => this.eventEmitter.fire(this.uri)); | ||
218 | } | ||
219 | } | ||
220 | private onDidChangeActiveTextEditor(editor: vscode.TextEditor | undefined) { | ||
221 | if (editor && isRustEditor(editor)) { | ||
222 | this.eventEmitter.fire(this.uri); | ||
223 | } | ||
224 | } | ||
225 | |||
226 | provideTextDocumentContent(uri: vscode.Uri, ct: vscode.CancellationToken): vscode.ProviderResult<string> { | ||
227 | const rustEditor = ctx.activeRustEditor; | ||
228 | if (!rustEditor) return ''; | ||
229 | |||
230 | // When the range based query is enabled we take the range of the selection | ||
231 | const range = uri.query === 'range=true' && !rustEditor.selection.isEmpty | ||
232 | ? ctx.client.code2ProtocolConverter.asRange(rustEditor.selection) | ||
233 | : null; | ||
234 | |||
235 | const params = { textDocument: { uri: rustEditor.document.uri.toString() }, range, }; | ||
236 | return ctx.client.sendRequest(ra.syntaxTree, params, ct); | ||
237 | } | ||
238 | |||
239 | get onDidChange(): vscode.Event<vscode.Uri> { | ||
240 | return this.eventEmitter.event; | ||
241 | } | ||
242 | }; | ||
243 | |||
244 | void new AstInspector(ctx); | ||
245 | |||
246 | ctx.pushCleanup(vscode.workspace.registerTextDocumentContentProvider('rust-analyzer', tdcp)); | ||
247 | ctx.pushCleanup(vscode.languages.setLanguageConfiguration("ra_syntax_tree", { | ||
248 | brackets: [["[", ")"]], | ||
249 | })); | ||
250 | |||
251 | return async () => { | ||
252 | const editor = vscode.window.activeTextEditor; | ||
253 | const rangeEnabled = !!editor && !editor.selection.isEmpty; | ||
254 | |||
255 | const uri = rangeEnabled | ||
256 | ? vscode.Uri.parse(`${tdcp.uri.toString()}?range=true`) | ||
257 | : tdcp.uri; | ||
258 | |||
259 | const document = await vscode.workspace.openTextDocument(uri); | ||
260 | |||
261 | tdcp.eventEmitter.fire(uri); | ||
262 | |||
263 | void await vscode.window.showTextDocument(document, { | ||
264 | viewColumn: vscode.ViewColumn.Two, | ||
265 | preserveFocus: true | ||
266 | }); | ||
267 | }; | ||
268 | } | ||
269 | |||
270 | |||
271 | // Opens the virtual file that will show the syntax tree | ||
272 | // | ||
273 | // The contents of the file come from the `TextDocumentContentProvider` | ||
274 | export function expandMacro(ctx: Ctx): Cmd { | ||
275 | function codeFormat(expanded: ra.ExpandedMacro): string { | ||
276 | let result = `// Recursive expansion of ${expanded.name}! macro\n`; | ||
277 | result += '// ' + '='.repeat(result.length - 3); | ||
278 | result += '\n\n'; | ||
279 | result += expanded.expansion; | ||
280 | |||
281 | return result; | ||
282 | } | ||
283 | |||
284 | const tdcp = new class implements vscode.TextDocumentContentProvider { | ||
285 | uri = vscode.Uri.parse('rust-analyzer://expandMacro/[EXPANSION].rs'); | ||
286 | eventEmitter = new vscode.EventEmitter<vscode.Uri>(); | ||
287 | async provideTextDocumentContent(_uri: vscode.Uri): Promise<string> { | ||
288 | const editor = vscode.window.activeTextEditor; | ||
289 | const client = ctx.client; | ||
290 | if (!editor || !client) return ''; | ||
291 | |||
292 | const position = editor.selection.active; | ||
293 | |||
294 | const expanded = await client.sendRequest(ra.expandMacro, { | ||
295 | textDocument: { uri: editor.document.uri.toString() }, | ||
296 | position, | ||
297 | }); | ||
298 | |||
299 | if (expanded == null) return 'Not available'; | ||
300 | |||
301 | return codeFormat(expanded); | ||
302 | } | ||
303 | |||
304 | get onDidChange(): vscode.Event<vscode.Uri> { | ||
305 | return this.eventEmitter.event; | ||
306 | } | ||
307 | }(); | ||
308 | |||
309 | ctx.pushCleanup( | ||
310 | vscode.workspace.registerTextDocumentContentProvider( | ||
311 | 'rust-analyzer', | ||
312 | tdcp, | ||
313 | ), | ||
314 | ); | ||
315 | |||
316 | return async () => { | ||
317 | const document = await vscode.workspace.openTextDocument(tdcp.uri); | ||
318 | tdcp.eventEmitter.fire(tdcp.uri); | ||
319 | return vscode.window.showTextDocument( | ||
320 | document, | ||
321 | vscode.ViewColumn.Two, | ||
322 | true, | ||
323 | ); | ||
324 | }; | ||
325 | } | ||
326 | |||
327 | export function collectGarbage(ctx: Ctx): Cmd { | ||
328 | return async () => ctx.client.sendRequest(ra.collectGarbage, null); | ||
329 | } | ||
330 | |||
331 | export function showReferences(ctx: Ctx): Cmd { | ||
332 | return (uri: string, position: lc.Position, locations: lc.Location[]) => { | ||
333 | const client = ctx.client; | ||
334 | if (client) { | ||
335 | vscode.commands.executeCommand( | ||
336 | 'editor.action.showReferences', | ||
337 | vscode.Uri.parse(uri), | ||
338 | client.protocol2CodeConverter.asPosition(position), | ||
339 | locations.map(client.protocol2CodeConverter.asLocation), | ||
340 | ); | ||
341 | } | ||
342 | }; | ||
343 | } | ||
344 | |||
345 | export function applyActionGroup(_ctx: Ctx): Cmd { | ||
346 | return async (actions: { label: string; edit: vscode.WorkspaceEdit }[]) => { | ||
347 | const selectedAction = await vscode.window.showQuickPick(actions); | ||
348 | if (!selectedAction) return; | ||
349 | await applySnippetWorkspaceEdit(selectedAction.edit); | ||
350 | }; | ||
351 | } | ||
352 | |||
353 | export function applySnippetWorkspaceEditCommand(_ctx: Ctx): Cmd { | ||
354 | return async (edit: vscode.WorkspaceEdit) => { | ||
355 | await applySnippetWorkspaceEdit(edit); | ||
356 | }; | ||
357 | } | ||
358 | |||
359 | export function run(ctx: Ctx): Cmd { | ||
360 | let prevRunnable: RunnableQuickPick | undefined; | ||
361 | |||
362 | return async () => { | ||
363 | const item = await selectRunnable(ctx, prevRunnable); | ||
364 | if (!item) return; | ||
365 | |||
366 | item.detail = 'rerun'; | ||
367 | prevRunnable = item; | ||
368 | const task = createTask(item.runnable); | ||
369 | return await vscode.tasks.executeTask(task); | ||
370 | }; | ||
371 | } | ||
372 | |||
373 | export function runSingle(ctx: Ctx): Cmd { | ||
374 | return async (runnable: ra.Runnable) => { | ||
375 | const editor = ctx.activeRustEditor; | ||
376 | if (!editor) return; | ||
377 | |||
378 | const task = createTask(runnable); | ||
379 | task.group = vscode.TaskGroup.Build; | ||
380 | task.presentationOptions = { | ||
381 | reveal: vscode.TaskRevealKind.Always, | ||
382 | panel: vscode.TaskPanelKind.Dedicated, | ||
383 | clear: true, | ||
384 | }; | ||
385 | |||
386 | return vscode.tasks.executeTask(task); | ||
387 | }; | ||
388 | } | ||
389 | |||
390 | export function debug(ctx: Ctx): Cmd { | ||
391 | let prevDebuggee: RunnableQuickPick | undefined; | ||
392 | |||
393 | return async () => { | ||
394 | const item = await selectRunnable(ctx, prevDebuggee, true); | ||
395 | if (!item) return; | ||
396 | |||
397 | item.detail = 'restart'; | ||
398 | prevDebuggee = item; | ||
399 | return await startDebugSession(ctx, item.runnable); | ||
400 | }; | ||
401 | } | ||
402 | |||
403 | export function debugSingle(ctx: Ctx): Cmd { | ||
404 | return async (config: ra.Runnable) => { | ||
405 | await startDebugSession(ctx, config); | ||
406 | }; | ||
407 | } | ||
408 | |||
409 | export function newDebugConfig(ctx: Ctx): Cmd { | ||
410 | return async () => { | ||
411 | const item = await selectRunnable(ctx, undefined, true, false); | ||
412 | if (!item) return; | ||
413 | |||
414 | await makeDebugConfig(ctx, item.runnable); | ||
415 | }; | ||
416 | } | ||
diff --git a/editors/code/src/commands/analyzer_status.ts b/editors/code/src/commands/analyzer_status.ts deleted file mode 100644 index 09daa3402..000000000 --- a/editors/code/src/commands/analyzer_status.ts +++ /dev/null | |||
@@ -1,51 +0,0 @@ | |||
1 | import * as vscode from 'vscode'; | ||
2 | |||
3 | import * as ra from '../rust-analyzer-api'; | ||
4 | import { Ctx, Cmd } from '../ctx'; | ||
5 | |||
6 | // Shows status of rust-analyzer (for debugging) | ||
7 | export function analyzerStatus(ctx: Ctx): Cmd { | ||
8 | let poller: NodeJS.Timer | undefined = undefined; | ||
9 | const tdcp = new TextDocumentContentProvider(ctx); | ||
10 | |||
11 | ctx.pushCleanup( | ||
12 | vscode.workspace.registerTextDocumentContentProvider( | ||
13 | 'rust-analyzer-status', | ||
14 | tdcp, | ||
15 | ), | ||
16 | ); | ||
17 | |||
18 | ctx.pushCleanup({ | ||
19 | dispose() { | ||
20 | if (poller !== undefined) { | ||
21 | clearInterval(poller); | ||
22 | } | ||
23 | }, | ||
24 | }); | ||
25 | |||
26 | return async () => { | ||
27 | if (poller === undefined) { | ||
28 | poller = setInterval(() => tdcp.eventEmitter.fire(tdcp.uri), 1000); | ||
29 | } | ||
30 | const document = await vscode.workspace.openTextDocument(tdcp.uri); | ||
31 | return vscode.window.showTextDocument(document, vscode.ViewColumn.Two, true); | ||
32 | }; | ||
33 | } | ||
34 | |||
35 | class TextDocumentContentProvider implements vscode.TextDocumentContentProvider { | ||
36 | readonly uri = vscode.Uri.parse('rust-analyzer-status://status'); | ||
37 | readonly eventEmitter = new vscode.EventEmitter<vscode.Uri>(); | ||
38 | |||
39 | constructor(private readonly ctx: Ctx) { | ||
40 | } | ||
41 | |||
42 | provideTextDocumentContent(_uri: vscode.Uri): vscode.ProviderResult<string> { | ||
43 | if (!vscode.window.activeTextEditor) return ''; | ||
44 | |||
45 | return this.ctx.client.sendRequest(ra.analyzerStatus, null); | ||
46 | } | ||
47 | |||
48 | get onDidChange(): vscode.Event<vscode.Uri> { | ||
49 | return this.eventEmitter.event; | ||
50 | } | ||
51 | } | ||
diff --git a/editors/code/src/commands/expand_macro.ts b/editors/code/src/commands/expand_macro.ts deleted file mode 100644 index 23f2ef1d5..000000000 --- a/editors/code/src/commands/expand_macro.ts +++ /dev/null | |||
@@ -1,66 +0,0 @@ | |||
1 | import * as vscode from 'vscode'; | ||
2 | import * as ra from '../rust-analyzer-api'; | ||
3 | |||
4 | import { Ctx, Cmd } from '../ctx'; | ||
5 | |||
6 | // Opens the virtual file that will show the syntax tree | ||
7 | // | ||
8 | // The contents of the file come from the `TextDocumentContentProvider` | ||
9 | export function expandMacro(ctx: Ctx): Cmd { | ||
10 | const tdcp = new TextDocumentContentProvider(ctx); | ||
11 | ctx.pushCleanup( | ||
12 | vscode.workspace.registerTextDocumentContentProvider( | ||
13 | 'rust-analyzer', | ||
14 | tdcp, | ||
15 | ), | ||
16 | ); | ||
17 | |||
18 | return async () => { | ||
19 | const document = await vscode.workspace.openTextDocument(tdcp.uri); | ||
20 | tdcp.eventEmitter.fire(tdcp.uri); | ||
21 | return vscode.window.showTextDocument( | ||
22 | document, | ||
23 | vscode.ViewColumn.Two, | ||
24 | true, | ||
25 | ); | ||
26 | }; | ||
27 | } | ||
28 | |||
29 | function codeFormat(expanded: ra.ExpandedMacro): string { | ||
30 | let result = `// Recursive expansion of ${expanded.name}! macro\n`; | ||
31 | result += '// ' + '='.repeat(result.length - 3); | ||
32 | result += '\n\n'; | ||
33 | result += expanded.expansion; | ||
34 | |||
35 | return result; | ||
36 | } | ||
37 | |||
38 | class TextDocumentContentProvider | ||
39 | implements vscode.TextDocumentContentProvider { | ||
40 | uri = vscode.Uri.parse('rust-analyzer://expandMacro/[EXPANSION].rs'); | ||
41 | eventEmitter = new vscode.EventEmitter<vscode.Uri>(); | ||
42 | |||
43 | constructor(private readonly ctx: Ctx) { | ||
44 | } | ||
45 | |||
46 | async provideTextDocumentContent(_uri: vscode.Uri): Promise<string> { | ||
47 | const editor = vscode.window.activeTextEditor; | ||
48 | const client = this.ctx.client; | ||
49 | if (!editor || !client) return ''; | ||
50 | |||
51 | const position = editor.selection.active; | ||
52 | |||
53 | const expanded = await client.sendRequest(ra.expandMacro, { | ||
54 | textDocument: { uri: editor.document.uri.toString() }, | ||
55 | position, | ||
56 | }); | ||
57 | |||
58 | if (expanded == null) return 'Not available'; | ||
59 | |||
60 | return codeFormat(expanded); | ||
61 | } | ||
62 | |||
63 | get onDidChange(): vscode.Event<vscode.Uri> { | ||
64 | return this.eventEmitter.event; | ||
65 | } | ||
66 | } | ||
diff --git a/editors/code/src/commands/join_lines.ts b/editors/code/src/commands/join_lines.ts deleted file mode 100644 index 0bf1ee6e6..000000000 --- a/editors/code/src/commands/join_lines.ts +++ /dev/null | |||
@@ -1,22 +0,0 @@ | |||
1 | import * as ra from '../rust-analyzer-api'; | ||
2 | import * as lc from 'vscode-languageclient'; | ||
3 | |||
4 | import { Ctx, Cmd } from '../ctx'; | ||
5 | |||
6 | export function joinLines(ctx: Ctx): Cmd { | ||
7 | return async () => { | ||
8 | const editor = ctx.activeRustEditor; | ||
9 | const client = ctx.client; | ||
10 | if (!editor || !client) return; | ||
11 | |||
12 | const items: lc.TextEdit[] = await client.sendRequest(ra.joinLines, { | ||
13 | ranges: editor.selections.map((it) => client.code2ProtocolConverter.asRange(it)), | ||
14 | textDocument: { uri: editor.document.uri.toString() }, | ||
15 | }); | ||
16 | editor.edit((builder) => { | ||
17 | client.protocol2CodeConverter.asTextEdits(items).forEach((edit) => { | ||
18 | builder.replace(edit.range, edit.newText); | ||
19 | }); | ||
20 | }); | ||
21 | }; | ||
22 | } | ||
diff --git a/editors/code/src/commands/matching_brace.ts b/editors/code/src/commands/matching_brace.ts deleted file mode 100644 index a60776e2d..000000000 --- a/editors/code/src/commands/matching_brace.ts +++ /dev/null | |||
@@ -1,27 +0,0 @@ | |||
1 | import * as vscode from 'vscode'; | ||
2 | import * as ra from '../rust-analyzer-api'; | ||
3 | |||
4 | import { Ctx, Cmd } from '../ctx'; | ||
5 | |||
6 | export function matchingBrace(ctx: Ctx): Cmd { | ||
7 | return async () => { | ||
8 | const editor = ctx.activeRustEditor; | ||
9 | const client = ctx.client; | ||
10 | if (!editor || !client) return; | ||
11 | |||
12 | const response = await client.sendRequest(ra.findMatchingBrace, { | ||
13 | textDocument: { uri: editor.document.uri.toString() }, | ||
14 | offsets: editor.selections.map(s => | ||
15 | client.code2ProtocolConverter.asPosition(s.active), | ||
16 | ), | ||
17 | }); | ||
18 | editor.selections = editor.selections.map((sel, idx) => { | ||
19 | const active = client.protocol2CodeConverter.asPosition( | ||
20 | response[idx], | ||
21 | ); | ||
22 | const anchor = sel.isEmpty ? active : sel.anchor; | ||
23 | return new vscode.Selection(anchor, active); | ||
24 | }); | ||
25 | editor.revealRange(editor.selection); | ||
26 | }; | ||
27 | } | ||
diff --git a/editors/code/src/commands/on_enter.ts b/editors/code/src/commands/on_enter.ts deleted file mode 100644 index a7871c31e..000000000 --- a/editors/code/src/commands/on_enter.ts +++ /dev/null | |||
@@ -1,35 +0,0 @@ | |||
1 | import * as vscode from 'vscode'; | ||
2 | import * as ra from '../rust-analyzer-api'; | ||
3 | |||
4 | import { Cmd, Ctx } from '../ctx'; | ||
5 | import { applySnippetWorkspaceEdit } from '.'; | ||
6 | |||
7 | async function handleKeypress(ctx: Ctx) { | ||
8 | const editor = ctx.activeRustEditor; | ||
9 | const client = ctx.client; | ||
10 | |||
11 | if (!editor || !client) return false; | ||
12 | |||
13 | const change = await client.sendRequest(ra.onEnter, { | ||
14 | textDocument: { uri: editor.document.uri.toString() }, | ||
15 | position: client.code2ProtocolConverter.asPosition( | ||
16 | editor.selection.active, | ||
17 | ), | ||
18 | }).catch(_error => { | ||
19 | // client.logFailedRequest(OnEnterRequest.type, error); | ||
20 | return null; | ||
21 | }); | ||
22 | if (!change) return false; | ||
23 | |||
24 | const workspaceEdit = client.protocol2CodeConverter.asWorkspaceEdit(change); | ||
25 | await applySnippetWorkspaceEdit(workspaceEdit); | ||
26 | return true; | ||
27 | } | ||
28 | |||
29 | export function onEnter(ctx: Ctx): Cmd { | ||
30 | return async () => { | ||
31 | if (await handleKeypress(ctx)) return; | ||
32 | |||
33 | await vscode.commands.executeCommand('default:type', { text: '\n' }); | ||
34 | }; | ||
35 | } | ||
diff --git a/editors/code/src/commands/parent_module.ts b/editors/code/src/commands/parent_module.ts deleted file mode 100644 index 8f78ddd71..000000000 --- a/editors/code/src/commands/parent_module.ts +++ /dev/null | |||
@@ -1,29 +0,0 @@ | |||
1 | import * as vscode from 'vscode'; | ||
2 | import * as ra from '../rust-analyzer-api'; | ||
3 | |||
4 | import { Ctx, Cmd } from '../ctx'; | ||
5 | |||
6 | export function parentModule(ctx: Ctx): Cmd { | ||
7 | return async () => { | ||
8 | const editor = ctx.activeRustEditor; | ||
9 | const client = ctx.client; | ||
10 | if (!editor || !client) return; | ||
11 | |||
12 | const response = await client.sendRequest(ra.parentModule, { | ||
13 | textDocument: { uri: editor.document.uri.toString() }, | ||
14 | position: client.code2ProtocolConverter.asPosition( | ||
15 | editor.selection.active, | ||
16 | ), | ||
17 | }); | ||
18 | const loc = response[0]; | ||
19 | if (loc == null) return; | ||
20 | |||
21 | const uri = client.protocol2CodeConverter.asUri(loc.uri); | ||
22 | const range = client.protocol2CodeConverter.asRange(loc.range); | ||
23 | |||
24 | const doc = await vscode.workspace.openTextDocument(uri); | ||
25 | const e = await vscode.window.showTextDocument(doc); | ||
26 | e.selection = new vscode.Selection(range.start, range.start); | ||
27 | e.revealRange(range, vscode.TextEditorRevealType.InCenter); | ||
28 | }; | ||
29 | } | ||
diff --git a/editors/code/src/commands/server_version.ts b/editors/code/src/commands/server_version.ts deleted file mode 100644 index d64ac726e..000000000 --- a/editors/code/src/commands/server_version.ts +++ /dev/null | |||
@@ -1,15 +0,0 @@ | |||
1 | import * as vscode from "vscode"; | ||
2 | import { spawnSync } from "child_process"; | ||
3 | import { Ctx, Cmd } from '../ctx'; | ||
4 | |||
5 | export function serverVersion(ctx: Ctx): Cmd { | ||
6 | return async () => { | ||
7 | const { stdout } = spawnSync(ctx.serverPath, ["--version"], { encoding: "utf8" }); | ||
8 | const commitHash = stdout.slice(`rust-analyzer `.length).trim(); | ||
9 | const { releaseTag } = ctx.config.package; | ||
10 | |||
11 | void vscode.window.showInformationMessage( | ||
12 | `rust-analyzer version: ${releaseTag ?? "unreleased"} (${commitHash})` | ||
13 | ); | ||
14 | }; | ||
15 | } | ||
diff --git a/editors/code/src/commands/ssr.ts b/editors/code/src/commands/ssr.ts deleted file mode 100644 index 5d40a64d2..000000000 --- a/editors/code/src/commands/ssr.ts +++ /dev/null | |||
@@ -1,30 +0,0 @@ | |||
1 | import * as vscode from 'vscode'; | ||
2 | import * as ra from "../rust-analyzer-api"; | ||
3 | |||
4 | import { Ctx, Cmd } from '../ctx'; | ||
5 | |||
6 | export function ssr(ctx: Ctx): Cmd { | ||
7 | return async () => { | ||
8 | const client = ctx.client; | ||
9 | if (!client) return; | ||
10 | |||
11 | const options: vscode.InputBoxOptions = { | ||
12 | value: "() ==>> ()", | ||
13 | prompt: "Enter request, for example 'Foo($a:expr) ==> Foo::new($a)' ", | ||
14 | validateInput: async (x: string) => { | ||
15 | try { | ||
16 | await client.sendRequest(ra.ssr, { query: x, parseOnly: true }); | ||
17 | } catch (e) { | ||
18 | return e.toString(); | ||
19 | } | ||
20 | return null; | ||
21 | } | ||
22 | }; | ||
23 | const request = await vscode.window.showInputBox(options); | ||
24 | if (!request) return; | ||
25 | |||
26 | const edit = await client.sendRequest(ra.ssr, { query: request, parseOnly: false }); | ||
27 | |||
28 | await vscode.workspace.applyEdit(client.protocol2CodeConverter.asWorkspaceEdit(edit)); | ||
29 | }; | ||
30 | } | ||
diff --git a/editors/code/src/config.ts b/editors/code/src/config.ts index ee294fbe3..e8abf8284 100644 --- a/editors/code/src/config.ts +++ b/editors/code/src/config.ts | |||
@@ -8,7 +8,7 @@ export const NIGHTLY_TAG = "nightly"; | |||
8 | export class Config { | 8 | export class Config { |
9 | readonly extensionId = "matklad.rust-analyzer"; | 9 | readonly extensionId = "matklad.rust-analyzer"; |
10 | 10 | ||
11 | private readonly rootSection = "rust-analyzer"; | 11 | readonly rootSection = "rust-analyzer"; |
12 | private readonly requiresReloadOpts = [ | 12 | private readonly requiresReloadOpts = [ |
13 | "serverPath", | 13 | "serverPath", |
14 | "cargo", | 14 | "cargo", |
diff --git a/editors/code/src/debug.ts b/editors/code/src/debug.ts index d3fe588e8..a0c9b3ab2 100644 --- a/editors/code/src/debug.ts +++ b/editors/code/src/debug.ts | |||
@@ -1,48 +1,61 @@ | |||
1 | import * as os from "os"; | 1 | import * as os from "os"; |
2 | import * as vscode from 'vscode'; | 2 | import * as vscode from 'vscode'; |
3 | import * as path from 'path'; | 3 | import * as path from 'path'; |
4 | import * as ra from './rust-analyzer-api'; | 4 | import * as ra from './lsp_ext'; |
5 | 5 | ||
6 | import { Cargo } from './cargo'; | 6 | import { Cargo } from './toolchain'; |
7 | import { Ctx } from "./ctx"; | 7 | import { Ctx } from "./ctx"; |
8 | 8 | ||
9 | const debugOutput = vscode.window.createOutputChannel("Debug"); | 9 | const debugOutput = vscode.window.createOutputChannel("Debug"); |
10 | type DebugConfigProvider = (config: ra.Runnable, executable: string, sourceFileMap?: Record<string, string>) => vscode.DebugConfiguration; | 10 | type DebugConfigProvider = (config: ra.Runnable, executable: string, sourceFileMap?: Record<string, string>) => vscode.DebugConfiguration; |
11 | 11 | ||
12 | function getLldbDebugConfig(config: ra.Runnable, executable: string, sourceFileMap?: Record<string, string>): vscode.DebugConfiguration { | 12 | export async function makeDebugConfig(ctx: Ctx, runnable: ra.Runnable): Promise<void> { |
13 | return { | 13 | const scope = ctx.activeRustEditor?.document.uri; |
14 | type: "lldb", | 14 | if (!scope) return; |
15 | request: "launch", | ||
16 | name: config.label, | ||
17 | program: executable, | ||
18 | args: config.extraArgs, | ||
19 | cwd: config.cwd, | ||
20 | sourceMap: sourceFileMap, | ||
21 | sourceLanguages: ["rust"] | ||
22 | }; | ||
23 | } | ||
24 | 15 | ||
25 | function getCppvsDebugConfig(config: ra.Runnable, executable: string, sourceFileMap?: Record<string, string>): vscode.DebugConfiguration { | 16 | const debugConfig = await getDebugConfiguration(ctx, runnable); |
26 | return { | 17 | if (!debugConfig) return; |
27 | type: (os.platform() === "win32") ? "cppvsdbg" : "cppdbg", | 18 | |
28 | request: "launch", | 19 | const wsLaunchSection = vscode.workspace.getConfiguration("launch", scope); |
29 | name: config.label, | 20 | const configurations = wsLaunchSection.get<any[]>("configurations") || []; |
30 | program: executable, | 21 | |
31 | args: config.extraArgs, | 22 | const index = configurations.findIndex(c => c.name === debugConfig.name); |
32 | cwd: config.cwd, | 23 | if (index !== -1) { |
33 | sourceFileMap: sourceFileMap, | 24 | const answer = await vscode.window.showErrorMessage(`Launch configuration '${debugConfig.name}' already exists!`, 'Cancel', 'Update'); |
34 | }; | 25 | if (answer === "Cancel") return; |
26 | |||
27 | configurations[index] = debugConfig; | ||
28 | } else { | ||
29 | configurations.push(debugConfig); | ||
30 | } | ||
31 | |||
32 | await wsLaunchSection.update("configurations", configurations); | ||
35 | } | 33 | } |
36 | 34 | ||
37 | async function getDebugExecutable(config: ra.Runnable): Promise<string> { | 35 | export async function startDebugSession(ctx: Ctx, runnable: ra.Runnable): Promise<boolean> { |
38 | const cargo = new Cargo(config.cwd || '.', debugOutput); | 36 | let debugConfig: vscode.DebugConfiguration | undefined = undefined; |
39 | const executable = await cargo.executableFromArgs(config.args); | 37 | let message = ""; |
40 | 38 | ||
41 | // if we are here, there were no compilation errors. | 39 | const wsLaunchSection = vscode.workspace.getConfiguration("launch"); |
42 | return executable; | 40 | const configurations = wsLaunchSection.get<any[]>("configurations") || []; |
41 | |||
42 | const index = configurations.findIndex(c => c.name === runnable.label); | ||
43 | if (-1 !== index) { | ||
44 | debugConfig = configurations[index]; | ||
45 | message = " (from launch.json)"; | ||
46 | debugOutput.clear(); | ||
47 | } else { | ||
48 | debugConfig = await getDebugConfiguration(ctx, runnable); | ||
49 | } | ||
50 | |||
51 | if (!debugConfig) return false; | ||
52 | |||
53 | debugOutput.appendLine(`Launching debug configuration${message}:`); | ||
54 | debugOutput.appendLine(JSON.stringify(debugConfig, null, 2)); | ||
55 | return vscode.debug.startDebugging(undefined, debugConfig); | ||
43 | } | 56 | } |
44 | 57 | ||
45 | export async function getDebugConfiguration(ctx: Ctx, config: ra.Runnable): Promise<vscode.DebugConfiguration | undefined> { | 58 | async function getDebugConfiguration(ctx: Ctx, runnable: ra.Runnable): Promise<vscode.DebugConfiguration | undefined> { |
46 | const editor = ctx.activeRustEditor; | 59 | const editor = ctx.activeRustEditor; |
47 | if (!editor) return; | 60 | if (!editor) return; |
48 | 61 | ||
@@ -78,8 +91,8 @@ export async function getDebugConfiguration(ctx: Ctx, config: ra.Runnable): Prom | |||
78 | return path.normalize(p).replace(wsFolder, '${workspaceRoot}'); | 91 | return path.normalize(p).replace(wsFolder, '${workspaceRoot}'); |
79 | } | 92 | } |
80 | 93 | ||
81 | const executable = await getDebugExecutable(config); | 94 | const executable = await getDebugExecutable(runnable); |
82 | const debugConfig = knownEngines[debugEngine.id](config, simplifyPath(executable), debugOptions.sourceFileMap); | 95 | const debugConfig = knownEngines[debugEngine.id](runnable, simplifyPath(executable), debugOptions.sourceFileMap); |
83 | if (debugConfig.type in debugOptions.engineSettings) { | 96 | if (debugConfig.type in debugOptions.engineSettings) { |
84 | const settingsMap = (debugOptions.engineSettings as any)[debugConfig.type]; | 97 | const settingsMap = (debugOptions.engineSettings as any)[debugConfig.type]; |
85 | for (var key in settingsMap) { | 98 | for (var key in settingsMap) { |
@@ -100,25 +113,35 @@ export async function getDebugConfiguration(ctx: Ctx, config: ra.Runnable): Prom | |||
100 | return debugConfig; | 113 | return debugConfig; |
101 | } | 114 | } |
102 | 115 | ||
103 | export async function startDebugSession(ctx: Ctx, config: ra.Runnable): Promise<boolean> { | 116 | async function getDebugExecutable(runnable: ra.Runnable): Promise<string> { |
104 | let debugConfig: vscode.DebugConfiguration | undefined = undefined; | 117 | const cargo = new Cargo(runnable.args.workspaceRoot || '.', debugOutput); |
105 | let message = ""; | 118 | const executable = await cargo.executableFromArgs(runnable.args.cargoArgs); |
106 | |||
107 | const wsLaunchSection = vscode.workspace.getConfiguration("launch"); | ||
108 | const configurations = wsLaunchSection.get<any[]>("configurations") || []; | ||
109 | 119 | ||
110 | const index = configurations.findIndex(c => c.name === config.label); | 120 | // if we are here, there were no compilation errors. |
111 | if (-1 !== index) { | 121 | return executable; |
112 | debugConfig = configurations[index]; | 122 | } |
113 | message = " (from launch.json)"; | ||
114 | debugOutput.clear(); | ||
115 | } else { | ||
116 | debugConfig = await getDebugConfiguration(ctx, config); | ||
117 | } | ||
118 | 123 | ||
119 | if (!debugConfig) return false; | 124 | function getLldbDebugConfig(runnable: ra.Runnable, executable: string, sourceFileMap?: Record<string, string>): vscode.DebugConfiguration { |
125 | return { | ||
126 | type: "lldb", | ||
127 | request: "launch", | ||
128 | name: runnable.label, | ||
129 | program: executable, | ||
130 | args: runnable.args.executableArgs, | ||
131 | cwd: runnable.args.workspaceRoot, | ||
132 | sourceMap: sourceFileMap, | ||
133 | sourceLanguages: ["rust"] | ||
134 | }; | ||
135 | } | ||
120 | 136 | ||
121 | debugOutput.appendLine(`Launching debug configuration${message}:`); | 137 | function getCppvsDebugConfig(runnable: ra.Runnable, executable: string, sourceFileMap?: Record<string, string>): vscode.DebugConfiguration { |
122 | debugOutput.appendLine(JSON.stringify(debugConfig, null, 2)); | 138 | return { |
123 | return vscode.debug.startDebugging(undefined, debugConfig); | 139 | type: (os.platform() === "win32") ? "cppvsdbg" : "cppdbg", |
140 | request: "launch", | ||
141 | name: runnable.label, | ||
142 | program: executable, | ||
143 | args: runnable.args.executableArgs, | ||
144 | cwd: runnable.args.workspaceRoot, | ||
145 | sourceFileMap: sourceFileMap, | ||
146 | }; | ||
124 | } | 147 | } |
diff --git a/editors/code/src/inlay_hints.ts b/editors/code/src/inlay_hints.ts index a2b07d003..9e6d6045f 100644 --- a/editors/code/src/inlay_hints.ts +++ b/editors/code/src/inlay_hints.ts | |||
@@ -1,6 +1,6 @@ | |||
1 | import * as lc from "vscode-languageclient"; | 1 | import * as lc from "vscode-languageclient"; |
2 | import * as vscode from 'vscode'; | 2 | import * as vscode from 'vscode'; |
3 | import * as ra from './rust-analyzer-api'; | 3 | import * as ra from './lsp_ext'; |
4 | 4 | ||
5 | import { Ctx, Disposable } from './ctx'; | 5 | import { Ctx, Disposable } from './ctx'; |
6 | import { sendRequestWithRetry, isRustDocument, RustDocument, RustEditor, sleep } from './util'; | 6 | import { sendRequestWithRetry, isRustDocument, RustDocument, RustEditor, sleep } from './util'; |
diff --git a/editors/code/src/lsp_ext.ts b/editors/code/src/lsp_ext.ts new file mode 100644 index 000000000..c51acfccb --- /dev/null +++ b/editors/code/src/lsp_ext.ts | |||
@@ -0,0 +1,86 @@ | |||
1 | /** | ||
2 | * This file mirrors `crates/rust-analyzer/src/req.rs` declarations. | ||
3 | */ | ||
4 | |||
5 | import * as lc from "vscode-languageclient"; | ||
6 | |||
7 | export const analyzerStatus = new lc.RequestType<null, string, void>("rust-analyzer/analyzerStatus"); | ||
8 | |||
9 | export const collectGarbage = new lc.RequestType<null, null, void>("rust-analyzer/collectGarbage"); | ||
10 | |||
11 | export interface SyntaxTreeParams { | ||
12 | textDocument: lc.TextDocumentIdentifier; | ||
13 | range: lc.Range | null; | ||
14 | } | ||
15 | export const syntaxTree = new lc.RequestType<SyntaxTreeParams, string, void>("rust-analyzer/syntaxTree"); | ||
16 | |||
17 | |||
18 | export interface ExpandMacroParams { | ||
19 | textDocument: lc.TextDocumentIdentifier; | ||
20 | position: lc.Position; | ||
21 | } | ||
22 | export interface ExpandedMacro { | ||
23 | name: string; | ||
24 | expansion: string; | ||
25 | } | ||
26 | export const expandMacro = new lc.RequestType<ExpandMacroParams, ExpandedMacro | null, void>("rust-analyzer/expandMacro"); | ||
27 | |||
28 | export interface MatchingBraceParams { | ||
29 | textDocument: lc.TextDocumentIdentifier; | ||
30 | positions: lc.Position[]; | ||
31 | } | ||
32 | export const matchingBrace = new lc.RequestType<MatchingBraceParams, lc.Position[], void>("experimental/matchingBrace"); | ||
33 | |||
34 | export const parentModule = new lc.RequestType<lc.TextDocumentPositionParams, lc.LocationLink[], void>("experimental/parentModule"); | ||
35 | |||
36 | export interface JoinLinesParams { | ||
37 | textDocument: lc.TextDocumentIdentifier; | ||
38 | ranges: lc.Range[]; | ||
39 | } | ||
40 | export const joinLines = new lc.RequestType<JoinLinesParams, lc.TextEdit[], void>("experimental/joinLines"); | ||
41 | |||
42 | export const onEnter = new lc.RequestType<lc.TextDocumentPositionParams, lc.TextEdit[], void>("experimental/onEnter"); | ||
43 | |||
44 | export interface RunnablesParams { | ||
45 | textDocument: lc.TextDocumentIdentifier; | ||
46 | position: lc.Position | null; | ||
47 | } | ||
48 | |||
49 | export interface Runnable { | ||
50 | label: string; | ||
51 | location?: lc.LocationLink; | ||
52 | kind: "cargo"; | ||
53 | args: { | ||
54 | workspaceRoot?: string; | ||
55 | cargoArgs: string[]; | ||
56 | executableArgs: string[]; | ||
57 | }; | ||
58 | } | ||
59 | export const runnables = new lc.RequestType<RunnablesParams, Runnable[], void>("experimental/runnables"); | ||
60 | |||
61 | export type InlayHint = InlayHint.TypeHint | InlayHint.ParamHint | InlayHint.ChainingHint; | ||
62 | |||
63 | export namespace InlayHint { | ||
64 | export const enum Kind { | ||
65 | TypeHint = "TypeHint", | ||
66 | ParamHint = "ParameterHint", | ||
67 | ChainingHint = "ChainingHint", | ||
68 | } | ||
69 | interface Common { | ||
70 | range: lc.Range; | ||
71 | label: string; | ||
72 | } | ||
73 | export type TypeHint = Common & { kind: Kind.TypeHint }; | ||
74 | export type ParamHint = Common & { kind: Kind.ParamHint }; | ||
75 | export type ChainingHint = Common & { kind: Kind.ChainingHint }; | ||
76 | } | ||
77 | export interface InlayHintsParams { | ||
78 | textDocument: lc.TextDocumentIdentifier; | ||
79 | } | ||
80 | export const inlayHints = new lc.RequestType<InlayHintsParams, InlayHint[], void>("rust-analyzer/inlayHints"); | ||
81 | |||
82 | export interface SsrParams { | ||
83 | query: string; | ||
84 | parseOnly: boolean; | ||
85 | } | ||
86 | export const ssr = new lc.RequestType<SsrParams, lc.WorkspaceEdit, void>('experimental/ssr'); | ||
diff --git a/editors/code/src/main.ts b/editors/code/src/main.ts index 4d4513869..b7337621c 100644 --- a/editors/code/src/main.ts +++ b/editors/code/src/main.ts | |||
@@ -1,7 +1,7 @@ | |||
1 | import * as vscode from 'vscode'; | 1 | import * as vscode from 'vscode'; |
2 | import * as path from "path"; | 2 | import * as path from "path"; |
3 | import * as os from "os"; | 3 | import * as os from "os"; |
4 | import { promises as fs } from "fs"; | 4 | import { promises as fs, PathLike } from "fs"; |
5 | 5 | ||
6 | import * as commands from './commands'; | 6 | import * as commands from './commands'; |
7 | import { activateInlayHints } from './inlay_hints'; | 7 | import { activateInlayHints } from './inlay_hints'; |
@@ -12,9 +12,13 @@ import { log, assert, isValidExecutable } from './util'; | |||
12 | import { PersistentState } from './persistent_state'; | 12 | import { PersistentState } from './persistent_state'; |
13 | import { fetchRelease, download } from './net'; | 13 | import { fetchRelease, download } from './net'; |
14 | import { activateTaskProvider } from './tasks'; | 14 | import { activateTaskProvider } from './tasks'; |
15 | import { setContextValue } from './util'; | ||
16 | import { exec } from 'child_process'; | ||
15 | 17 | ||
16 | let ctx: Ctx | undefined; | 18 | let ctx: Ctx | undefined; |
17 | 19 | ||
20 | const RUST_PROJECT_CONTEXT_NAME = "inRustProject"; | ||
21 | |||
18 | export async function activate(context: vscode.ExtensionContext) { | 22 | export async function activate(context: vscode.ExtensionContext) { |
19 | // Register a "dumb" onEnter command for the case where server fails to | 23 | // Register a "dumb" onEnter command for the case where server fails to |
20 | // start. | 24 | // start. |
@@ -53,6 +57,8 @@ export async function activate(context: vscode.ExtensionContext) { | |||
53 | // This a horribly, horribly wrong way to deal with this problem. | 57 | // This a horribly, horribly wrong way to deal with this problem. |
54 | ctx = await Ctx.create(config, context, serverPath, workspaceFolder.uri.fsPath); | 58 | ctx = await Ctx.create(config, context, serverPath, workspaceFolder.uri.fsPath); |
55 | 59 | ||
60 | setContextValue(RUST_PROJECT_CONTEXT_NAME, true); | ||
61 | |||
56 | // Commands which invokes manually via command palette, shortcut, etc. | 62 | // Commands which invokes manually via command palette, shortcut, etc. |
57 | 63 | ||
58 | // Reloading is inspired by @DanTup maneuver: https://github.com/microsoft/vscode/issues/45774#issuecomment-373423895 | 64 | // Reloading is inspired by @DanTup maneuver: https://github.com/microsoft/vscode/issues/45774#issuecomment-373423895 |
@@ -85,12 +91,12 @@ export async function activate(context: vscode.ExtensionContext) { | |||
85 | 91 | ||
86 | ctx.registerCommand('ssr', commands.ssr); | 92 | ctx.registerCommand('ssr', commands.ssr); |
87 | ctx.registerCommand('serverVersion', commands.serverVersion); | 93 | ctx.registerCommand('serverVersion', commands.serverVersion); |
94 | ctx.registerCommand('toggleInlayHints', commands.toggleInlayHints); | ||
88 | 95 | ||
89 | // Internal commands which are invoked by the server. | 96 | // Internal commands which are invoked by the server. |
90 | ctx.registerCommand('runSingle', commands.runSingle); | 97 | ctx.registerCommand('runSingle', commands.runSingle); |
91 | ctx.registerCommand('debugSingle', commands.debugSingle); | 98 | ctx.registerCommand('debugSingle', commands.debugSingle); |
92 | ctx.registerCommand('showReferences', commands.showReferences); | 99 | ctx.registerCommand('showReferences', commands.showReferences); |
93 | ctx.registerCommand('applySourceChange', commands.applySourceChange); | ||
94 | ctx.registerCommand('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEditCommand); | 100 | ctx.registerCommand('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEditCommand); |
95 | ctx.registerCommand('applyActionGroup', commands.applyActionGroup); | 101 | ctx.registerCommand('applyActionGroup', commands.applyActionGroup); |
96 | 102 | ||
@@ -108,6 +114,7 @@ export async function activate(context: vscode.ExtensionContext) { | |||
108 | } | 114 | } |
109 | 115 | ||
110 | export async function deactivate() { | 116 | export async function deactivate() { |
117 | setContextValue(RUST_PROJECT_CONTEXT_NAME, undefined); | ||
111 | await ctx?.client.stop(); | 118 | await ctx?.client.stop(); |
112 | ctx = undefined; | 119 | ctx = undefined; |
113 | } | 120 | } |
@@ -188,6 +195,46 @@ async function bootstrapServer(config: Config, state: PersistentState): Promise< | |||
188 | return path; | 195 | return path; |
189 | } | 196 | } |
190 | 197 | ||
198 | async function patchelf(dest: PathLike): Promise<void> { | ||
199 | await vscode.window.withProgress( | ||
200 | { | ||
201 | location: vscode.ProgressLocation.Notification, | ||
202 | title: "Patching rust-analyzer for NixOS" | ||
203 | }, | ||
204 | async (progress, _) => { | ||
205 | const expression = ` | ||
206 | {src, pkgs ? import <nixpkgs> {}}: | ||
207 | pkgs.stdenv.mkDerivation { | ||
208 | name = "rust-analyzer"; | ||
209 | inherit src; | ||
210 | phases = [ "installPhase" "fixupPhase" ]; | ||
211 | installPhase = "cp $src $out"; | ||
212 | fixupPhase = '' | ||
213 | chmod 755 $out | ||
214 | patchelf --set-interpreter "$(cat $NIX_CC/nix-support/dynamic-linker)" $out | ||
215 | ''; | ||
216 | } | ||
217 | `; | ||
218 | const origFile = dest + "-orig"; | ||
219 | await fs.rename(dest, origFile); | ||
220 | progress.report({ message: "Patching executable", increment: 20 }); | ||
221 | await new Promise((resolve, reject) => { | ||
222 | const handle = exec(`nix-build -E - --arg src '${origFile}' -o ${dest}`, | ||
223 | (err, stdout, stderr) => { | ||
224 | if (err != null) { | ||
225 | reject(Error(stderr)); | ||
226 | } else { | ||
227 | resolve(stdout); | ||
228 | } | ||
229 | }); | ||
230 | handle.stdin?.write(expression); | ||
231 | handle.stdin?.end(); | ||
232 | }); | ||
233 | await fs.unlink(origFile); | ||
234 | } | ||
235 | ); | ||
236 | } | ||
237 | |||
191 | async function getServer(config: Config, state: PersistentState): Promise<string | undefined> { | 238 | async function getServer(config: Config, state: PersistentState): Promise<string | undefined> { |
192 | const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath; | 239 | const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath; |
193 | if (explicitPath) { | 240 | if (explicitPath) { |
@@ -237,6 +284,12 @@ async function getServer(config: Config, state: PersistentState): Promise<string | |||
237 | assert(!!artifact, `Bad release: ${JSON.stringify(release)}`); | 284 | assert(!!artifact, `Bad release: ${JSON.stringify(release)}`); |
238 | 285 | ||
239 | await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 }); | 286 | await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 }); |
287 | |||
288 | // Patching executable if that's NixOS. | ||
289 | if (await fs.stat("/etc/nixos").then(_ => true).catch(_ => false)) { | ||
290 | await patchelf(dest); | ||
291 | } | ||
292 | |||
240 | await state.updateServerVersion(config.package.version); | 293 | await state.updateServerVersion(config.package.version); |
241 | return dest; | 294 | return dest; |
242 | } | 295 | } |
diff --git a/editors/code/src/commands/runnables.ts b/editors/code/src/run.ts index 0bd30fb07..5c790741f 100644 --- a/editors/code/src/commands/runnables.ts +++ b/editors/code/src/run.ts | |||
@@ -1,13 +1,14 @@ | |||
1 | import * as vscode from 'vscode'; | 1 | import * as vscode from 'vscode'; |
2 | import * as lc from 'vscode-languageclient'; | 2 | import * as lc from 'vscode-languageclient'; |
3 | import * as ra from '../rust-analyzer-api'; | 3 | import * as ra from './lsp_ext'; |
4 | import * as toolchain from "./toolchain"; | ||
4 | 5 | ||
5 | import { Ctx, Cmd } from '../ctx'; | 6 | import { Ctx } from './ctx'; |
6 | import { startDebugSession, getDebugConfiguration } from '../debug'; | 7 | import { makeDebugConfig } from './debug'; |
7 | 8 | ||
8 | const quickPickButtons = [{ iconPath: new vscode.ThemeIcon("save"), tooltip: "Save as a launch.json configurtation." }]; | 9 | const quickPickButtons = [{ iconPath: new vscode.ThemeIcon("save"), tooltip: "Save as a launch.json configurtation." }]; |
9 | 10 | ||
10 | async function selectRunnable(ctx: Ctx, prevRunnable?: RunnableQuickPick, debuggeeOnly = false, showButtons: boolean = true): Promise<RunnableQuickPick | undefined> { | 11 | export async function selectRunnable(ctx: Ctx, prevRunnable?: RunnableQuickPick, debuggeeOnly = false, showButtons: boolean = true): Promise<RunnableQuickPick | undefined> { |
11 | const editor = ctx.activeRustEditor; | 12 | const editor = ctx.activeRustEditor; |
12 | const client = ctx.client; | 13 | const client = ctx.client; |
13 | if (!editor || !client) return; | 14 | if (!editor || !client) return; |
@@ -64,7 +65,7 @@ async function selectRunnable(ctx: Ctx, prevRunnable?: RunnableQuickPick, debugg | |||
64 | quickPick.onDidHide(() => close()), | 65 | quickPick.onDidHide(() => close()), |
65 | quickPick.onDidAccept(() => close(quickPick.selectedItems[0])), | 66 | quickPick.onDidAccept(() => close(quickPick.selectedItems[0])), |
66 | quickPick.onDidTriggerButton((_button) => { | 67 | quickPick.onDidTriggerButton((_button) => { |
67 | (async () => await makeDebugConfig(ctx, quickPick.activeItems[0]))(); | 68 | (async () => await makeDebugConfig(ctx, quickPick.activeItems[0].runnable))(); |
68 | close(); | 69 | close(); |
69 | }), | 70 | }), |
70 | quickPick.onDidChangeActive((active) => { | 71 | quickPick.onDidChangeActive((active) => { |
@@ -83,89 +84,7 @@ async function selectRunnable(ctx: Ctx, prevRunnable?: RunnableQuickPick, debugg | |||
83 | }); | 84 | }); |
84 | } | 85 | } |
85 | 86 | ||
86 | export function run(ctx: Ctx): Cmd { | 87 | export class RunnableQuickPick implements vscode.QuickPickItem { |
87 | let prevRunnable: RunnableQuickPick | undefined; | ||
88 | |||
89 | return async () => { | ||
90 | const item = await selectRunnable(ctx, prevRunnable); | ||
91 | if (!item) return; | ||
92 | |||
93 | item.detail = 'rerun'; | ||
94 | prevRunnable = item; | ||
95 | const task = createTask(item.runnable); | ||
96 | return await vscode.tasks.executeTask(task); | ||
97 | }; | ||
98 | } | ||
99 | |||
100 | export function runSingle(ctx: Ctx): Cmd { | ||
101 | return async (runnable: ra.Runnable) => { | ||
102 | const editor = ctx.activeRustEditor; | ||
103 | if (!editor) return; | ||
104 | |||
105 | const task = createTask(runnable); | ||
106 | task.group = vscode.TaskGroup.Build; | ||
107 | task.presentationOptions = { | ||
108 | reveal: vscode.TaskRevealKind.Always, | ||
109 | panel: vscode.TaskPanelKind.Dedicated, | ||
110 | clear: true, | ||
111 | }; | ||
112 | |||
113 | return vscode.tasks.executeTask(task); | ||
114 | }; | ||
115 | } | ||
116 | |||
117 | export function debug(ctx: Ctx): Cmd { | ||
118 | let prevDebuggee: RunnableQuickPick | undefined; | ||
119 | |||
120 | return async () => { | ||
121 | const item = await selectRunnable(ctx, prevDebuggee, true); | ||
122 | if (!item) return; | ||
123 | |||
124 | item.detail = 'restart'; | ||
125 | prevDebuggee = item; | ||
126 | return await startDebugSession(ctx, item.runnable); | ||
127 | }; | ||
128 | } | ||
129 | |||
130 | export function debugSingle(ctx: Ctx): Cmd { | ||
131 | return async (config: ra.Runnable) => { | ||
132 | await startDebugSession(ctx, config); | ||
133 | }; | ||
134 | } | ||
135 | |||
136 | async function makeDebugConfig(ctx: Ctx, item: RunnableQuickPick): Promise<void> { | ||
137 | const scope = ctx.activeRustEditor?.document.uri; | ||
138 | if (!scope) return; | ||
139 | |||
140 | const debugConfig = await getDebugConfiguration(ctx, item.runnable); | ||
141 | if (!debugConfig) return; | ||
142 | |||
143 | const wsLaunchSection = vscode.workspace.getConfiguration("launch", scope); | ||
144 | const configurations = wsLaunchSection.get<any[]>("configurations") || []; | ||
145 | |||
146 | const index = configurations.findIndex(c => c.name === debugConfig.name); | ||
147 | if (index !== -1) { | ||
148 | const answer = await vscode.window.showErrorMessage(`Launch configuration '${debugConfig.name}' already exists!`, 'Cancel', 'Update'); | ||
149 | if (answer === "Cancel") return; | ||
150 | |||
151 | configurations[index] = debugConfig; | ||
152 | } else { | ||
153 | configurations.push(debugConfig); | ||
154 | } | ||
155 | |||
156 | await wsLaunchSection.update("configurations", configurations); | ||
157 | } | ||
158 | |||
159 | export function newDebugConfig(ctx: Ctx): Cmd { | ||
160 | return async () => { | ||
161 | const item = await selectRunnable(ctx, undefined, true, false); | ||
162 | if (!item) return; | ||
163 | |||
164 | await makeDebugConfig(ctx, item); | ||
165 | }; | ||
166 | } | ||
167 | |||
168 | class RunnableQuickPick implements vscode.QuickPickItem { | ||
169 | public label: string; | 88 | public label: string; |
170 | public description?: string | undefined; | 89 | public description?: string | undefined; |
171 | public detail?: string | undefined; | 90 | public detail?: string | undefined; |
@@ -184,18 +103,27 @@ interface CargoTaskDefinition extends vscode.TaskDefinition { | |||
184 | env?: { [key: string]: string }; | 103 | env?: { [key: string]: string }; |
185 | } | 104 | } |
186 | 105 | ||
187 | function createTask(spec: ra.Runnable): vscode.Task { | 106 | export function createTask(runnable: ra.Runnable): vscode.Task { |
188 | const TASK_SOURCE = 'Rust'; | 107 | const TASK_SOURCE = 'Rust'; |
108 | |||
109 | let command; | ||
110 | switch (runnable.kind) { | ||
111 | case "cargo": command = toolchain.getPathForExecutable("cargo"); | ||
112 | } | ||
113 | const args = runnable.args.cargoArgs; | ||
114 | if (runnable.args.executableArgs.length > 0) { | ||
115 | args.push('--', ...runnable.args.executableArgs); | ||
116 | } | ||
189 | const definition: CargoTaskDefinition = { | 117 | const definition: CargoTaskDefinition = { |
190 | type: 'cargo', | 118 | type: 'cargo', |
191 | label: spec.label, | 119 | label: runnable.label, |
192 | command: spec.bin, | 120 | command, |
193 | args: spec.extraArgs ? [...spec.args, '--', ...spec.extraArgs] : spec.args, | 121 | args, |
194 | env: spec.env, | 122 | env: Object.assign({}, process.env as { [key: string]: string }, { "RUST_BACKTRACE": "short" }), |
195 | }; | 123 | }; |
196 | 124 | ||
197 | const execOption: vscode.ShellExecutionOptions = { | 125 | const execOption: vscode.ShellExecutionOptions = { |
198 | cwd: spec.cwd || '.', | 126 | cwd: runnable.args.workspaceRoot || '.', |
199 | env: definition.env, | 127 | env: definition.env, |
200 | }; | 128 | }; |
201 | const exec = new vscode.ShellExecution( | 129 | const exec = new vscode.ShellExecution( |
diff --git a/editors/code/src/rust-analyzer-api.ts b/editors/code/src/rust-analyzer-api.ts deleted file mode 100644 index 73f36432f..000000000 --- a/editors/code/src/rust-analyzer-api.ts +++ /dev/null | |||
@@ -1,125 +0,0 @@ | |||
1 | /** | ||
2 | * This file mirrors `crates/rust-analyzer/src/req.rs` declarations. | ||
3 | */ | ||
4 | |||
5 | import * as lc from "vscode-languageclient"; | ||
6 | |||
7 | type Option<T> = null | T; | ||
8 | type Vec<T> = T[]; | ||
9 | type FxHashMap<K extends PropertyKey, V> = Record<K, V>; | ||
10 | |||
11 | function request<TParams, TResult>(method: string) { | ||
12 | return new lc.RequestType<TParams, TResult, unknown>(`rust-analyzer/${method}`); | ||
13 | } | ||
14 | function notification<TParam>(method: string) { | ||
15 | return new lc.NotificationType<TParam>(method); | ||
16 | } | ||
17 | |||
18 | |||
19 | export const analyzerStatus = request<null, string>("analyzerStatus"); | ||
20 | |||
21 | |||
22 | export const collectGarbage = request<null, null>("collectGarbage"); | ||
23 | |||
24 | |||
25 | export interface SyntaxTreeParams { | ||
26 | textDocument: lc.TextDocumentIdentifier; | ||
27 | range: Option<lc.Range>; | ||
28 | } | ||
29 | export const syntaxTree = request<SyntaxTreeParams, string>("syntaxTree"); | ||
30 | |||
31 | |||
32 | export interface ExpandMacroParams { | ||
33 | textDocument: lc.TextDocumentIdentifier; | ||
34 | position: Option<lc.Position>; | ||
35 | } | ||
36 | export interface ExpandedMacro { | ||
37 | name: string; | ||
38 | expansion: string; | ||
39 | } | ||
40 | export const expandMacro = request<ExpandMacroParams, Option<ExpandedMacro>>("expandMacro"); | ||
41 | |||
42 | |||
43 | export interface FindMatchingBraceParams { | ||
44 | textDocument: lc.TextDocumentIdentifier; | ||
45 | offsets: Vec<lc.Position>; | ||
46 | } | ||
47 | export const findMatchingBrace = request<FindMatchingBraceParams, Vec<lc.Position>>("findMatchingBrace"); | ||
48 | |||
49 | |||
50 | export interface PublishDecorationsParams { | ||
51 | uri: string; | ||
52 | decorations: Vec<Decoration>; | ||
53 | } | ||
54 | export interface Decoration { | ||
55 | range: lc.Range; | ||
56 | tag: string; | ||
57 | bindingHash: Option<string>; | ||
58 | } | ||
59 | export const decorationsRequest = request<lc.TextDocumentIdentifier, Vec<Decoration>>("decorationsRequest"); | ||
60 | |||
61 | |||
62 | export const parentModule = request<lc.TextDocumentPositionParams, Vec<lc.Location>>("parentModule"); | ||
63 | |||
64 | |||
65 | export interface JoinLinesParams { | ||
66 | textDocument: lc.TextDocumentIdentifier; | ||
67 | ranges: lc.Range[]; | ||
68 | } | ||
69 | export const joinLines = new lc.RequestType<JoinLinesParams, lc.TextEdit[], unknown>('experimental/joinLines'); | ||
70 | |||
71 | |||
72 | export const onEnter = request<lc.TextDocumentPositionParams, Option<lc.WorkspaceEdit>>("onEnter"); | ||
73 | |||
74 | export interface RunnablesParams { | ||
75 | textDocument: lc.TextDocumentIdentifier; | ||
76 | position: Option<lc.Position>; | ||
77 | } | ||
78 | export interface Runnable { | ||
79 | range: lc.Range; | ||
80 | label: string; | ||
81 | bin: string; | ||
82 | args: Vec<string>; | ||
83 | extraArgs: Vec<string>; | ||
84 | env: FxHashMap<string, string>; | ||
85 | cwd: Option<string>; | ||
86 | } | ||
87 | export const runnables = request<RunnablesParams, Vec<Runnable>>("runnables"); | ||
88 | |||
89 | export type InlayHint = InlayHint.TypeHint | InlayHint.ParamHint | InlayHint.ChainingHint; | ||
90 | |||
91 | export namespace InlayHint { | ||
92 | export const enum Kind { | ||
93 | TypeHint = "TypeHint", | ||
94 | ParamHint = "ParameterHint", | ||
95 | ChainingHint = "ChainingHint", | ||
96 | } | ||
97 | interface Common { | ||
98 | range: lc.Range; | ||
99 | label: string; | ||
100 | } | ||
101 | export type TypeHint = Common & { kind: Kind.TypeHint }; | ||
102 | export type ParamHint = Common & { kind: Kind.ParamHint }; | ||
103 | export type ChainingHint = Common & { kind: Kind.ChainingHint }; | ||
104 | } | ||
105 | export interface InlayHintsParams { | ||
106 | textDocument: lc.TextDocumentIdentifier; | ||
107 | } | ||
108 | export const inlayHints = request<InlayHintsParams, Vec<InlayHint>>("inlayHints"); | ||
109 | |||
110 | |||
111 | export interface SsrParams { | ||
112 | query: string; | ||
113 | parseOnly: boolean; | ||
114 | } | ||
115 | export const ssr = new lc.RequestType<SsrParams, lc.WorkspaceEdit, unknown>('experimental/ssr'); | ||
116 | |||
117 | |||
118 | export const publishDecorations = notification<PublishDecorationsParams>("publishDecorations"); | ||
119 | |||
120 | |||
121 | export interface SourceChange { | ||
122 | label: string; | ||
123 | workspaceEdit: lc.WorkspaceEdit; | ||
124 | cursorPosition: Option<lc.TextDocumentPositionParams>; | ||
125 | } | ||
diff --git a/editors/code/src/commands/index.ts b/editors/code/src/snippets.ts index abb53a248..bcb3f2cc7 100644 --- a/editors/code/src/commands/index.ts +++ b/editors/code/src/snippets.ts | |||
@@ -1,59 +1,6 @@ | |||
1 | import * as vscode from 'vscode'; | 1 | import * as vscode from 'vscode'; |
2 | import * as lc from 'vscode-languageclient'; | ||
3 | import * as ra from '../rust-analyzer-api'; | ||
4 | 2 | ||
5 | import { Ctx, Cmd } from '../ctx'; | 3 | import { assert } from './util'; |
6 | import * as sourceChange from '../source_change'; | ||
7 | import { assert } from '../util'; | ||
8 | |||
9 | export * from './analyzer_status'; | ||
10 | export * from './matching_brace'; | ||
11 | export * from './join_lines'; | ||
12 | export * from './on_enter'; | ||
13 | export * from './parent_module'; | ||
14 | export * from './syntax_tree'; | ||
15 | export * from './expand_macro'; | ||
16 | export * from './runnables'; | ||
17 | export * from './ssr'; | ||
18 | export * from './server_version'; | ||
19 | |||
20 | export function collectGarbage(ctx: Ctx): Cmd { | ||
21 | return async () => ctx.client.sendRequest(ra.collectGarbage, null); | ||
22 | } | ||
23 | |||
24 | export function showReferences(ctx: Ctx): Cmd { | ||
25 | return (uri: string, position: lc.Position, locations: lc.Location[]) => { | ||
26 | const client = ctx.client; | ||
27 | if (client) { | ||
28 | vscode.commands.executeCommand( | ||
29 | 'editor.action.showReferences', | ||
30 | vscode.Uri.parse(uri), | ||
31 | client.protocol2CodeConverter.asPosition(position), | ||
32 | locations.map(client.protocol2CodeConverter.asLocation), | ||
33 | ); | ||
34 | } | ||
35 | }; | ||
36 | } | ||
37 | |||
38 | export function applySourceChange(ctx: Ctx): Cmd { | ||
39 | return async (change: ra.SourceChange) => { | ||
40 | await sourceChange.applySourceChange(ctx, change); | ||
41 | }; | ||
42 | } | ||
43 | |||
44 | export function applyActionGroup(_ctx: Ctx): Cmd { | ||
45 | return async (actions: { label: string; edit: vscode.WorkspaceEdit }[]) => { | ||
46 | const selectedAction = await vscode.window.showQuickPick(actions); | ||
47 | if (!selectedAction) return; | ||
48 | await applySnippetWorkspaceEdit(selectedAction.edit); | ||
49 | }; | ||
50 | } | ||
51 | |||
52 | export function applySnippetWorkspaceEditCommand(_ctx: Ctx): Cmd { | ||
53 | return async (edit: vscode.WorkspaceEdit) => { | ||
54 | await applySnippetWorkspaceEdit(edit); | ||
55 | }; | ||
56 | } | ||
57 | 4 | ||
58 | export async function applySnippetWorkspaceEdit(edit: vscode.WorkspaceEdit) { | 5 | export async function applySnippetWorkspaceEdit(edit: vscode.WorkspaceEdit) { |
59 | assert(edit.entries().length === 1, `bad ws edit: ${JSON.stringify(edit)}`); | 6 | assert(edit.entries().length === 1, `bad ws edit: ${JSON.stringify(edit)}`); |
@@ -61,7 +8,10 @@ export async function applySnippetWorkspaceEdit(edit: vscode.WorkspaceEdit) { | |||
61 | 8 | ||
62 | const editor = vscode.window.visibleTextEditors.find((it) => it.document.uri.toString() === uri.toString()); | 9 | const editor = vscode.window.visibleTextEditors.find((it) => it.document.uri.toString() === uri.toString()); |
63 | if (!editor) return; | 10 | if (!editor) return; |
11 | await applySnippetTextEdits(editor, edits); | ||
12 | } | ||
64 | 13 | ||
14 | export async function applySnippetTextEdits(editor: vscode.TextEditor, edits: vscode.TextEdit[]) { | ||
65 | let selection: vscode.Selection | undefined = undefined; | 15 | let selection: vscode.Selection | undefined = undefined; |
66 | let lineDelta = 0; | 16 | let lineDelta = 0; |
67 | await editor.edit((builder) => { | 17 | await editor.edit((builder) => { |
diff --git a/editors/code/src/source_change.ts b/editors/code/src/source_change.ts deleted file mode 100644 index af8f1df51..000000000 --- a/editors/code/src/source_change.ts +++ /dev/null | |||
@@ -1,54 +0,0 @@ | |||
1 | import * as vscode from 'vscode'; | ||
2 | import * as lc from 'vscode-languageclient'; | ||
3 | import * as ra from './rust-analyzer-api'; | ||
4 | |||
5 | import { Ctx } from './ctx'; | ||
6 | |||
7 | export async function applySourceChange(ctx: Ctx, change: ra.SourceChange) { | ||
8 | const client = ctx.client; | ||
9 | if (!client) return; | ||
10 | |||
11 | const wsEdit = client.protocol2CodeConverter.asWorkspaceEdit( | ||
12 | change.workspaceEdit, | ||
13 | ); | ||
14 | let created; | ||
15 | let moved; | ||
16 | if (change.workspaceEdit.documentChanges) { | ||
17 | for (const docChange of change.workspaceEdit.documentChanges) { | ||
18 | if (lc.CreateFile.is(docChange)) { | ||
19 | created = docChange.uri; | ||
20 | } else if (lc.RenameFile.is(docChange)) { | ||
21 | moved = docChange.newUri; | ||
22 | } | ||
23 | } | ||
24 | } | ||
25 | const toOpen = created || moved; | ||
26 | const toReveal = change.cursorPosition; | ||
27 | await vscode.workspace.applyEdit(wsEdit); | ||
28 | if (toOpen) { | ||
29 | const toOpenUri = vscode.Uri.parse(toOpen); | ||
30 | const doc = await vscode.workspace.openTextDocument(toOpenUri); | ||
31 | await vscode.window.showTextDocument(doc); | ||
32 | } else if (toReveal) { | ||
33 | const uri = client.protocol2CodeConverter.asUri( | ||
34 | toReveal.textDocument.uri, | ||
35 | ); | ||
36 | const position = client.protocol2CodeConverter.asPosition( | ||
37 | toReveal.position, | ||
38 | ); | ||
39 | const editor = vscode.window.activeTextEditor; | ||
40 | if (!editor || !editor.selection.isEmpty) { | ||
41 | return; | ||
42 | } | ||
43 | |||
44 | if (editor.document.uri !== uri) { | ||
45 | const doc = await vscode.workspace.openTextDocument(uri); | ||
46 | await vscode.window.showTextDocument(doc); | ||
47 | } | ||
48 | editor.selection = new vscode.Selection(position, position); | ||
49 | editor.revealRange( | ||
50 | new vscode.Range(position, position), | ||
51 | vscode.TextEditorRevealType.Default, | ||
52 | ); | ||
53 | } | ||
54 | } | ||
diff --git a/editors/code/src/tasks.ts b/editors/code/src/tasks.ts index 1366c76d6..9748824df 100644 --- a/editors/code/src/tasks.ts +++ b/editors/code/src/tasks.ts | |||
@@ -1,4 +1,5 @@ | |||
1 | import * as vscode from 'vscode'; | 1 | import * as vscode from 'vscode'; |
2 | import * as toolchain from "./toolchain"; | ||
2 | 3 | ||
3 | // This ends up as the `type` key in tasks.json. RLS also uses `cargo` and | 4 | // This ends up as the `type` key in tasks.json. RLS also uses `cargo` and |
4 | // our configuration should be compatible with it so use the same key. | 5 | // our configuration should be compatible with it so use the same key. |
@@ -24,6 +25,8 @@ class CargoTaskProvider implements vscode.TaskProvider { | |||
24 | // set of tasks that always exist. These tasks cannot be removed in | 25 | // set of tasks that always exist. These tasks cannot be removed in |
25 | // tasks.json - only tweaked. | 26 | // tasks.json - only tweaked. |
26 | 27 | ||
28 | const cargoPath = toolchain.cargoPath(); | ||
29 | |||
27 | return [ | 30 | return [ |
28 | { command: 'build', group: vscode.TaskGroup.Build }, | 31 | { command: 'build', group: vscode.TaskGroup.Build }, |
29 | { command: 'check', group: vscode.TaskGroup.Build }, | 32 | { command: 'check', group: vscode.TaskGroup.Build }, |
@@ -46,7 +49,7 @@ class CargoTaskProvider implements vscode.TaskProvider { | |||
46 | `cargo ${command}`, | 49 | `cargo ${command}`, |
47 | 'rust', | 50 | 'rust', |
48 | // What to do when this command is executed. | 51 | // What to do when this command is executed. |
49 | new vscode.ShellExecution('cargo', [command]), | 52 | new vscode.ShellExecution(cargoPath, [command]), |
50 | // Problem matchers. | 53 | // Problem matchers. |
51 | ['$rustc'], | 54 | ['$rustc'], |
52 | ); | 55 | ); |
@@ -80,4 +83,4 @@ class CargoTaskProvider implements vscode.TaskProvider { | |||
80 | export function activateTaskProvider(target: vscode.WorkspaceFolder): vscode.Disposable { | 83 | export function activateTaskProvider(target: vscode.WorkspaceFolder): vscode.Disposable { |
81 | const provider = new CargoTaskProvider(target); | 84 | const provider = new CargoTaskProvider(target); |
82 | return vscode.tasks.registerTaskProvider(TASK_TYPE, provider); | 85 | return vscode.tasks.registerTaskProvider(TASK_TYPE, provider); |
83 | } \ No newline at end of file | 86 | } |
diff --git a/editors/code/src/cargo.ts b/editors/code/src/toolchain.ts index 6a41873d0..80a7915e9 100644 --- a/editors/code/src/cargo.ts +++ b/editors/code/src/toolchain.ts | |||
@@ -1,9 +1,10 @@ | |||
1 | import * as cp from 'child_process'; | 1 | import * as cp from 'child_process'; |
2 | import * as os from 'os'; | 2 | import * as os from 'os'; |
3 | import * as path from 'path'; | 3 | import * as path from 'path'; |
4 | import * as fs from 'fs'; | ||
4 | import * as readline from 'readline'; | 5 | import * as readline from 'readline'; |
5 | import { OutputChannel } from 'vscode'; | 6 | import { OutputChannel } from 'vscode'; |
6 | import { isValidExecutable } from './util'; | 7 | import { log, memoize } from './util'; |
7 | 8 | ||
8 | interface CompilationArtifact { | 9 | interface CompilationArtifact { |
9 | fileName: string; | 10 | fileName: string; |
@@ -12,14 +13,45 @@ interface CompilationArtifact { | |||
12 | isTest: boolean; | 13 | isTest: boolean; |
13 | } | 14 | } |
14 | 15 | ||
16 | export interface ArtifactSpec { | ||
17 | cargoArgs: string[]; | ||
18 | filter?: (artifacts: CompilationArtifact[]) => CompilationArtifact[]; | ||
19 | } | ||
20 | |||
15 | export class Cargo { | 21 | export class Cargo { |
16 | constructor(readonly rootFolder: string, readonly output: OutputChannel) { } | 22 | constructor(readonly rootFolder: string, readonly output: OutputChannel) { } |
17 | 23 | ||
18 | private async artifactsFromArgs(cargoArgs: string[]): Promise<CompilationArtifact[]> { | 24 | // Made public for testing purposes |
25 | static artifactSpec(args: readonly string[]): ArtifactSpec { | ||
26 | const cargoArgs = [...args, "--message-format=json"]; | ||
27 | |||
28 | // arguments for a runnable from the quick pick should be updated. | ||
29 | // see crates\rust-analyzer\src\main_loop\handlers.rs, handle_code_lens | ||
30 | switch (cargoArgs[0]) { | ||
31 | case "run": cargoArgs[0] = "build"; break; | ||
32 | case "test": { | ||
33 | if (!cargoArgs.includes("--no-run")) { | ||
34 | cargoArgs.push("--no-run"); | ||
35 | } | ||
36 | break; | ||
37 | } | ||
38 | } | ||
39 | |||
40 | const result: ArtifactSpec = { cargoArgs: cargoArgs }; | ||
41 | if (cargoArgs[0] === "test") { | ||
42 | // for instance, `crates\rust-analyzer\tests\heavy_tests\main.rs` tests | ||
43 | // produce 2 artifacts: {"kind": "bin"} and {"kind": "test"} | ||
44 | result.filter = (artifacts) => artifacts.filter(it => it.isTest); | ||
45 | } | ||
46 | |||
47 | return result; | ||
48 | } | ||
49 | |||
50 | private async getArtifacts(spec: ArtifactSpec): Promise<CompilationArtifact[]> { | ||
19 | const artifacts: CompilationArtifact[] = []; | 51 | const artifacts: CompilationArtifact[] = []; |
20 | 52 | ||
21 | try { | 53 | try { |
22 | await this.runCargo(cargoArgs, | 54 | await this.runCargo(spec.cargoArgs, |
23 | message => { | 55 | message => { |
24 | if (message.reason === 'compiler-artifact' && message.executable) { | 56 | if (message.reason === 'compiler-artifact' && message.executable) { |
25 | const isBinary = message.target.crate_types.includes('bin'); | 57 | const isBinary = message.target.crate_types.includes('bin'); |
@@ -43,30 +75,11 @@ export class Cargo { | |||
43 | throw new Error(`Cargo invocation has failed: ${err}`); | 75 | throw new Error(`Cargo invocation has failed: ${err}`); |
44 | } | 76 | } |
45 | 77 | ||
46 | return artifacts; | 78 | return spec.filter?.(artifacts) ?? artifacts; |
47 | } | 79 | } |
48 | 80 | ||
49 | async executableFromArgs(args: readonly string[]): Promise<string> { | 81 | async executableFromArgs(args: readonly string[]): Promise<string> { |
50 | const cargoArgs = [...args, "--message-format=json"]; | 82 | const artifacts = await this.getArtifacts(Cargo.artifactSpec(args)); |
51 | |||
52 | // arguments for a runnable from the quick pick should be updated. | ||
53 | // see crates\rust-analyzer\src\main_loop\handlers.rs, handle_code_lens | ||
54 | switch (cargoArgs[0]) { | ||
55 | case "run": cargoArgs[0] = "build"; break; | ||
56 | case "test": { | ||
57 | if (cargoArgs.indexOf("--no-run") === -1) { | ||
58 | cargoArgs.push("--no-run"); | ||
59 | } | ||
60 | break; | ||
61 | } | ||
62 | } | ||
63 | |||
64 | let artifacts = await this.artifactsFromArgs(cargoArgs); | ||
65 | if (cargoArgs[0] === "test") { | ||
66 | // for instance, `crates\rust-analyzer\tests\heavy_tests\main.rs` tests | ||
67 | // produce 2 artifacts: {"kind": "bin"} and {"kind": "test"} | ||
68 | artifacts = artifacts.filter(a => a.isTest); | ||
69 | } | ||
70 | 83 | ||
71 | if (artifacts.length === 0) { | 84 | if (artifacts.length === 0) { |
72 | throw new Error('No compilation artifacts'); | 85 | throw new Error('No compilation artifacts'); |
@@ -83,14 +96,7 @@ export class Cargo { | |||
83 | onStderrString: (data: string) => void | 96 | onStderrString: (data: string) => void |
84 | ): Promise<number> { | 97 | ): Promise<number> { |
85 | return new Promise((resolve, reject) => { | 98 | return new Promise((resolve, reject) => { |
86 | let cargoPath; | 99 | const cargo = cp.spawn(cargoPath(), cargoArgs, { |
87 | try { | ||
88 | cargoPath = getCargoPathOrFail(); | ||
89 | } catch (err) { | ||
90 | return reject(err); | ||
91 | } | ||
92 | |||
93 | const cargo = cp.spawn(cargoPath, cargoArgs, { | ||
94 | stdio: ['ignore', 'pipe', 'pipe'], | 100 | stdio: ['ignore', 'pipe', 'pipe'], |
95 | cwd: this.rootFolder | 101 | cwd: this.rootFolder |
96 | }); | 102 | }); |
@@ -115,26 +121,54 @@ export class Cargo { | |||
115 | } | 121 | } |
116 | } | 122 | } |
117 | 123 | ||
118 | // Mirrors `ra_env::get_path_for_executable` implementation | 124 | /** Mirrors `ra_toolchain::cargo()` implementation */ |
119 | function getCargoPathOrFail(): string { | 125 | export function cargoPath(): string { |
120 | const envVar = process.env.CARGO; | 126 | return getPathForExecutable("cargo"); |
121 | const executableName = "cargo"; | 127 | } |
128 | |||
129 | /** Mirrors `ra_toolchain::get_path_for_executable()` implementation */ | ||
130 | export const getPathForExecutable = memoize( | ||
131 | // We apply caching to decrease file-system interactions | ||
132 | (executableName: "cargo" | "rustc" | "rustup"): string => { | ||
133 | { | ||
134 | const envVar = process.env[executableName.toUpperCase()]; | ||
135 | if (envVar) return envVar; | ||
136 | } | ||
137 | |||
138 | if (lookupInPath(executableName)) return executableName; | ||
122 | 139 | ||
123 | if (envVar) { | 140 | try { |
124 | if (isValidExecutable(envVar)) return envVar; | 141 | // hmm, `os.homedir()` seems to be infallible |
142 | // it is not mentioned in docs and cannot be infered by the type signature... | ||
143 | const standardPath = path.join(os.homedir(), ".cargo", "bin", executableName); | ||
125 | 144 | ||
126 | throw new Error(`\`${envVar}\` environment variable points to something that's not a valid executable`); | 145 | if (isFile(standardPath)) return standardPath; |
146 | } catch (err) { | ||
147 | log.error("Failed to read the fs info", err); | ||
148 | } | ||
149 | return executableName; | ||
127 | } | 150 | } |
151 | ); | ||
128 | 152 | ||
129 | if (isValidExecutable(executableName)) return executableName; | 153 | function lookupInPath(exec: string): boolean { |
154 | const paths = process.env.PATH ?? "";; | ||
130 | 155 | ||
131 | const standardLocation = path.join(os.homedir(), '.cargo', 'bin', executableName); | 156 | const candidates = paths.split(path.delimiter).flatMap(dirInPath => { |
157 | const candidate = path.join(dirInPath, exec); | ||
158 | return os.type() === "Windows_NT" | ||
159 | ? [candidate, `${candidate}.exe`] | ||
160 | : [candidate]; | ||
161 | }); | ||
132 | 162 | ||
133 | if (isValidExecutable(standardLocation)) return standardLocation; | 163 | return candidates.some(isFile); |
164 | } | ||
134 | 165 | ||
135 | throw new Error( | 166 | function isFile(suspectPath: string): boolean { |
136 | `Failed to find \`${executableName}\` executable. ` + | 167 | // It is not mentionned in docs, but `statSync()` throws an error when |
137 | `Make sure \`${executableName}\` is in \`$PATH\`, ` + | 168 | // the path doesn't exist |
138 | `or set \`${envVar}\` to point to a valid executable.` | 169 | try { |
139 | ); | 170 | return fs.statSync(suspectPath).isFile(); |
171 | } catch { | ||
172 | return false; | ||
173 | } | ||
140 | } | 174 | } |
diff --git a/editors/code/src/util.ts b/editors/code/src/util.ts index 127a9e911..fe3fb71cd 100644 --- a/editors/code/src/util.ts +++ b/editors/code/src/util.ts | |||
@@ -74,10 +74,11 @@ export type RustDocument = vscode.TextDocument & { languageId: "rust" }; | |||
74 | export type RustEditor = vscode.TextEditor & { document: RustDocument }; | 74 | export type RustEditor = vscode.TextEditor & { document: RustDocument }; |
75 | 75 | ||
76 | export function isRustDocument(document: vscode.TextDocument): document is RustDocument { | 76 | export function isRustDocument(document: vscode.TextDocument): document is RustDocument { |
77 | return document.languageId === 'rust' | 77 | // Prevent corrupted text (particularly via inlay hints) in diff views |
78 | // SCM diff views have the same URI as the on-disk document but not the same content | 78 | // by allowing only `file` schemes |
79 | && document.uri.scheme !== 'git' | 79 | // unfortunately extensions that use diff views not always set this |
80 | && document.uri.scheme !== 'svn'; | 80 | // to something different than 'file' (see ongoing bug: #4608) |
81 | return document.languageId === 'rust' && document.uri.scheme === 'file'; | ||
81 | } | 82 | } |
82 | 83 | ||
83 | export function isRustEditor(editor: vscode.TextEditor): editor is RustEditor { | 84 | export function isRustEditor(editor: vscode.TextEditor): editor is RustEditor { |
@@ -93,3 +94,26 @@ export function isValidExecutable(path: string): boolean { | |||
93 | 94 | ||
94 | return res.status === 0; | 95 | return res.status === 0; |
95 | } | 96 | } |
97 | |||
98 | /** Sets ['when'](https://code.visualstudio.com/docs/getstarted/keybindings#_when-clause-contexts) clause contexts */ | ||
99 | export function setContextValue(key: string, value: any): Thenable<void> { | ||
100 | return vscode.commands.executeCommand('setContext', key, value); | ||
101 | } | ||
102 | |||
103 | /** | ||
104 | * Returns a higher-order function that caches the results of invoking the | ||
105 | * underlying function. | ||
106 | */ | ||
107 | export function memoize<Ret, TThis, Param extends string>(func: (this: TThis, arg: Param) => Ret) { | ||
108 | const cache = new Map<string, Ret>(); | ||
109 | |||
110 | return function(this: TThis, arg: Param) { | ||
111 | const cached = cache.get(arg); | ||
112 | if (cached) return cached; | ||
113 | |||
114 | const result = func.call(this, arg); | ||
115 | cache.set(arg, result); | ||
116 | |||
117 | return result; | ||
118 | }; | ||
119 | } | ||