aboutsummaryrefslogtreecommitdiff
path: root/editors/code
diff options
context:
space:
mode:
authorBenjamin Coenen <[email protected]>2020-05-10 11:31:55 +0100
committerBenjamin Coenen <[email protected]>2020-05-10 11:31:55 +0100
commite80903a96564c2239489a8c630a4748bf21a3659 (patch)
tree12b31a1fd12deb2120065cea5a558425c8c1984f /editors/code
parent6203e9c4faee288f16d93dbb7dd0f1f8df487d83 (diff)
parent4578154b608fa075595103d0c933da60d55b25c8 (diff)
Merge branch 'master' of github.com:rust-analyzer/rust-analyzer into feat_4348
Diffstat (limited to 'editors/code')
-rw-r--r--editors/code/package.json18
-rw-r--r--editors/code/src/cargo.ts81
-rw-r--r--editors/code/src/commands/runnables.ts71
-rw-r--r--editors/code/src/config.ts9
-rw-r--r--editors/code/src/inlay_hints.ts14
-rw-r--r--editors/code/src/main.ts8
-rw-r--r--editors/code/src/util.ts11
7 files changed, 138 insertions, 74 deletions
diff --git a/editors/code/package.json b/editors/code/package.json
index 12a08ba40..c6fc13519 100644
--- a/editors/code/package.json
+++ b/editors/code/package.json
@@ -300,6 +300,11 @@
300 "default": true, 300 "default": true,
301 "markdownDescription": "Check with all features (will be passed as `--all-features`)" 301 "markdownDescription": "Check with all features (will be passed as `--all-features`)"
302 }, 302 },
303 "rust-analyzer.inlayHints.enable": {
304 "type": "boolean",
305 "default": true,
306 "description": "Disable all inlay hints"
307 },
303 "rust-analyzer.inlayHints.typeHints": { 308 "rust-analyzer.inlayHints.typeHints": {
304 "type": "boolean", 309 "type": "boolean",
305 "default": true, 310 "default": true,
@@ -418,6 +423,16 @@
418 "default": { 423 "default": {
419 "/rustc/<id>": "${env:USERPROFILE}/.rustup/toolchains/<toolchain-id>/lib/rustlib/src/rust" 424 "/rustc/<id>": "${env:USERPROFILE}/.rustup/toolchains/<toolchain-id>/lib/rustlib/src/rust"
420 } 425 }
426 },
427 "rust-analyzer.debug.openDebugPane": {
428 "description": "Whether to open up the Debug Pane on debugging start.",
429 "type": "boolean",
430 "default": false
431 },
432 "rust-analyzer.debug.engineSettings": {
433 "type": "object",
434 "default": {},
435 "description": "Optional settings passed to the debug engine. Example:\n{ \"lldb\": { \"terminal\":\"external\"} }"
421 } 436 }
422 } 437 }
423 }, 438 },
@@ -589,6 +604,9 @@
589 "union": [ 604 "union": [
590 "entity.name.union" 605 "entity.name.union"
591 ], 606 ],
607 "struct": [
608 "entity.name.type.struct"
609 ],
592 "keyword.unsafe": [ 610 "keyword.unsafe": [
593 "keyword.other.unsafe" 611 "keyword.other.unsafe"
594 ], 612 ],
diff --git a/editors/code/src/cargo.ts b/editors/code/src/cargo.ts
index a328ba9bd..2a2c2e0e1 100644
--- a/editors/code/src/cargo.ts
+++ b/editors/code/src/cargo.ts
@@ -1,6 +1,9 @@
1import * as cp from 'child_process'; 1import * as cp from 'child_process';
2import * as os from 'os';
3import * as path from 'path';
2import * as readline from 'readline'; 4import * as readline from 'readline';
3import { OutputChannel } from 'vscode'; 5import { OutputChannel } from 'vscode';
6import { isValidExecutable } from './util';
4 7
5interface CompilationArtifact { 8interface CompilationArtifact {
6 fileName: string; 9 fileName: string;
@@ -10,17 +13,9 @@ interface CompilationArtifact {
10} 13}
11 14
12export class Cargo { 15export class Cargo {
13 rootFolder: string; 16 constructor(readonly rootFolder: string, readonly output: OutputChannel) { }
14 env?: Record<string, string>;
15 output: OutputChannel;
16
17 public constructor(cargoTomlFolder: string, output: OutputChannel, env: Record<string, string> | undefined = undefined) {
18 this.rootFolder = cargoTomlFolder;
19 this.output = output;
20 this.env = env;
21 }
22 17
23 public async artifactsFromArgs(cargoArgs: string[]): Promise<CompilationArtifact[]> { 18 private async artifactsFromArgs(cargoArgs: string[]): Promise<CompilationArtifact[]> {
24 const artifacts: CompilationArtifact[] = []; 19 const artifacts: CompilationArtifact[] = [];
25 20
26 try { 21 try {
@@ -37,17 +32,13 @@ export class Cargo {
37 isTest: message.profile.test 32 isTest: message.profile.test
38 }); 33 });
39 } 34 }
40 } 35 } else if (message.reason === 'compiler-message') {
41 else if (message.reason === 'compiler-message') {
42 this.output.append(message.message.rendered); 36 this.output.append(message.message.rendered);
43 } 37 }
44 }, 38 },
45 stderr => { 39 stderr => this.output.append(stderr),
46 this.output.append(stderr);
47 }
48 ); 40 );
49 } 41 } catch (err) {
50 catch (err) {
51 this.output.show(true); 42 this.output.show(true);
52 throw new Error(`Cargo invocation has failed: ${err}`); 43 throw new Error(`Cargo invocation has failed: ${err}`);
53 } 44 }
@@ -55,9 +46,8 @@ export class Cargo {
55 return artifacts; 46 return artifacts;
56 } 47 }
57 48
58 public async executableFromArgs(args: string[]): Promise<string> { 49 async executableFromArgs(args: readonly string[]): Promise<string> {
59 const cargoArgs = [...args]; // to remain args unchanged 50 const cargoArgs = [...args, "--message-format=json"];
60 cargoArgs.push("--message-format=json");
61 51
62 const artifacts = await this.artifactsFromArgs(cargoArgs); 52 const artifacts = await this.artifactsFromArgs(cargoArgs);
63 53
@@ -70,24 +60,27 @@ export class Cargo {
70 return artifacts[0].fileName; 60 return artifacts[0].fileName;
71 } 61 }
72 62
73 runCargo( 63 private runCargo(
74 cargoArgs: string[], 64 cargoArgs: string[],
75 onStdoutJson: (obj: any) => void, 65 onStdoutJson: (obj: any) => void,
76 onStderrString: (data: string) => void 66 onStderrString: (data: string) => void
77 ): Promise<number> { 67 ): Promise<number> {
78 return new Promise<number>((resolve, reject) => { 68 return new Promise((resolve, reject) => {
79 const cargo = cp.spawn('cargo', cargoArgs, { 69 let cargoPath;
70 try {
71 cargoPath = getCargoPathOrFail();
72 } catch (err) {
73 return reject(err);
74 }
75
76 const cargo = cp.spawn(cargoPath, cargoArgs, {
80 stdio: ['ignore', 'pipe', 'pipe'], 77 stdio: ['ignore', 'pipe', 'pipe'],
81 cwd: this.rootFolder, 78 cwd: this.rootFolder
82 env: this.env,
83 }); 79 });
84 80
85 cargo.on('error', err => { 81 cargo.on('error', err => reject(new Error(`could not launch cargo: ${err}`)));
86 reject(new Error(`could not launch cargo: ${err}`)); 82
87 }); 83 cargo.stderr.on('data', chunk => onStderrString(chunk.toString()));
88 cargo.stderr.on('data', chunk => {
89 onStderrString(chunk.toString());
90 });
91 84
92 const rl = readline.createInterface({ input: cargo.stdout }); 85 const rl = readline.createInterface({ input: cargo.stdout });
93 rl.on('line', line => { 86 rl.on('line', line => {
@@ -103,4 +96,28 @@ export class Cargo {
103 }); 96 });
104 }); 97 });
105 } 98 }
106} \ No newline at end of file 99}
100
101// Mirrors `ra_env::get_path_for_executable` implementation
102function getCargoPathOrFail(): string {
103 const envVar = process.env.CARGO;
104 const executableName = "cargo";
105
106 if (envVar) {
107 if (isValidExecutable(envVar)) return envVar;
108
109 throw new Error(`\`${envVar}\` environment variable points to something that's not a valid executable`);
110 }
111
112 if (isValidExecutable(executableName)) return executableName;
113
114 const standardLocation = path.join(os.homedir(), '.cargo', 'bin', executableName);
115
116 if (isValidExecutable(standardLocation)) return standardLocation;
117
118 throw new Error(
119 `Failed to find \`${executableName}\` executable. ` +
120 `Make sure \`${executableName}\` is in \`$PATH\`, ` +
121 `or set \`${envVar}\` to point to a valid executable.`
122 );
123}
diff --git a/editors/code/src/commands/runnables.ts b/editors/code/src/commands/runnables.ts
index d77e8188c..ae328d2a4 100644
--- a/editors/code/src/commands/runnables.ts
+++ b/editors/code/src/commands/runnables.ts
@@ -64,29 +64,20 @@ export function runSingle(ctx: Ctx): Cmd {
64 }; 64 };
65} 65}
66 66
67function getLldbDebugConfig(config: ra.Runnable, sourceFileMap: Record<string, string>): vscode.DebugConfiguration { 67function getLldbDebugConfig(config: ra.Runnable, executable: string, sourceFileMap?: Record<string, string>): vscode.DebugConfiguration {
68 return { 68 return {
69 type: "lldb", 69 type: "lldb",
70 request: "launch", 70 request: "launch",
71 name: config.label, 71 name: config.label,
72 cargo: { 72 program: executable,
73 args: config.args,
74 },
75 args: config.extraArgs, 73 args: config.extraArgs,
76 cwd: config.cwd, 74 cwd: config.cwd,
77 sourceMap: sourceFileMap 75 sourceMap: sourceFileMap,
76 sourceLanguages: ["rust"]
78 }; 77 };
79} 78}
80 79
81const debugOutput = vscode.window.createOutputChannel("Debug"); 80function getCppvsDebugConfig(config: ra.Runnable, executable: string, sourceFileMap?: Record<string, string>): vscode.DebugConfiguration {
82
83async function getCppvsDebugConfig(config: ra.Runnable, sourceFileMap: Record<string, string>): Promise<vscode.DebugConfiguration> {
84 debugOutput.clear();
85
86 const cargo = new Cargo(config.cwd || '.', debugOutput);
87 const executable = await cargo.executableFromArgs(config.args);
88
89 // if we are here, there were no compilation errors.
90 return { 81 return {
91 type: (os.platform() === "win32") ? "cppvsdbg" : 'cppdbg', 82 type: (os.platform() === "win32") ? "cppvsdbg" : 'cppdbg',
92 request: "launch", 83 request: "launch",
@@ -98,36 +89,62 @@ async function getCppvsDebugConfig(config: ra.Runnable, sourceFileMap: Record<st
98 }; 89 };
99} 90}
100 91
92const debugOutput = vscode.window.createOutputChannel("Debug");
93
94async function getDebugExecutable(config: ra.Runnable): Promise<string> {
95 const cargo = new Cargo(config.cwd || '.', debugOutput);
96 const executable = await cargo.executableFromArgs(config.args);
97
98 // if we are here, there were no compilation errors.
99 return executable;
100}
101
102type DebugConfigProvider = (config: ra.Runnable, executable: string, sourceFileMap?: Record<string, string>) => vscode.DebugConfiguration;
103
101export function debugSingle(ctx: Ctx): Cmd { 104export function debugSingle(ctx: Ctx): Cmd {
102 return async (config: ra.Runnable) => { 105 return async (config: ra.Runnable) => {
103 const editor = ctx.activeRustEditor; 106 const editor = ctx.activeRustEditor;
104 if (!editor) return; 107 if (!editor) return;
105 108
106 const lldbId = "vadimcn.vscode-lldb"; 109 const knownEngines: Record<string, DebugConfigProvider> = {
107 const cpptoolsId = "ms-vscode.cpptools"; 110 "vadimcn.vscode-lldb": getLldbDebugConfig,
111 "ms-vscode.cpptools": getCppvsDebugConfig
112 };
113 const debugOptions = ctx.config.debug;
108 114
109 const debugEngineId = ctx.config.debug.engine;
110 let debugEngine = null; 115 let debugEngine = null;
111 if (debugEngineId === "auto") { 116 if (debugOptions.engine === "auto") {
112 debugEngine = vscode.extensions.getExtension(lldbId); 117 for (var engineId in knownEngines) {
113 if (!debugEngine) { 118 debugEngine = vscode.extensions.getExtension(engineId);
114 debugEngine = vscode.extensions.getExtension(cpptoolsId); 119 if (debugEngine) break;
115 } 120 }
116 } 121 }
117 else { 122 else {
118 debugEngine = vscode.extensions.getExtension(debugEngineId); 123 debugEngine = vscode.extensions.getExtension(debugOptions.engine);
119 } 124 }
120 125
121 if (!debugEngine) { 126 if (!debugEngine) {
122 vscode.window.showErrorMessage(`Install [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=${lldbId})` 127 vscode.window.showErrorMessage(`Install [CodeLLDB](https://marketplace.visualstudio.com/items?itemName=vadimcn.vscode-lldb)`
123 + ` or [MS C++ tools](https://marketplace.visualstudio.com/items?itemName=${cpptoolsId}) extension for debugging.`); 128 + ` or [MS C++ tools](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools) extension for debugging.`);
124 return; 129 return;
125 } 130 }
126 131
127 const debugConfig = lldbId === debugEngine.id 132 debugOutput.clear();
128 ? getLldbDebugConfig(config, ctx.config.debug.sourceFileMap) 133 if (ctx.config.debug.openUpDebugPane) {
129 : await getCppvsDebugConfig(config, ctx.config.debug.sourceFileMap); 134 debugOutput.show(true);
135 }
136
137 const executable = await getDebugExecutable(config);
138 const debugConfig = knownEngines[debugEngine.id](config, executable, debugOptions.sourceFileMap);
139 if (debugConfig.type in debugOptions.engineSettings) {
140 const settingsMap = (debugOptions.engineSettings as any)[debugConfig.type];
141 for (var key in settingsMap) {
142 debugConfig[key] = settingsMap[key];
143 }
144 }
130 145
146 debugOutput.appendLine("Launching debug configuration:");
147 debugOutput.appendLine(JSON.stringify(debugConfig, null, 2));
131 return vscode.debug.startDebugging(undefined, debugConfig); 148 return vscode.debug.startDebugging(undefined, debugConfig);
132 }; 149 };
133} 150}
diff --git a/editors/code/src/config.ts b/editors/code/src/config.ts
index 110e54180..be2e27aec 100644
--- a/editors/code/src/config.ts
+++ b/editors/code/src/config.ts
@@ -94,6 +94,7 @@ export class Config {
94 94
95 get inlayHints() { 95 get inlayHints() {
96 return { 96 return {
97 enable: this.get<boolean>("inlayHints.enable"),
97 typeHints: this.get<boolean>("inlayHints.typeHints"), 98 typeHints: this.get<boolean>("inlayHints.typeHints"),
98 parameterHints: this.get<boolean>("inlayHints.parameterHints"), 99 parameterHints: this.get<boolean>("inlayHints.parameterHints"),
99 chainingHints: this.get<boolean>("inlayHints.chainingHints"), 100 chainingHints: this.get<boolean>("inlayHints.chainingHints"),
@@ -108,10 +109,14 @@ export class Config {
108 } 109 }
109 110
110 get debug() { 111 get debug() {
112 // "/rustc/<id>" used by suggestions only.
113 const { ["/rustc/<id>"]: _, ...sourceFileMap } = this.get<Record<string, string>>("debug.sourceFileMap");
114
111 return { 115 return {
112 engine: this.get<string>("debug.engine"), 116 engine: this.get<string>("debug.engine"),
113 sourceFileMap: this.get<Record<string, string>>("debug.sourceFileMap"), 117 engineSettings: this.get<object>("debug.engineSettings"),
118 openUpDebugPane: this.get<boolean>("debug.openUpDebugPane"),
119 sourceFileMap: sourceFileMap,
114 }; 120 };
115 } 121 }
116
117} 122}
diff --git a/editors/code/src/inlay_hints.ts b/editors/code/src/inlay_hints.ts
index a09531797..a2b07d003 100644
--- a/editors/code/src/inlay_hints.ts
+++ b/editors/code/src/inlay_hints.ts
@@ -10,13 +10,13 @@ export function activateInlayHints(ctx: Ctx) {
10 const maybeUpdater = { 10 const maybeUpdater = {
11 updater: null as null | HintsUpdater, 11 updater: null as null | HintsUpdater,
12 async onConfigChange() { 12 async onConfigChange() {
13 if ( 13 const anyEnabled = ctx.config.inlayHints.typeHints
14 !ctx.config.inlayHints.typeHints && 14 || ctx.config.inlayHints.parameterHints
15 !ctx.config.inlayHints.parameterHints && 15 || ctx.config.inlayHints.chainingHints;
16 !ctx.config.inlayHints.chainingHints 16 const enabled = ctx.config.inlayHints.enable && anyEnabled;
17 ) { 17
18 return this.dispose(); 18 if (!enabled) return this.dispose();
19 } 19
20 await sleep(100); 20 await sleep(100);
21 if (this.updater) { 21 if (this.updater) {
22 this.updater.syncCacheAndRenderHints(); 22 this.updater.syncCacheAndRenderHints();
diff --git a/editors/code/src/main.ts b/editors/code/src/main.ts
index efd56a84b..9b020d001 100644
--- a/editors/code/src/main.ts
+++ b/editors/code/src/main.ts
@@ -8,10 +8,9 @@ import { activateInlayHints } from './inlay_hints';
8import { activateStatusDisplay } from './status_display'; 8import { activateStatusDisplay } from './status_display';
9import { Ctx } from './ctx'; 9import { Ctx } from './ctx';
10import { Config, NIGHTLY_TAG } from './config'; 10import { Config, NIGHTLY_TAG } from './config';
11import { log, assert } from './util'; 11import { log, assert, isValidExecutable } from './util';
12import { PersistentState } from './persistent_state'; 12import { PersistentState } from './persistent_state';
13import { fetchRelease, download } from './net'; 13import { fetchRelease, download } from './net';
14import { spawnSync } from 'child_process';
15import { activateTaskProvider } from './tasks'; 14import { activateTaskProvider } from './tasks';
16 15
17let ctx: Ctx | undefined; 16let ctx: Ctx | undefined;
@@ -179,10 +178,7 @@ async function bootstrapServer(config: Config, state: PersistentState): Promise<
179 178
180 log.debug("Using server binary at", path); 179 log.debug("Using server binary at", path);
181 180
182 const res = spawnSync(path, ["--version"], { encoding: 'utf8' }); 181 if (!isValidExecutable(path)) {
183 log.debug("Checked binary availability via --version", res);
184 log.debug(res, "--version output:", res.output);
185 if (res.status !== 0) {
186 throw new Error(`Failed to execute ${path} --version`); 182 throw new Error(`Failed to execute ${path} --version`);
187 } 183 }
188 184
diff --git a/editors/code/src/util.ts b/editors/code/src/util.ts
index 6f91f81d6..127a9e911 100644
--- a/editors/code/src/util.ts
+++ b/editors/code/src/util.ts
@@ -1,6 +1,7 @@
1import * as lc from "vscode-languageclient"; 1import * as lc from "vscode-languageclient";
2import * as vscode from "vscode"; 2import * as vscode from "vscode";
3import { strict as nativeAssert } from "assert"; 3import { strict as nativeAssert } from "assert";
4import { spawnSync } from "child_process";
4 5
5export function assert(condition: boolean, explanation: string): asserts condition { 6export function assert(condition: boolean, explanation: string): asserts condition {
6 try { 7 try {
@@ -82,3 +83,13 @@ export function isRustDocument(document: vscode.TextDocument): document is RustD
82export function isRustEditor(editor: vscode.TextEditor): editor is RustEditor { 83export function isRustEditor(editor: vscode.TextEditor): editor is RustEditor {
83 return isRustDocument(editor.document); 84 return isRustDocument(editor.document);
84} 85}
86
87export function isValidExecutable(path: string): boolean {
88 log.debug("Checking availability of a binary at", path);
89
90 const res = spawnSync(path, ["--version"], { encoding: 'utf8' });
91
92 log.debug(res, "--version output:", res.output);
93
94 return res.status === 0;
95}