From 41a1ec723ce2ea3fa78ae468830f0a77e5658307 Mon Sep 17 00:00:00 2001 From: Emil Lauridsen Date: Wed, 25 Dec 2019 16:44:42 +0100 Subject: Remove cargo-watch from vscode extension. Still keeps tests around for reference when porting them to rust --- editors/code/package.json | 12 +- editors/code/src/commands/cargo_watch.ts | 264 ----------------------------- editors/code/src/commands/runnables.ts | 91 ---------- editors/code/src/extension.ts | 25 --- editors/code/src/utils/processes.ts | 51 ------ editors/code/src/utils/terminateProcess.sh | 12 -- 6 files changed, 1 insertion(+), 454 deletions(-) delete mode 100644 editors/code/src/commands/cargo_watch.ts delete mode 100644 editors/code/src/utils/processes.ts delete mode 100644 editors/code/src/utils/terminateProcess.sh (limited to 'editors') diff --git a/editors/code/package.json b/editors/code/package.json index f75fafeb9..6cb24a3ce 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -18,7 +18,7 @@ "scripts": { "vscode:prepublish": "npm run compile", "package": "vsce package", - "compile": "rollup -c && shx cp src/utils/terminateProcess.sh bundle/terminateProcess.sh", + "compile": "rollup -c", "watch": "tsc -watch -p ./", "fix": "prettier **/*.{json,ts} --write && tslint --project . --fix", "lint": "tslint --project .", @@ -133,16 +133,6 @@ "command": "rust-analyzer.reload", "title": "Restart server", "category": "Rust Analyzer" - }, - { - "command": "rust-analyzer.startCargoWatch", - "title": "Start Cargo Watch", - "category": "Rust Analyzer" - }, - { - "command": "rust-analyzer.stopCargoWatch", - "title": "Stop Cargo Watch", - "category": "Rust Analyzer" } ], "keybindings": [ diff --git a/editors/code/src/commands/cargo_watch.ts b/editors/code/src/commands/cargo_watch.ts deleted file mode 100644 index ac62bdd48..000000000 --- a/editors/code/src/commands/cargo_watch.ts +++ /dev/null @@ -1,264 +0,0 @@ -import * as child_process from 'child_process'; -import * as path from 'path'; -import * as vscode from 'vscode'; - -import { Server } from '../server'; -import { terminate } from '../utils/processes'; -import { LineBuffer } from './line_buffer'; -import { StatusDisplay } from './watch_status'; - -import { - mapRustDiagnosticToVsCode, - RustDiagnostic, -} from '../utils/diagnostics/rust'; -import SuggestedFixCollection from '../utils/diagnostics/SuggestedFixCollection'; -import { areDiagnosticsEqual } from '../utils/diagnostics/vscode'; - -export async function registerCargoWatchProvider( - subscriptions: vscode.Disposable[], -): Promise { - let cargoExists = false; - - // Check if the working directory is valid cargo root path - const cargoTomlPath = path.join(vscode.workspace.rootPath!, 'Cargo.toml'); - const cargoTomlUri = vscode.Uri.file(cargoTomlPath); - const cargoTomlFileInfo = await vscode.workspace.fs.stat(cargoTomlUri); - - if (cargoTomlFileInfo) { - cargoExists = true; - } - - if (!cargoExists) { - vscode.window.showErrorMessage( - `Couldn\'t find \'Cargo.toml\' at ${cargoTomlPath}`, - ); - return; - } - - const provider = new CargoWatchProvider(); - subscriptions.push(provider); - return provider; -} - -export class CargoWatchProvider implements vscode.Disposable { - private readonly diagnosticCollection: vscode.DiagnosticCollection; - private readonly statusDisplay: StatusDisplay; - private readonly outputChannel: vscode.OutputChannel; - - private suggestedFixCollection: SuggestedFixCollection; - private codeActionDispose: vscode.Disposable; - - private cargoProcess?: child_process.ChildProcess; - - constructor() { - this.diagnosticCollection = vscode.languages.createDiagnosticCollection( - 'rustc', - ); - this.statusDisplay = new StatusDisplay( - Server.config.cargoWatchOptions.command, - ); - this.outputChannel = vscode.window.createOutputChannel( - 'Cargo Watch Trace', - ); - - // Track `rustc`'s suggested fixes so we can convert them to code actions - this.suggestedFixCollection = new SuggestedFixCollection(); - this.codeActionDispose = vscode.languages.registerCodeActionsProvider( - [{ scheme: 'file', language: 'rust' }], - this.suggestedFixCollection, - { - providedCodeActionKinds: - SuggestedFixCollection.PROVIDED_CODE_ACTION_KINDS, - }, - ); - } - - public start() { - if (this.cargoProcess) { - vscode.window.showInformationMessage( - 'Cargo Watch is already running', - ); - return; - } - - let args = - Server.config.cargoWatchOptions.command + ' --message-format json'; - if (Server.config.cargoWatchOptions.allTargets) { - args += ' --all-targets'; - } - if (Server.config.cargoWatchOptions.command.length > 0) { - // Excape the double quote string: - args += ' ' + Server.config.cargoWatchOptions.arguments; - } - // Windows handles arguments differently than the unix-likes, so we need to wrap the args in double quotes - if (process.platform === 'win32') { - args = '"' + args + '"'; - } - - const ignoreFlags = Server.config.cargoWatchOptions.ignore.reduce( - (flags, pattern) => [...flags, '--ignore', pattern], - [] as string[], - ); - - // Start the cargo watch with json message - this.cargoProcess = child_process.spawn( - 'cargo', - ['watch', '-x', args, ...ignoreFlags], - { - stdio: ['ignore', 'pipe', 'pipe'], - cwd: vscode.workspace.rootPath, - windowsVerbatimArguments: true, - }, - ); - - if (!this.cargoProcess) { - vscode.window.showErrorMessage('Cargo Watch failed to start'); - return; - } - - const stdoutData = new LineBuffer(); - this.cargoProcess.stdout?.on('data', (s: string) => { - stdoutData.processOutput(s, line => { - this.logInfo(line); - try { - this.parseLine(line); - } catch (err) { - this.logError(`Failed to parse: ${err}, content : ${line}`); - } - }); - }); - - const stderrData = new LineBuffer(); - this.cargoProcess.stderr?.on('data', (s: string) => { - stderrData.processOutput(s, line => { - this.logError('Error on cargo-watch : {\n' + line + '}\n'); - }); - }); - - this.cargoProcess.on('error', (err: Error) => { - this.logError( - 'Error on cargo-watch process : {\n' + err.message + '}\n', - ); - }); - - this.logInfo('cargo-watch started.'); - } - - public stop() { - if (this.cargoProcess) { - this.cargoProcess.kill(); - terminate(this.cargoProcess); - this.cargoProcess = undefined; - } else { - vscode.window.showInformationMessage('Cargo Watch is not running'); - } - } - - public dispose(): void { - this.stop(); - - this.diagnosticCollection.clear(); - this.diagnosticCollection.dispose(); - this.outputChannel.dispose(); - this.statusDisplay.dispose(); - this.codeActionDispose.dispose(); - } - - private logInfo(line: string) { - if (Server.config.cargoWatchOptions.trace === 'verbose') { - this.outputChannel.append(line); - } - } - - private logError(line: string) { - if ( - Server.config.cargoWatchOptions.trace === 'error' || - Server.config.cargoWatchOptions.trace === 'verbose' - ) { - this.outputChannel.append(line); - } - } - - private parseLine(line: string) { - if (line.startsWith('[Running')) { - this.diagnosticCollection.clear(); - this.suggestedFixCollection.clear(); - this.statusDisplay.show(); - } - - if (line.startsWith('[Finished running')) { - this.statusDisplay.hide(); - } - - interface CargoArtifact { - reason: string; - package_id: string; - } - - // https://github.com/rust-lang/cargo/blob/master/src/cargo/util/machine_message.rs - interface CargoMessage { - reason: string; - package_id: string; - message: RustDiagnostic; - } - - // cargo-watch itself output non json format - // Ignore these lines - let data: CargoMessage; - try { - data = JSON.parse(line.trim()); - } catch (error) { - this.logError(`Fail to parse to json : { ${error} }`); - return; - } - - if (data.reason === 'compiler-artifact') { - const msg = data as CargoArtifact; - - // The format of the package_id is "{name} {version} ({source_id})", - // https://github.com/rust-lang/cargo/blob/37ad03f86e895bb80b474c1c088322634f4725f5/src/cargo/core/package_id.rs#L53 - this.statusDisplay.packageName = msg.package_id.split(' ')[0]; - } else if (data.reason === 'compiler-message') { - const msg = data.message as RustDiagnostic; - - const mapResult = mapRustDiagnosticToVsCode(msg); - if (!mapResult) { - return; - } - - const { location, diagnostic, suggestedFixes } = mapResult; - const fileUri = location.uri; - - const diagnostics: vscode.Diagnostic[] = [ - ...(this.diagnosticCollection!.get(fileUri) || []), - ]; - - // If we're building multiple targets it's possible we've already seen this diagnostic - const isDuplicate = diagnostics.some(d => - areDiagnosticsEqual(d, diagnostic), - ); - if (isDuplicate) { - return; - } - - diagnostics.push(diagnostic); - this.diagnosticCollection!.set(fileUri, diagnostics); - - if (suggestedFixes.length) { - for (const suggestedFix of suggestedFixes) { - this.suggestedFixCollection.addSuggestedFixForDiagnostic( - suggestedFix, - diagnostic, - ); - } - - // Have VsCode query us for the code actions - vscode.commands.executeCommand( - 'vscode.executeCodeActionProvider', - fileUri, - diagnostic.range, - ); - } - } - } -} diff --git a/editors/code/src/commands/runnables.ts b/editors/code/src/commands/runnables.ts index cf980e257..7728541de 100644 --- a/editors/code/src/commands/runnables.ts +++ b/editors/code/src/commands/runnables.ts @@ -1,11 +1,7 @@ -import * as child_process from 'child_process'; - -import * as util from 'util'; import * as vscode from 'vscode'; import * as lc from 'vscode-languageclient'; import { Server } from '../server'; -import { CargoWatchProvider, registerCargoWatchProvider } from './cargo_watch'; interface RunnablesParams { textDocument: lc.TextDocumentIdentifier; @@ -131,90 +127,3 @@ export async function handleSingle(runnable: Runnable) { return vscode.tasks.executeTask(task); } - -/** - * Interactively asks the user whether we should run `cargo check` in order to - * provide inline diagnostics; the user is met with a series of dialog boxes - * that, when accepted, allow us to `cargo install cargo-watch` and then run it. - */ -export async function interactivelyStartCargoWatch( - context: vscode.ExtensionContext, -): Promise { - if (Server.config.cargoWatchOptions.enableOnStartup === 'disabled') { - return; - } - - if (Server.config.cargoWatchOptions.enableOnStartup === 'ask') { - const watch = await vscode.window.showInformationMessage( - 'Start watching changes with cargo? (Executes `cargo watch`, provides inline diagnostics)', - 'yes', - 'no', - ); - if (watch !== 'yes') { - return; - } - } - - return startCargoWatch(context); -} - -export async function startCargoWatch( - context: vscode.ExtensionContext, -): Promise { - const execPromise = util.promisify(child_process.exec); - - const { stderr, code = 0 } = await execPromise( - 'cargo watch --version', - ).catch(e => e); - - if (stderr.includes('no such subcommand: `watch`')) { - const msg = - 'The `cargo-watch` subcommand is not installed. Install? (takes ~1-2 minutes)'; - const install = await vscode.window.showInformationMessage( - msg, - 'yes', - 'no', - ); - if (install !== 'yes') { - return; - } - - const label = 'install-cargo-watch'; - const taskFinished = new Promise((resolve, _reject) => { - const disposable = vscode.tasks.onDidEndTask(({ execution }) => { - if (execution.task.name === label) { - disposable.dispose(); - resolve(); - } - }); - }); - - vscode.tasks.executeTask( - createTask({ - label, - bin: 'cargo', - args: ['install', 'cargo-watch'], - env: {}, - }), - ); - await taskFinished; - const output = await execPromise('cargo watch --version').catch(e => e); - if (output.stderr !== '') { - vscode.window.showErrorMessage( - `Couldn't install \`cargo-\`watch: ${output.stderr}`, - ); - return; - } - } else if (code !== 0) { - vscode.window.showErrorMessage( - `\`cargo watch\` failed with ${code}: ${stderr}`, - ); - return; - } - - const provider = await registerCargoWatchProvider(context.subscriptions); - if (provider) { - provider.start(); - } - return provider; -} diff --git a/editors/code/src/extension.ts b/editors/code/src/extension.ts index 815f3692c..72a4d4bf2 100644 --- a/editors/code/src/extension.ts +++ b/editors/code/src/extension.ts @@ -2,13 +2,8 @@ import * as vscode from 'vscode'; import * as lc from 'vscode-languageclient'; import * as commands from './commands'; -import { CargoWatchProvider } from './commands/cargo_watch'; import { ExpandMacroContentProvider } from './commands/expand_macro'; import { HintsUpdater } from './commands/inlay_hints'; -import { - interactivelyStartCargoWatch, - startCargoWatch, -} from './commands/runnables'; import { SyntaxTreeContentProvider } from './commands/syntaxTree'; import * as events from './events'; import * as notifications from './notifications'; @@ -139,26 +134,6 @@ export async function activate(context: vscode.ExtensionContext) { vscode.commands.registerCommand('rust-analyzer.reload', reloadCommand); - // Executing `cargo watch` provides us with inline diagnostics on save - let provider: CargoWatchProvider | undefined; - interactivelyStartCargoWatch(context).then(p => { - provider = p; - }); - registerCommand('rust-analyzer.startCargoWatch', () => { - if (provider) { - provider.start(); - } else { - startCargoWatch(context).then(p => { - provider = p; - }); - } - }); - registerCommand('rust-analyzer.stopCargoWatch', () => { - if (provider) { - provider.stop(); - } - }); - // Start the language server, finally! try { await startServer(); diff --git a/editors/code/src/utils/processes.ts b/editors/code/src/utils/processes.ts deleted file mode 100644 index a1d6b7eaf..000000000 --- a/editors/code/src/utils/processes.ts +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -import * as cp from 'child_process'; -import ChildProcess = cp.ChildProcess; - -import { join } from 'path'; - -const isWindows = process.platform === 'win32'; -const isMacintosh = process.platform === 'darwin'; -const isLinux = process.platform === 'linux'; - -// this is very complex, but is basically copy-pased from VSCode implementation here: -// https://github.com/Microsoft/vscode-languageserver-node/blob/dbfd37e35953ad0ee14c4eeced8cfbc41697b47e/client/src/utils/processes.ts#L15 - -// And see discussion at -// https://github.com/rust-analyzer/rust-analyzer/pull/1079#issuecomment-478908109 - -export function terminate(process: ChildProcess, cwd?: string): boolean { - if (isWindows) { - try { - // This we run in Atom execFileSync is available. - // Ignore stderr since this is otherwise piped to parent.stderr - // which might be already closed. - const options: any = { - stdio: ['pipe', 'pipe', 'ignore'], - }; - if (cwd) { - options.cwd = cwd; - } - cp.execFileSync( - 'taskkill', - ['/T', '/F', '/PID', process.pid.toString()], - options, - ); - return true; - } catch (err) { - return false; - } - } else if (isLinux || isMacintosh) { - try { - const cmd = join(__dirname, 'terminateProcess.sh'); - const result = cp.spawnSync(cmd, [process.pid.toString()]); - return result.error ? false : true; - } catch (err) { - return false; - } - } else { - process.kill('SIGKILL'); - return true; - } -} diff --git a/editors/code/src/utils/terminateProcess.sh b/editors/code/src/utils/terminateProcess.sh deleted file mode 100644 index 2ec9e1c2e..000000000 --- a/editors/code/src/utils/terminateProcess.sh +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/bash - -terminateTree() { - for cpid in $(pgrep -P $1); do - terminateTree $cpid - done - kill -9 $1 > /dev/null 2>&1 -} - -for pid in $*; do - terminateTree $pid -done \ No newline at end of file -- cgit v1.2.3 From 6af4bf7a8d27e653d2e6316172fe140871054d27 Mon Sep 17 00:00:00 2001 From: Emil Lauridsen Date: Wed, 25 Dec 2019 16:50:38 +0100 Subject: Configuration plumbing for cargo watcher --- editors/code/package.json | 40 ++++++++----------------------- editors/code/src/config.ts | 59 ++++++++++++---------------------------------- editors/code/src/server.ts | 3 +++ 3 files changed, 28 insertions(+), 74 deletions(-) (limited to 'editors') diff --git a/editors/code/package.json b/editors/code/package.json index 6cb24a3ce..5f4123397 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -188,20 +188,10 @@ "default": "ra_lsp_server", "description": "Path to ra_lsp_server executable" }, - "rust-analyzer.enableCargoWatchOnStartup": { - "type": "string", - "default": "ask", - "enum": [ - "ask", - "enabled", - "disabled" - ], - "enumDescriptions": [ - "Asks each time whether to run `cargo watch`", - "`cargo watch` is always started", - "Don't start `cargo watch`" - ], - "description": "Whether to run `cargo watch` on startup" + "rust-analyzer.enableCargoCheck": { + "type": "boolean", + "default": true, + "description": "Run `cargo check` for diagnostics on save" }, "rust-analyzer.excludeGlobs": { "type": "array", @@ -213,25 +203,15 @@ "default": true, "description": "client provided file watching instead of notify watching." }, - "rust-analyzer.cargo-watch.arguments": { - "type": "string", - "description": "`cargo-watch` arguments. (e.g: `--features=\"shumway,pdf\"` will run as `cargo watch -x \"check --features=\"shumway,pdf\"\"` )", - "default": "" - }, - "rust-analyzer.cargo-watch.command": { - "type": "string", - "description": "`cargo-watch` command. (e.g: `clippy` will run as `cargo watch -x clippy` )", - "default": "check" - }, - "rust-analyzer.cargo-watch.ignore": { + "rust-analyzer.cargo-check.arguments": { "type": "array", - "description": "A list of patterns for cargo-watch to ignore (will be passed as `--ignore`)", + "description": "`cargo-check` arguments. (e.g: `--features=\"shumway,pdf\"` will run as `cargo check --features=\"shumway,pdf\"` )", "default": [] }, - "rust-analyzer.cargo-watch.allTargets": { - "type": "boolean", - "description": "Check all targets and tests (will be passed as `--all-targets`)", - "default": true + "rust-analyzer.cargo-check.command": { + "type": "string", + "description": "`cargo-check` command. (e.g: `clippy` will run as `cargo clippy` )", + "default": "check" }, "rust-analyzer.trace.server": { "type": "string", diff --git a/editors/code/src/config.ts b/editors/code/src/config.ts index e131f09df..96532e2c9 100644 --- a/editors/code/src/config.ts +++ b/editors/code/src/config.ts @@ -4,16 +4,10 @@ import { Server } from './server'; const RA_LSP_DEBUG = process.env.__RA_LSP_SERVER_DEBUG; -export type CargoWatchStartupOptions = 'ask' | 'enabled' | 'disabled'; -export type CargoWatchTraceOptions = 'off' | 'error' | 'verbose'; - -export interface CargoWatchOptions { - enableOnStartup: CargoWatchStartupOptions; - arguments: string; - command: string; - trace: CargoWatchTraceOptions; - ignore: string[]; - allTargets: boolean; +export interface CargoCheckOptions { + enabled: boolean; + arguments: string[]; + command: null | string; } export interface CargoFeatures { @@ -35,13 +29,10 @@ export class Config { public featureFlags = {}; // for internal use public withSysroot: null | boolean = null; - public cargoWatchOptions: CargoWatchOptions = { - enableOnStartup: 'ask', - trace: 'off', - arguments: '', - command: '', - ignore: [], - allTargets: true, + public cargoCheckOptions: CargoCheckOptions = { + enabled: true, + arguments: [], + command: null, }; public cargoFeatures: CargoFeatures = { noDefaultFeatures: false, @@ -100,47 +91,27 @@ export class Config { RA_LSP_DEBUG || (config.get('raLspServerPath') as string); } - if (config.has('enableCargoWatchOnStartup')) { - this.cargoWatchOptions.enableOnStartup = config.get< - CargoWatchStartupOptions - >('enableCargoWatchOnStartup', 'ask'); - } - - if (config.has('trace.cargo-watch')) { - this.cargoWatchOptions.trace = config.get( - 'trace.cargo-watch', - 'off', + if (config.has('enableCargoCheck')) { + this.cargoCheckOptions.enabled = config.get( + 'enableCargoCheck', + true, ); } if (config.has('cargo-watch.arguments')) { - this.cargoWatchOptions.arguments = config.get( + this.cargoCheckOptions.arguments = config.get( 'cargo-watch.arguments', - '', + [], ); } if (config.has('cargo-watch.command')) { - this.cargoWatchOptions.command = config.get( + this.cargoCheckOptions.command = config.get( 'cargo-watch.command', '', ); } - if (config.has('cargo-watch.ignore')) { - this.cargoWatchOptions.ignore = config.get( - 'cargo-watch.ignore', - [], - ); - } - - if (config.has('cargo-watch.allTargets')) { - this.cargoWatchOptions.allTargets = config.get( - 'cargo-watch.allTargets', - true, - ); - } - if (config.has('lruCapacity')) { this.lruCapacity = config.get('lruCapacity') as number; } diff --git a/editors/code/src/server.ts b/editors/code/src/server.ts index 5ace1d0fa..409d3b4b7 100644 --- a/editors/code/src/server.ts +++ b/editors/code/src/server.ts @@ -55,6 +55,9 @@ export class Server { publishDecorations: true, lruCapacity: Server.config.lruCapacity, maxInlayHintLength: Server.config.maxInlayHintLength, + cargoCheckEnable: Server.config.cargoCheckOptions.enabled, + cargoCheckCommand: Server.config.cargoCheckOptions.command, + cargoCheckArgs: Server.config.cargoCheckOptions.arguments, excludeGlobs: Server.config.excludeGlobs, useClientWatching: Server.config.useClientWatching, featureFlags: Server.config.featureFlags, -- cgit v1.2.3 From 500fe46e6c0df7827d56c7cd07741533422e7743 Mon Sep 17 00:00:00 2001 From: Emil Lauridsen Date: Wed, 25 Dec 2019 17:34:51 +0100 Subject: Remove cargo watch supporting code and tests from vscode extension --- .../clippy/trivially_copy_pass_by_ref.json | 110 -------- .../fixtures/rust-diagnostics/error/E0053.json | 42 --- .../fixtures/rust-diagnostics/error/E0061.json | 114 -------- .../fixtures/rust-diagnostics/error/E0277.json | 261 ------------------ .../fixtures/rust-diagnostics/error/E0308.json | 33 --- .../rust-diagnostics/warning/unused_variables.json | 72 ----- .../src/test/utils/diagnotics/SuggestedFix.test.ts | 134 --------- .../diagnotics/SuggestedFixCollection.test.ts | 127 --------- .../code/src/test/utils/diagnotics/rust.test.ts | 236 ---------------- .../code/src/test/utils/diagnotics/vscode.test.ts | 98 ------- editors/code/src/utils/diagnostics/SuggestedFix.ts | 67 ----- .../utils/diagnostics/SuggestedFixCollection.ts | 77 ------ editors/code/src/utils/diagnostics/rust.ts | 299 --------------------- editors/code/src/utils/diagnostics/vscode.ts | 14 - 14 files changed, 1684 deletions(-) delete mode 100644 editors/code/src/test/fixtures/rust-diagnostics/clippy/trivially_copy_pass_by_ref.json delete mode 100644 editors/code/src/test/fixtures/rust-diagnostics/error/E0053.json delete mode 100644 editors/code/src/test/fixtures/rust-diagnostics/error/E0061.json delete mode 100644 editors/code/src/test/fixtures/rust-diagnostics/error/E0277.json delete mode 100644 editors/code/src/test/fixtures/rust-diagnostics/error/E0308.json delete mode 100644 editors/code/src/test/fixtures/rust-diagnostics/warning/unused_variables.json delete mode 100644 editors/code/src/test/utils/diagnotics/SuggestedFix.test.ts delete mode 100644 editors/code/src/test/utils/diagnotics/SuggestedFixCollection.test.ts delete mode 100644 editors/code/src/test/utils/diagnotics/rust.test.ts delete mode 100644 editors/code/src/test/utils/diagnotics/vscode.test.ts delete mode 100644 editors/code/src/utils/diagnostics/SuggestedFix.ts delete mode 100644 editors/code/src/utils/diagnostics/SuggestedFixCollection.ts delete mode 100644 editors/code/src/utils/diagnostics/rust.ts delete mode 100644 editors/code/src/utils/diagnostics/vscode.ts (limited to 'editors') diff --git a/editors/code/src/test/fixtures/rust-diagnostics/clippy/trivially_copy_pass_by_ref.json b/editors/code/src/test/fixtures/rust-diagnostics/clippy/trivially_copy_pass_by_ref.json deleted file mode 100644 index d874e99bc..000000000 --- a/editors/code/src/test/fixtures/rust-diagnostics/clippy/trivially_copy_pass_by_ref.json +++ /dev/null @@ -1,110 +0,0 @@ -{ - "message": "this argument is passed by reference, but would be more efficient if passed by value", - "code": { - "code": "clippy::trivially_copy_pass_by_ref", - "explanation": null - }, - "level": "warning", - "spans": [ - { - "file_name": "compiler/mir/tagset.rs", - "byte_start": 941, - "byte_end": 946, - "line_start": 42, - "line_end": 42, - "column_start": 24, - "column_end": 29, - "is_primary": true, - "text": [ - { - "text": " pub fn is_disjoint(&self, other: Self) -> bool {", - "highlight_start": 24, - "highlight_end": 29 - } - ], - "label": null, - "suggested_replacement": null, - "suggestion_applicability": null, - "expansion": null - } - ], - "children": [ - { - "message": "lint level defined here", - "code": null, - "level": "note", - "spans": [ - { - "file_name": "compiler/lib.rs", - "byte_start": 8, - "byte_end": 19, - "line_start": 1, - "line_end": 1, - "column_start": 9, - "column_end": 20, - "is_primary": true, - "text": [ - { - "text": "#![warn(clippy::all)]", - "highlight_start": 9, - "highlight_end": 20 - } - ], - "label": null, - "suggested_replacement": null, - "suggestion_applicability": null, - "expansion": null - } - ], - "children": [], - "rendered": null - }, - { - "message": "#[warn(clippy::trivially_copy_pass_by_ref)] implied by #[warn(clippy::all)]", - "code": null, - "level": "note", - "spans": [], - "children": [], - "rendered": null - }, - { - "message": "for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref", - "code": null, - "level": "help", - "spans": [], - "children": [], - "rendered": null - }, - { - "message": "consider passing by value instead", - "code": null, - "level": "help", - "spans": [ - { - "file_name": "compiler/mir/tagset.rs", - "byte_start": 941, - "byte_end": 946, - "line_start": 42, - "line_end": 42, - "column_start": 24, - "column_end": 29, - "is_primary": true, - "text": [ - { - "text": " pub fn is_disjoint(&self, other: Self) -> bool {", - "highlight_start": 24, - "highlight_end": 29 - } - ], - "label": null, - "suggested_replacement": "self", - "suggestion_applicability": "Unspecified", - "expansion": null - } - ], - "children": [], - "rendered": null - } - ], - "rendered": "warning: this argument is passed by reference, but would be more efficient if passed by value\n --> compiler/mir/tagset.rs:42:24\n |\n42 | pub fn is_disjoint(&self, other: Self) -> bool {\n | ^^^^^ help: consider passing by value instead: `self`\n |\nnote: lint level defined here\n --> compiler/lib.rs:1:9\n |\n1 | #![warn(clippy::all)]\n | ^^^^^^^^^^^\n = note: #[warn(clippy::trivially_copy_pass_by_ref)] implied by #[warn(clippy::all)]\n = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref\n\n" -} diff --git a/editors/code/src/test/fixtures/rust-diagnostics/error/E0053.json b/editors/code/src/test/fixtures/rust-diagnostics/error/E0053.json deleted file mode 100644 index ea5c976d1..000000000 --- a/editors/code/src/test/fixtures/rust-diagnostics/error/E0053.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "message": "method `next` has an incompatible type for trait", - "code": { - "code": "E0053", - "explanation": "\nThe parameters of any trait method must match between a trait implementation\nand the trait definition.\n\nHere are a couple examples of this error:\n\n```compile_fail,E0053\ntrait Foo {\n fn foo(x: u16);\n fn bar(&self);\n}\n\nstruct Bar;\n\nimpl Foo for Bar {\n // error, expected u16, found i16\n fn foo(x: i16) { }\n\n // error, types differ in mutability\n fn bar(&mut self) { }\n}\n```\n" - }, - "level": "error", - "spans": [ - { - "file_name": "compiler/ty/list_iter.rs", - "byte_start": 1307, - "byte_end": 1350, - "line_start": 52, - "line_end": 52, - "column_start": 5, - "column_end": 48, - "is_primary": true, - "text": [ - { - "text": " fn next(&self) -> Option<&'list ty::Ref> {", - "highlight_start": 5, - "highlight_end": 48 - } - ], - "label": "types differ in mutability", - "suggested_replacement": null, - "suggestion_applicability": null, - "expansion": null - } - ], - "children": [ - { - "message": "expected type `fn(&mut ty::list_iter::ListIterator<'list, M>) -> std::option::Option<&ty::Ref>`\n found type `fn(&ty::list_iter::ListIterator<'list, M>) -> std::option::Option<&'list ty::Ref>`", - "code": null, - "level": "note", - "spans": [], - "children": [], - "rendered": null - } - ], - "rendered": "error[E0053]: method `next` has an incompatible type for trait\n --> compiler/ty/list_iter.rs:52:5\n |\n52 | fn next(&self) -> Option<&'list ty::Ref> {\n | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ types differ in mutability\n |\n = note: expected type `fn(&mut ty::list_iter::ListIterator<'list, M>) -> std::option::Option<&ty::Ref>`\n found type `fn(&ty::list_iter::ListIterator<'list, M>) -> std::option::Option<&'list ty::Ref>`\n\n" -} diff --git a/editors/code/src/test/fixtures/rust-diagnostics/error/E0061.json b/editors/code/src/test/fixtures/rust-diagnostics/error/E0061.json deleted file mode 100644 index 3154d1098..000000000 --- a/editors/code/src/test/fixtures/rust-diagnostics/error/E0061.json +++ /dev/null @@ -1,114 +0,0 @@ -{ - "message": "this function takes 2 parameters but 3 parameters were supplied", - "code": { - "code": "E0061", - "explanation": "\nThe number of arguments passed to a function must match the number of arguments\nspecified in the function signature.\n\nFor example, a function like:\n\n```\nfn f(a: u16, b: &str) {}\n```\n\nMust always be called with exactly two arguments, e.g., `f(2, \"test\")`.\n\nNote that Rust does not have a notion of optional function arguments or\nvariadic functions (except for its C-FFI).\n" - }, - "level": "error", - "spans": [ - { - "file_name": "compiler/ty/select.rs", - "byte_start": 8787, - "byte_end": 9241, - "line_start": 219, - "line_end": 231, - "column_start": 5, - "column_end": 6, - "is_primary": false, - "text": [ - { - "text": " pub fn add_evidence(", - "highlight_start": 5, - "highlight_end": 25 - }, - { - "text": " &mut self,", - "highlight_start": 1, - "highlight_end": 19 - }, - { - "text": " target_poly: &ty::Ref,", - "highlight_start": 1, - "highlight_end": 41 - }, - { - "text": " evidence_poly: &ty::Ref,", - "highlight_start": 1, - "highlight_end": 43 - }, - { - "text": " ) {", - "highlight_start": 1, - "highlight_end": 8 - }, - { - "text": " match target_poly {", - "highlight_start": 1, - "highlight_end": 28 - }, - { - "text": " ty::Ref::Var(tvar, _) => self.add_var_evidence(tvar, evidence_poly),", - "highlight_start": 1, - "highlight_end": 81 - }, - { - "text": " ty::Ref::Fixed(target_ty) => {", - "highlight_start": 1, - "highlight_end": 43 - }, - { - "text": " let evidence_ty = evidence_poly.resolve_to_ty();", - "highlight_start": 1, - "highlight_end": 65 - }, - { - "text": " self.add_evidence_ty(target_ty, evidence_poly, evidence_ty)", - "highlight_start": 1, - "highlight_end": 76 - }, - { - "text": " }", - "highlight_start": 1, - "highlight_end": 14 - }, - { - "text": " }", - "highlight_start": 1, - "highlight_end": 10 - }, - { - "text": " }", - "highlight_start": 1, - "highlight_end": 6 - } - ], - "label": "defined here", - "suggested_replacement": null, - "suggestion_applicability": null, - "expansion": null - }, - { - "file_name": "compiler/ty/select.rs", - "byte_start": 4045, - "byte_end": 4057, - "line_start": 104, - "line_end": 104, - "column_start": 18, - "column_end": 30, - "is_primary": true, - "text": [ - { - "text": " self.add_evidence(target_fixed, evidence_fixed, false);", - "highlight_start": 18, - "highlight_end": 30 - } - ], - "label": "expected 2 parameters", - "suggested_replacement": null, - "suggestion_applicability": null, - "expansion": null - } - ], - "children": [], - "rendered": "error[E0061]: this function takes 2 parameters but 3 parameters were supplied\n --> compiler/ty/select.rs:104:18\n |\n104 | self.add_evidence(target_fixed, evidence_fixed, false);\n | ^^^^^^^^^^^^ expected 2 parameters\n...\n219 | / pub fn add_evidence(\n220 | | &mut self,\n221 | | target_poly: &ty::Ref,\n222 | | evidence_poly: &ty::Ref,\n... |\n230 | | }\n231 | | }\n | |_____- defined here\n\n" -} diff --git a/editors/code/src/test/fixtures/rust-diagnostics/error/E0277.json b/editors/code/src/test/fixtures/rust-diagnostics/error/E0277.json deleted file mode 100644 index bfef33c7d..000000000 --- a/editors/code/src/test/fixtures/rust-diagnostics/error/E0277.json +++ /dev/null @@ -1,261 +0,0 @@ -{ - "rendered": "error[E0277]: can't compare `{integer}` with `&str`\n --> src/main.rs:2:5\n |\n2 | assert_eq!(1, \"love\");\n | ^^^^^^^^^^^^^^^^^^^^^^ no implementation for `{integer} == &str`\n |\n = help: the trait `std::cmp::PartialEq<&str>` is not implemented for `{integer}`\n = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)\n\n", - "children": [ - { - "children": [], - "code": null, - "level": "help", - "message": "the trait `std::cmp::PartialEq<&str>` is not implemented for `{integer}`", - "rendered": null, - "spans": [] - } - ], - "code": { - "code": "E0277", - "explanation": "\nYou tried to use a type which doesn't implement some trait in a place which\nexpected that trait. Erroneous code example:\n\n```compile_fail,E0277\n// here we declare the Foo trait with a bar method\ntrait Foo {\n fn bar(&self);\n}\n\n// we now declare a function which takes an object implementing the Foo trait\nfn some_func(foo: T) {\n foo.bar();\n}\n\nfn main() {\n // we now call the method with the i32 type, which doesn't implement\n // the Foo trait\n some_func(5i32); // error: the trait bound `i32 : Foo` is not satisfied\n}\n```\n\nIn order to fix this error, verify that the type you're using does implement\nthe trait. Example:\n\n```\ntrait Foo {\n fn bar(&self);\n}\n\nfn some_func(foo: T) {\n foo.bar(); // we can now use this method since i32 implements the\n // Foo trait\n}\n\n// we implement the trait on the i32 type\nimpl Foo for i32 {\n fn bar(&self) {}\n}\n\nfn main() {\n some_func(5i32); // ok!\n}\n```\n\nOr in a generic context, an erroneous code example would look like:\n\n```compile_fail,E0277\nfn some_func(foo: T) {\n println!(\"{:?}\", foo); // error: the trait `core::fmt::Debug` is not\n // implemented for the type `T`\n}\n\nfn main() {\n // We now call the method with the i32 type,\n // which *does* implement the Debug trait.\n some_func(5i32);\n}\n```\n\nNote that the error here is in the definition of the generic function: Although\nwe only call it with a parameter that does implement `Debug`, the compiler\nstill rejects the function: It must work with all possible input types. In\norder to make this example compile, we need to restrict the generic type we're\naccepting:\n\n```\nuse std::fmt;\n\n// Restrict the input type to types that implement Debug.\nfn some_func(foo: T) {\n println!(\"{:?}\", foo);\n}\n\nfn main() {\n // Calling the method is still fine, as i32 implements Debug.\n some_func(5i32);\n\n // This would fail to compile now:\n // struct WithoutDebug;\n // some_func(WithoutDebug);\n}\n```\n\nRust only looks at the signature of the called function, as such it must\nalready specify all requirements that will be used for every type parameter.\n" - }, - "level": "error", - "message": "can't compare `{integer}` with `&str`", - "spans": [ - { - "byte_end": 155, - "byte_start": 153, - "column_end": 33, - "column_start": 31, - "expansion": { - "def_site_span": { - "byte_end": 940, - "byte_start": 0, - "column_end": 6, - "column_start": 1, - "expansion": null, - "file_name": "<::core::macros::assert_eq macros>", - "is_primary": false, - "label": null, - "line_end": 36, - "line_start": 1, - "suggested_replacement": null, - "suggestion_applicability": null, - "text": [ - { - "highlight_end": 35, - "highlight_start": 1, - "text": "($ left : expr, $ right : expr) =>" - }, - { - "highlight_end": 3, - "highlight_start": 1, - "text": "({" - }, - { - "highlight_end": 33, - "highlight_start": 1, - "text": " match (& $ left, & $ right)" - }, - { - "highlight_end": 7, - "highlight_start": 1, - "text": " {" - }, - { - "highlight_end": 34, - "highlight_start": 1, - "text": " (left_val, right_val) =>" - }, - { - "highlight_end": 11, - "highlight_start": 1, - "text": " {" - }, - { - "highlight_end": 46, - "highlight_start": 1, - "text": " if ! (* left_val == * right_val)" - }, - { - "highlight_end": 15, - "highlight_start": 1, - "text": " {" - }, - { - "highlight_end": 25, - "highlight_start": 1, - "text": " panic !" - }, - { - "highlight_end": 57, - "highlight_start": 1, - "text": " (r#\"assertion failed: `(left == right)`" - }, - { - "highlight_end": 16, - "highlight_start": 1, - "text": " left: `{:?}`," - }, - { - "highlight_end": 18, - "highlight_start": 1, - "text": " right: `{:?}`\"#," - }, - { - "highlight_end": 47, - "highlight_start": 1, - "text": " & * left_val, & * right_val)" - }, - { - "highlight_end": 15, - "highlight_start": 1, - "text": " }" - }, - { - "highlight_end": 11, - "highlight_start": 1, - "text": " }" - }, - { - "highlight_end": 7, - "highlight_start": 1, - "text": " }" - }, - { - "highlight_end": 42, - "highlight_start": 1, - "text": " }) ; ($ left : expr, $ right : expr,) =>" - }, - { - "highlight_end": 49, - "highlight_start": 1, - "text": "({ $ crate :: assert_eq ! ($ left, $ right) }) ;" - }, - { - "highlight_end": 53, - "highlight_start": 1, - "text": "($ left : expr, $ right : expr, $ ($ arg : tt) +) =>" - }, - { - "highlight_end": 3, - "highlight_start": 1, - "text": "({" - }, - { - "highlight_end": 37, - "highlight_start": 1, - "text": " match (& ($ left), & ($ right))" - }, - { - "highlight_end": 7, - "highlight_start": 1, - "text": " {" - }, - { - "highlight_end": 34, - "highlight_start": 1, - "text": " (left_val, right_val) =>" - }, - { - "highlight_end": 11, - "highlight_start": 1, - "text": " {" - }, - { - "highlight_end": 46, - "highlight_start": 1, - "text": " if ! (* left_val == * right_val)" - }, - { - "highlight_end": 15, - "highlight_start": 1, - "text": " {" - }, - { - "highlight_end": 25, - "highlight_start": 1, - "text": " panic !" - }, - { - "highlight_end": 57, - "highlight_start": 1, - "text": " (r#\"assertion failed: `(left == right)`" - }, - { - "highlight_end": 16, - "highlight_start": 1, - "text": " left: `{:?}`," - }, - { - "highlight_end": 22, - "highlight_start": 1, - "text": " right: `{:?}`: {}\"#," - }, - { - "highlight_end": 72, - "highlight_start": 1, - "text": " & * left_val, & * right_val, $ crate :: format_args !" - }, - { - "highlight_end": 33, - "highlight_start": 1, - "text": " ($ ($ arg) +))" - }, - { - "highlight_end": 15, - "highlight_start": 1, - "text": " }" - }, - { - "highlight_end": 11, - "highlight_start": 1, - "text": " }" - }, - { - "highlight_end": 7, - "highlight_start": 1, - "text": " }" - }, - { - "highlight_end": 6, - "highlight_start": 1, - "text": " }) ;" - } - ] - }, - "macro_decl_name": "assert_eq!", - "span": { - "byte_end": 38, - "byte_start": 16, - "column_end": 27, - "column_start": 5, - "expansion": null, - "file_name": "src/main.rs", - "is_primary": false, - "label": null, - "line_end": 2, - "line_start": 2, - "suggested_replacement": null, - "suggestion_applicability": null, - "text": [ - { - "highlight_end": 27, - "highlight_start": 5, - "text": " assert_eq!(1, \"love\");" - } - ] - } - }, - "file_name": "<::core::macros::assert_eq macros>", - "is_primary": true, - "label": "no implementation for `{integer} == &str`", - "line_end": 7, - "line_start": 7, - "suggested_replacement": null, - "suggestion_applicability": null, - "text": [ - { - "highlight_end": 33, - "highlight_start": 31, - "text": " if ! (* left_val == * right_val)" - } - ] - } - ] -} diff --git a/editors/code/src/test/fixtures/rust-diagnostics/error/E0308.json b/editors/code/src/test/fixtures/rust-diagnostics/error/E0308.json deleted file mode 100644 index fb23824a3..000000000 --- a/editors/code/src/test/fixtures/rust-diagnostics/error/E0308.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "message": "mismatched types", - "code": { - "code": "E0308", - "explanation": "\nThis error occurs when the compiler was unable to infer the concrete type of a\nvariable. It can occur for several cases, the most common of which is a\nmismatch in the expected type that the compiler inferred for a variable's\ninitializing expression, and the actual type explicitly assigned to the\nvariable.\n\nFor example:\n\n```compile_fail,E0308\nlet x: i32 = \"I am not a number!\";\n// ~~~ ~~~~~~~~~~~~~~~~~~~~\n// | |\n// | initializing expression;\n// | compiler infers type `&str`\n// |\n// type `i32` assigned to variable `x`\n```\n" - }, - "level": "error", - "spans": [ - { - "file_name": "runtime/compiler_support.rs", - "byte_start": 1589, - "byte_end": 1594, - "line_start": 48, - "line_end": 48, - "column_start": 65, - "column_end": 70, - "is_primary": true, - "text": [ - { - "text": " let layout = alloc::Layout::from_size_align_unchecked(size, align);", - "highlight_start": 65, - "highlight_end": 70 - } - ], - "label": "expected usize, found u32", - "suggested_replacement": null, - "suggestion_applicability": null, - "expansion": null - } - ], - "children": [], - "rendered": "error[E0308]: mismatched types\n --> runtime/compiler_support.rs:48:65\n |\n48 | let layout = alloc::Layout::from_size_align_unchecked(size, align);\n | ^^^^^ expected usize, found u32\n\n" -} diff --git a/editors/code/src/test/fixtures/rust-diagnostics/warning/unused_variables.json b/editors/code/src/test/fixtures/rust-diagnostics/warning/unused_variables.json deleted file mode 100644 index d1e2be722..000000000 --- a/editors/code/src/test/fixtures/rust-diagnostics/warning/unused_variables.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "message": "unused variable: `foo`", - "code": { - "code": "unused_variables", - "explanation": null - }, - "level": "warning", - "spans": [ - { - "file_name": "driver/subcommand/repl.rs", - "byte_start": 9228, - "byte_end": 9231, - "line_start": 291, - "line_end": 291, - "column_start": 9, - "column_end": 12, - "is_primary": true, - "text": [ - { - "text": " let foo = 42;", - "highlight_start": 9, - "highlight_end": 12 - } - ], - "label": null, - "suggested_replacement": null, - "suggestion_applicability": null, - "expansion": null - } - ], - "children": [ - { - "message": "#[warn(unused_variables)] on by default", - "code": null, - "level": "note", - "spans": [], - "children": [], - "rendered": null - }, - { - "message": "consider prefixing with an underscore", - "code": null, - "level": "help", - "spans": [ - { - "file_name": "driver/subcommand/repl.rs", - "byte_start": 9228, - "byte_end": 9231, - "line_start": 291, - "line_end": 291, - "column_start": 9, - "column_end": 12, - "is_primary": true, - "text": [ - { - "text": " let foo = 42;", - "highlight_start": 9, - "highlight_end": 12 - } - ], - "label": null, - "suggested_replacement": "_foo", - "suggestion_applicability": "MachineApplicable", - "expansion": null - } - ], - "children": [], - "rendered": null - } - ], - "rendered": "warning: unused variable: `foo`\n --> driver/subcommand/repl.rs:291:9\n |\n291 | let foo = 42;\n | ^^^ help: consider prefixing with an underscore: `_foo`\n |\n = note: #[warn(unused_variables)] on by default\n\n" -} diff --git a/editors/code/src/test/utils/diagnotics/SuggestedFix.test.ts b/editors/code/src/test/utils/diagnotics/SuggestedFix.test.ts deleted file mode 100644 index 2b25eb705..000000000 --- a/editors/code/src/test/utils/diagnotics/SuggestedFix.test.ts +++ /dev/null @@ -1,134 +0,0 @@ -import * as assert from 'assert'; -import * as vscode from 'vscode'; - -import { SuggestionApplicability } from '../../../utils/diagnostics/rust'; -import SuggestedFix from '../../../utils/diagnostics/SuggestedFix'; - -const location1 = new vscode.Location( - vscode.Uri.file('/file/1'), - new vscode.Range(new vscode.Position(1, 2), new vscode.Position(3, 4)), -); - -const location2 = new vscode.Location( - vscode.Uri.file('/file/2'), - new vscode.Range(new vscode.Position(5, 6), new vscode.Position(7, 8)), -); - -describe('SuggestedFix', () => { - describe('isEqual', () => { - it('should treat identical instances as equal', () => { - const suggestion1 = new SuggestedFix( - 'Replace me!', - location1, - 'With this!', - ); - - const suggestion2 = new SuggestedFix( - 'Replace me!', - location1, - 'With this!', - ); - - assert(suggestion1.isEqual(suggestion2)); - }); - - it('should treat instances with different titles as inequal', () => { - const suggestion1 = new SuggestedFix( - 'Replace me!', - location1, - 'With this!', - ); - - const suggestion2 = new SuggestedFix( - 'Not the same title!', - location1, - 'With this!', - ); - - assert(!suggestion1.isEqual(suggestion2)); - }); - - it('should treat instances with different replacements as inequal', () => { - const suggestion1 = new SuggestedFix( - 'Replace me!', - location1, - 'With this!', - ); - - const suggestion2 = new SuggestedFix( - 'Replace me!', - location1, - 'With something else!', - ); - - assert(!suggestion1.isEqual(suggestion2)); - }); - - it('should treat instances with different locations as inequal', () => { - const suggestion1 = new SuggestedFix( - 'Replace me!', - location1, - 'With this!', - ); - - const suggestion2 = new SuggestedFix( - 'Replace me!', - location2, - 'With this!', - ); - - assert(!suggestion1.isEqual(suggestion2)); - }); - - it('should treat instances with different applicability as inequal', () => { - const suggestion1 = new SuggestedFix( - 'Replace me!', - location1, - 'With this!', - SuggestionApplicability.MachineApplicable, - ); - - const suggestion2 = new SuggestedFix( - 'Replace me!', - location2, - 'With this!', - SuggestionApplicability.HasPlaceholders, - ); - - assert(!suggestion1.isEqual(suggestion2)); - }); - }); - - describe('toCodeAction', () => { - it('should map a simple suggestion', () => { - const suggestion = new SuggestedFix( - 'Replace me!', - location1, - 'With this!', - ); - - const codeAction = suggestion.toCodeAction(); - assert.strictEqual(codeAction.kind, vscode.CodeActionKind.QuickFix); - assert.strictEqual(codeAction.title, 'Replace me!'); - assert.strictEqual(codeAction.isPreferred, false); - - const edit = codeAction.edit; - if (!edit) { - assert.fail('Code Action edit unexpectedly missing'); - return; - } - - const editEntries = edit.entries(); - assert.strictEqual(editEntries.length, 1); - - const [[editUri, textEdits]] = editEntries; - assert.strictEqual(editUri.toString(), location1.uri.toString()); - - assert.strictEqual(textEdits.length, 1); - const [textEdit] = textEdits; - - assert(textEdit.range.isEqual(location1.range)); - assert.strictEqual(textEdit.newText, 'With this!'); - }); - }); -}); diff --git a/editors/code/src/test/utils/diagnotics/SuggestedFixCollection.test.ts b/editors/code/src/test/utils/diagnotics/SuggestedFixCollection.test.ts deleted file mode 100644 index ef09013f4..000000000 --- a/editors/code/src/test/utils/diagnotics/SuggestedFixCollection.test.ts +++ /dev/null @@ -1,127 +0,0 @@ -import * as assert from 'assert'; -import * as vscode from 'vscode'; - -import SuggestedFix from '../../../utils/diagnostics/SuggestedFix'; -import SuggestedFixCollection from '../../../utils/diagnostics/SuggestedFixCollection'; - -const uri1 = vscode.Uri.file('/file/1'); -const uri2 = vscode.Uri.file('/file/2'); - -const mockDocument1 = ({ - uri: uri1, -} as unknown) as vscode.TextDocument; - -const mockDocument2 = ({ - uri: uri2, -} as unknown) as vscode.TextDocument; - -const range1 = new vscode.Range( - new vscode.Position(1, 2), - new vscode.Position(3, 4), -); -const range2 = new vscode.Range( - new vscode.Position(5, 6), - new vscode.Position(7, 8), -); - -const diagnostic1 = new vscode.Diagnostic(range1, 'First diagnostic'); -const diagnostic2 = new vscode.Diagnostic(range2, 'Second diagnostic'); - -// This is a mutable object so return a fresh instance every time -function suggestion1(): SuggestedFix { - return new SuggestedFix( - 'Replace me!', - new vscode.Location(uri1, range1), - 'With this!', - ); -} - -describe('SuggestedFixCollection', () => { - it('should add a suggestion then return it as a code action', () => { - const suggestedFixes = new SuggestedFixCollection(); - suggestedFixes.addSuggestedFixForDiagnostic(suggestion1(), diagnostic1); - - // Specify the document and range that exactly matches - const codeActions = suggestedFixes.provideCodeActions( - mockDocument1, - range1, - ); - - assert.strictEqual(codeActions.length, 1); - const [codeAction] = codeActions; - assert.strictEqual(codeAction.title, suggestion1().title); - - const { diagnostics } = codeAction; - if (!diagnostics) { - assert.fail('Diagnostics unexpectedly missing'); - return; - } - - assert.strictEqual(diagnostics.length, 1); - assert.strictEqual(diagnostics[0], diagnostic1); - }); - - it('should not return code actions for different ranges', () => { - const suggestedFixes = new SuggestedFixCollection(); - suggestedFixes.addSuggestedFixForDiagnostic(suggestion1(), diagnostic1); - - const codeActions = suggestedFixes.provideCodeActions( - mockDocument1, - range2, - ); - - assert(!codeActions || codeActions.length === 0); - }); - - it('should not return code actions for different documents', () => { - const suggestedFixes = new SuggestedFixCollection(); - suggestedFixes.addSuggestedFixForDiagnostic(suggestion1(), diagnostic1); - - const codeActions = suggestedFixes.provideCodeActions( - mockDocument2, - range1, - ); - - assert(!codeActions || codeActions.length === 0); - }); - - it('should not return code actions that have been cleared', () => { - const suggestedFixes = new SuggestedFixCollection(); - suggestedFixes.addSuggestedFixForDiagnostic(suggestion1(), diagnostic1); - suggestedFixes.clear(); - - const codeActions = suggestedFixes.provideCodeActions( - mockDocument1, - range1, - ); - - assert(!codeActions || codeActions.length === 0); - }); - - it('should merge identical suggestions together', () => { - const suggestedFixes = new SuggestedFixCollection(); - - // Add the same suggestion for two diagnostics - suggestedFixes.addSuggestedFixForDiagnostic(suggestion1(), diagnostic1); - suggestedFixes.addSuggestedFixForDiagnostic(suggestion1(), diagnostic2); - - const codeActions = suggestedFixes.provideCodeActions( - mockDocument1, - range1, - ); - - assert.strictEqual(codeActions.length, 1); - const [codeAction] = codeActions; - const { diagnostics } = codeAction; - - if (!diagnostics) { - assert.fail('Diagnostics unexpectedly missing'); - return; - } - - // We should be associated with both diagnostics - assert.strictEqual(diagnostics.length, 2); - assert.strictEqual(diagnostics[0], diagnostic1); - assert.strictEqual(diagnostics[1], diagnostic2); - }); -}); diff --git a/editors/code/src/test/utils/diagnotics/rust.test.ts b/editors/code/src/test/utils/diagnotics/rust.test.ts deleted file mode 100644 index 358325cc8..000000000 --- a/editors/code/src/test/utils/diagnotics/rust.test.ts +++ /dev/null @@ -1,236 +0,0 @@ -import * as assert from 'assert'; -import * as fs from 'fs'; -import * as vscode from 'vscode'; - -import { - MappedRustDiagnostic, - mapRustDiagnosticToVsCode, - RustDiagnostic, - SuggestionApplicability, -} from '../../../utils/diagnostics/rust'; - -function loadDiagnosticFixture(name: string): RustDiagnostic { - const jsonText = fs - .readFileSync( - // We're actually in our JavaScript output directory, climb out - `${__dirname}/../../../../src/test/fixtures/rust-diagnostics/${name}.json`, - ) - .toString(); - - return JSON.parse(jsonText); -} - -function mapFixtureToVsCode(name: string): MappedRustDiagnostic { - const rd = loadDiagnosticFixture(name); - const mapResult = mapRustDiagnosticToVsCode(rd); - - if (!mapResult) { - return assert.fail('Mapping unexpectedly failed'); - } - return mapResult; -} - -describe('mapRustDiagnosticToVsCode', () => { - it('should map an incompatible type for trait error', () => { - const { diagnostic, suggestedFixes } = mapFixtureToVsCode( - 'error/E0053', - ); - - assert.strictEqual( - diagnostic.severity, - vscode.DiagnosticSeverity.Error, - ); - assert.strictEqual(diagnostic.source, 'rustc'); - assert.strictEqual( - diagnostic.message, - [ - `method \`next\` has an incompatible type for trait`, - `expected type \`fn(&mut ty::list_iter::ListIterator<'list, M>) -> std::option::Option<&ty::Ref>\``, - ` found type \`fn(&ty::list_iter::ListIterator<'list, M>) -> std::option::Option<&'list ty::Ref>\``, - ].join('\n'), - ); - assert.strictEqual(diagnostic.code, 'E0053'); - assert.deepStrictEqual(diagnostic.tags, []); - - // No related information - assert.deepStrictEqual(diagnostic.relatedInformation, []); - - // There are no suggested fixes - assert.strictEqual(suggestedFixes.length, 0); - }); - - it('should map an unused variable warning', () => { - const { diagnostic, suggestedFixes } = mapFixtureToVsCode( - 'warning/unused_variables', - ); - - assert.strictEqual( - diagnostic.severity, - vscode.DiagnosticSeverity.Warning, - ); - assert.strictEqual( - diagnostic.message, - [ - 'unused variable: `foo`', - '#[warn(unused_variables)] on by default', - ].join('\n'), - ); - assert.strictEqual(diagnostic.code, 'unused_variables'); - assert.strictEqual(diagnostic.source, 'rustc'); - assert.deepStrictEqual(diagnostic.tags, [ - vscode.DiagnosticTag.Unnecessary, - ]); - - // No related information - assert.deepStrictEqual(diagnostic.relatedInformation, []); - - // One suggested fix available to prefix the variable - assert.strictEqual(suggestedFixes.length, 1); - const [suggestedFix] = suggestedFixes; - assert.strictEqual( - suggestedFix.title, - 'consider prefixing with an underscore: `_foo`', - ); - assert.strictEqual( - suggestedFix.applicability, - SuggestionApplicability.MachineApplicable, - ); - }); - - it('should map a wrong number of parameters error', () => { - const { diagnostic, suggestedFixes } = mapFixtureToVsCode( - 'error/E0061', - ); - - assert.strictEqual( - diagnostic.severity, - vscode.DiagnosticSeverity.Error, - ); - assert.strictEqual( - diagnostic.message, - [ - 'this function takes 2 parameters but 3 parameters were supplied', - 'expected 2 parameters', - ].join('\n'), - ); - assert.strictEqual(diagnostic.code, 'E0061'); - assert.strictEqual(diagnostic.source, 'rustc'); - assert.deepStrictEqual(diagnostic.tags, []); - - // One related information for the original definition - const relatedInformation = diagnostic.relatedInformation; - if (!relatedInformation) { - assert.fail('Related information unexpectedly undefined'); - return; - } - assert.strictEqual(relatedInformation.length, 1); - const [related] = relatedInformation; - assert.strictEqual(related.message, 'defined here'); - - // There are no suggested fixes - assert.strictEqual(suggestedFixes.length, 0); - }); - - it('should map a Clippy copy pass by ref warning', () => { - const { diagnostic, suggestedFixes } = mapFixtureToVsCode( - 'clippy/trivially_copy_pass_by_ref', - ); - - assert.strictEqual( - diagnostic.severity, - vscode.DiagnosticSeverity.Warning, - ); - assert.strictEqual(diagnostic.source, 'clippy'); - assert.strictEqual( - diagnostic.message, - [ - 'this argument is passed by reference, but would be more efficient if passed by value', - '#[warn(clippy::trivially_copy_pass_by_ref)] implied by #[warn(clippy::all)]', - 'for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#trivially_copy_pass_by_ref', - ].join('\n'), - ); - assert.strictEqual(diagnostic.code, 'trivially_copy_pass_by_ref'); - assert.deepStrictEqual(diagnostic.tags, []); - - // One related information for the lint definition - const relatedInformation = diagnostic.relatedInformation; - if (!relatedInformation) { - assert.fail('Related information unexpectedly undefined'); - return; - } - assert.strictEqual(relatedInformation.length, 1); - const [related] = relatedInformation; - assert.strictEqual(related.message, 'lint level defined here'); - - // One suggested fix to pass by value - assert.strictEqual(suggestedFixes.length, 1); - const [suggestedFix] = suggestedFixes; - assert.strictEqual( - suggestedFix.title, - 'consider passing by value instead: `self`', - ); - // Clippy does not mark this with any applicability - assert.strictEqual( - suggestedFix.applicability, - SuggestionApplicability.Unspecified, - ); - }); - - it('should map a mismatched type error', () => { - const { diagnostic, suggestedFixes } = mapFixtureToVsCode( - 'error/E0308', - ); - - assert.strictEqual( - diagnostic.severity, - vscode.DiagnosticSeverity.Error, - ); - assert.strictEqual( - diagnostic.message, - ['mismatched types', 'expected usize, found u32'].join('\n'), - ); - assert.strictEqual(diagnostic.code, 'E0308'); - assert.strictEqual(diagnostic.source, 'rustc'); - assert.deepStrictEqual(diagnostic.tags, []); - - // No related information - assert.deepStrictEqual(diagnostic.relatedInformation, []); - - // There are no suggested fixes - assert.strictEqual(suggestedFixes.length, 0); - }); - - it('should map a macro invocation location to normal file path', () => { - const { location, diagnostic, suggestedFixes } = mapFixtureToVsCode( - 'error/E0277', - ); - - assert.strictEqual( - diagnostic.severity, - vscode.DiagnosticSeverity.Error, - ); - assert.strictEqual( - diagnostic.message, - [ - "can't compare `{integer}` with `&str`", - 'the trait `std::cmp::PartialEq<&str>` is not implemented for `{integer}`', - ].join('\n'), - ); - assert.strictEqual(diagnostic.code, 'E0277'); - assert.strictEqual(diagnostic.source, 'rustc'); - assert.deepStrictEqual(diagnostic.tags, []); - - // No related information - assert.deepStrictEqual(diagnostic.relatedInformation, []); - - // There are no suggested fixes - assert.strictEqual(suggestedFixes.length, 0); - - // The file url should be normal file - // Ignore the first part because it depends on vs workspace location - assert.strictEqual( - location.uri.path.substr(-'src/main.rs'.length), - 'src/main.rs', - ); - }); -}); diff --git a/editors/code/src/test/utils/diagnotics/vscode.test.ts b/editors/code/src/test/utils/diagnotics/vscode.test.ts deleted file mode 100644 index 4944dd032..000000000 --- a/editors/code/src/test/utils/diagnotics/vscode.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import * as assert from 'assert'; -import * as vscode from 'vscode'; - -import { areDiagnosticsEqual } from '../../../utils/diagnostics/vscode'; - -const range1 = new vscode.Range( - new vscode.Position(1, 2), - new vscode.Position(3, 4), -); - -const range2 = new vscode.Range( - new vscode.Position(5, 6), - new vscode.Position(7, 8), -); - -describe('areDiagnosticsEqual', () => { - it('should treat identical diagnostics as equal', () => { - const diagnostic1 = new vscode.Diagnostic( - range1, - 'Hello, world!', - vscode.DiagnosticSeverity.Error, - ); - - const diagnostic2 = new vscode.Diagnostic( - range1, - 'Hello, world!', - vscode.DiagnosticSeverity.Error, - ); - - assert(areDiagnosticsEqual(diagnostic1, diagnostic2)); - }); - - it('should treat diagnostics with different sources as inequal', () => { - const diagnostic1 = new vscode.Diagnostic( - range1, - 'Hello, world!', - vscode.DiagnosticSeverity.Error, - ); - diagnostic1.source = 'rustc'; - - const diagnostic2 = new vscode.Diagnostic( - range1, - 'Hello, world!', - vscode.DiagnosticSeverity.Error, - ); - diagnostic2.source = 'clippy'; - - assert(!areDiagnosticsEqual(diagnostic1, diagnostic2)); - }); - - it('should treat diagnostics with different ranges as inequal', () => { - const diagnostic1 = new vscode.Diagnostic( - range1, - 'Hello, world!', - vscode.DiagnosticSeverity.Error, - ); - - const diagnostic2 = new vscode.Diagnostic( - range2, - 'Hello, world!', - vscode.DiagnosticSeverity.Error, - ); - - assert(!areDiagnosticsEqual(diagnostic1, diagnostic2)); - }); - - it('should treat diagnostics with different messages as inequal', () => { - const diagnostic1 = new vscode.Diagnostic( - range1, - 'Hello, world!', - vscode.DiagnosticSeverity.Error, - ); - - const diagnostic2 = new vscode.Diagnostic( - range1, - 'Goodbye!, world!', - vscode.DiagnosticSeverity.Error, - ); - - assert(!areDiagnosticsEqual(diagnostic1, diagnostic2)); - }); - - it('should treat diagnostics with different severities as inequal', () => { - const diagnostic1 = new vscode.Diagnostic( - range1, - 'Hello, world!', - vscode.DiagnosticSeverity.Warning, - ); - - const diagnostic2 = new vscode.Diagnostic( - range1, - 'Hello, world!', - vscode.DiagnosticSeverity.Error, - ); - - assert(!areDiagnosticsEqual(diagnostic1, diagnostic2)); - }); -}); diff --git a/editors/code/src/utils/diagnostics/SuggestedFix.ts b/editors/code/src/utils/diagnostics/SuggestedFix.ts deleted file mode 100644 index 6e660bb61..000000000 --- a/editors/code/src/utils/diagnostics/SuggestedFix.ts +++ /dev/null @@ -1,67 +0,0 @@ -import * as vscode from 'vscode'; - -import { SuggestionApplicability } from './rust'; - -/** - * Model object for text replacements suggested by the Rust compiler - * - * This is an intermediate form between the raw `rustc` JSON and a - * `vscode.CodeAction`. It's optimised for the use-cases of - * `SuggestedFixCollection`. - */ -export default class SuggestedFix { - public readonly title: string; - public readonly location: vscode.Location; - public readonly replacement: string; - public readonly applicability: SuggestionApplicability; - - /** - * Diagnostics this suggested fix could resolve - */ - public diagnostics: vscode.Diagnostic[]; - - constructor( - title: string, - location: vscode.Location, - replacement: string, - applicability: SuggestionApplicability = SuggestionApplicability.Unspecified, - ) { - this.title = title; - this.location = location; - this.replacement = replacement; - this.applicability = applicability; - this.diagnostics = []; - } - - /** - * Determines if this suggested fix is equivalent to another instance - */ - public isEqual(other: SuggestedFix): boolean { - return ( - this.title === other.title && - this.location.range.isEqual(other.location.range) && - this.replacement === other.replacement && - this.applicability === other.applicability - ); - } - - /** - * Converts this suggested fix to a VS Code Quick Fix code action - */ - public toCodeAction(): vscode.CodeAction { - const codeAction = new vscode.CodeAction( - this.title, - vscode.CodeActionKind.QuickFix, - ); - - const edit = new vscode.WorkspaceEdit(); - edit.replace(this.location.uri, this.location.range, this.replacement); - codeAction.edit = edit; - - codeAction.isPreferred = - this.applicability === SuggestionApplicability.MachineApplicable; - - codeAction.diagnostics = [...this.diagnostics]; - return codeAction; - } -} diff --git a/editors/code/src/utils/diagnostics/SuggestedFixCollection.ts b/editors/code/src/utils/diagnostics/SuggestedFixCollection.ts deleted file mode 100644 index 57c9856cf..000000000 --- a/editors/code/src/utils/diagnostics/SuggestedFixCollection.ts +++ /dev/null @@ -1,77 +0,0 @@ -import * as vscode from 'vscode'; -import SuggestedFix from './SuggestedFix'; - -/** - * Collection of suggested fixes across multiple documents - * - * This stores `SuggestedFix` model objects and returns them via the - * `vscode.CodeActionProvider` interface. - */ -export default class SuggestedFixCollection - implements vscode.CodeActionProvider { - public static PROVIDED_CODE_ACTION_KINDS = [vscode.CodeActionKind.QuickFix]; - - /** - * Map of document URI strings to suggested fixes - */ - private suggestedFixes: Map; - - constructor() { - this.suggestedFixes = new Map(); - } - - /** - * Clears all suggested fixes across all documents - */ - public clear(): void { - this.suggestedFixes = new Map(); - } - - /** - * Adds a suggested fix for the given diagnostic - * - * Some suggested fixes will appear in multiple diagnostics. For example, - * forgetting a `mut` on a variable will suggest changing the delaration on - * every mutable usage site. If the suggested fix has already been added - * this method will instead associate the existing fix with the new - * diagnostic. - */ - public addSuggestedFixForDiagnostic( - suggestedFix: SuggestedFix, - diagnostic: vscode.Diagnostic, - ): void { - const fileUriString = suggestedFix.location.uri.toString(); - const fileSuggestions = this.suggestedFixes.get(fileUriString) || []; - - const existingSuggestion = fileSuggestions.find(s => - s.isEqual(suggestedFix), - ); - - if (existingSuggestion) { - // The existing suggestion also applies to this new diagnostic - existingSuggestion.diagnostics.push(diagnostic); - } else { - // We haven't seen this suggestion before - suggestedFix.diagnostics.push(diagnostic); - fileSuggestions.push(suggestedFix); - } - - this.suggestedFixes.set(fileUriString, fileSuggestions); - } - - /** - * Filters suggested fixes by their document and range and converts them to - * code actions - */ - public provideCodeActions( - document: vscode.TextDocument, - range: vscode.Range, - ): vscode.CodeAction[] { - const documentUriString = document.uri.toString(); - - const suggestedFixes = this.suggestedFixes.get(documentUriString); - return (suggestedFixes || []) - .filter(({ location }) => location.range.intersection(range)) - .map(suggestedEdit => suggestedEdit.toCodeAction()); - } -} diff --git a/editors/code/src/utils/diagnostics/rust.ts b/editors/code/src/utils/diagnostics/rust.ts deleted file mode 100644 index 1f0c0d3e4..000000000 --- a/editors/code/src/utils/diagnostics/rust.ts +++ /dev/null @@ -1,299 +0,0 @@ -import * as path from 'path'; -import * as vscode from 'vscode'; - -import SuggestedFix from './SuggestedFix'; - -export enum SuggestionApplicability { - MachineApplicable = 'MachineApplicable', - HasPlaceholders = 'HasPlaceholders', - MaybeIncorrect = 'MaybeIncorrect', - Unspecified = 'Unspecified', -} - -export interface RustDiagnosticSpanMacroExpansion { - span: RustDiagnosticSpan; - macro_decl_name: string; - def_site_span?: RustDiagnosticSpan; -} - -// Reference: -// https://github.com/rust-lang/rust/blob/master/src/libsyntax/json.rs -export interface RustDiagnosticSpan { - line_start: number; - line_end: number; - column_start: number; - column_end: number; - is_primary: boolean; - file_name: string; - label?: string; - expansion?: RustDiagnosticSpanMacroExpansion; - suggested_replacement?: string; - suggestion_applicability?: SuggestionApplicability; -} - -export interface RustDiagnostic { - spans: RustDiagnosticSpan[]; - rendered: string; - message: string; - level: string; - code?: { - code: string; - }; - children: RustDiagnostic[]; -} - -export interface MappedRustDiagnostic { - location: vscode.Location; - diagnostic: vscode.Diagnostic; - suggestedFixes: SuggestedFix[]; -} - -interface MappedRustChildDiagnostic { - related?: vscode.DiagnosticRelatedInformation; - suggestedFix?: SuggestedFix; - messageLine?: string; -} - -/** - * Converts a Rust level string to a VsCode severity - */ -function mapLevelToSeverity(s: string): vscode.DiagnosticSeverity { - if (s === 'error') { - return vscode.DiagnosticSeverity.Error; - } - if (s.startsWith('warn')) { - return vscode.DiagnosticSeverity.Warning; - } - return vscode.DiagnosticSeverity.Information; -} - -/** - * Check whether a file name is from macro invocation - */ -function isFromMacro(fileName: string): boolean { - return fileName.startsWith('<') && fileName.endsWith('>'); -} - -/** - * Converts a Rust macro span to a VsCode location recursively - */ -function mapMacroSpanToLocation( - spanMacro: RustDiagnosticSpanMacroExpansion, -): vscode.Location | undefined { - if (!isFromMacro(spanMacro.span.file_name)) { - return mapSpanToLocation(spanMacro.span); - } - - if (spanMacro.span.expansion) { - return mapMacroSpanToLocation(spanMacro.span.expansion); - } - - return; -} - -/** - * Converts a Rust span to a VsCode location - */ -function mapSpanToLocation(span: RustDiagnosticSpan): vscode.Location { - if (isFromMacro(span.file_name) && span.expansion) { - const macroLoc = mapMacroSpanToLocation(span.expansion); - if (macroLoc) { - return macroLoc; - } - } - - const fileName = path.join(vscode.workspace.rootPath || '', span.file_name); - const fileUri = vscode.Uri.file(fileName); - - const range = new vscode.Range( - new vscode.Position(span.line_start - 1, span.column_start - 1), - new vscode.Position(span.line_end - 1, span.column_end - 1), - ); - - return new vscode.Location(fileUri, range); -} - -/** - * Converts a secondary Rust span to a VsCode related information - * - * If the span is unlabelled this will return `undefined`. - */ -function mapSecondarySpanToRelated( - span: RustDiagnosticSpan, -): vscode.DiagnosticRelatedInformation | undefined { - if (!span.label) { - // Nothing to label this with - return; - } - - const location = mapSpanToLocation(span); - return new vscode.DiagnosticRelatedInformation(location, span.label); -} - -/** - * Determines if diagnostic is related to unused code - */ -function isUnusedOrUnnecessary(rd: RustDiagnostic): boolean { - if (!rd.code) { - return false; - } - - return [ - 'dead_code', - 'unknown_lints', - 'unreachable_code', - 'unused_attributes', - 'unused_imports', - 'unused_macros', - 'unused_variables', - ].includes(rd.code.code); -} - -/** - * Determines if diagnostic is related to deprecated code - */ -function isDeprecated(rd: RustDiagnostic): boolean { - if (!rd.code) { - return false; - } - - return ['deprecated'].includes(rd.code.code); -} - -/** - * Converts a Rust child diagnostic to a VsCode related information - * - * This can have three outcomes: - * - * 1. If this is no primary span this will return a `noteLine` - * 2. If there is a primary span with a suggested replacement it will return a - * `codeAction`. - * 3. If there is a primary span without a suggested replacement it will return - * a `related`. - */ -function mapRustChildDiagnostic(rd: RustDiagnostic): MappedRustChildDiagnostic { - const span = rd.spans.find(s => s.is_primary); - - if (!span) { - // `rustc` uses these spanless children as a way to print multi-line - // messages - return { messageLine: rd.message }; - } - - // If we have a primary span use its location, otherwise use the parent - const location = mapSpanToLocation(span); - - // We need to distinguish `null` from an empty string - if (span && typeof span.suggested_replacement === 'string') { - // Include our replacement in the title unless it's empty - const title = span.suggested_replacement - ? `${rd.message}: \`${span.suggested_replacement}\`` - : rd.message; - - return { - suggestedFix: new SuggestedFix( - title, - location, - span.suggested_replacement, - span.suggestion_applicability, - ), - }; - } else { - const related = new vscode.DiagnosticRelatedInformation( - location, - rd.message, - ); - - return { related }; - } -} - -/** - * Converts a Rust root diagnostic to VsCode form - * - * This flattens the Rust diagnostic by: - * - * 1. Creating a `vscode.Diagnostic` with the root message and primary span. - * 2. Adding any labelled secondary spans to `relatedInformation` - * 3. Categorising child diagnostics as either `SuggestedFix`es, - * `relatedInformation` or additional message lines. - * - * If the diagnostic has no primary span this will return `undefined` - */ -export function mapRustDiagnosticToVsCode( - rd: RustDiagnostic, -): MappedRustDiagnostic | undefined { - const primarySpan = rd.spans.find(s => s.is_primary); - if (!primarySpan) { - return; - } - - const location = mapSpanToLocation(primarySpan); - const secondarySpans = rd.spans.filter(s => !s.is_primary); - - const severity = mapLevelToSeverity(rd.level); - let primarySpanLabel = primarySpan.label; - - const vd = new vscode.Diagnostic(location.range, rd.message, severity); - - let source = 'rustc'; - let code = rd.code && rd.code.code; - if (code) { - // See if this is an RFC #2103 scoped lint (e.g. from Clippy) - const scopedCode = code.split('::'); - if (scopedCode.length === 2) { - [source, code] = scopedCode; - } - } - - vd.source = source; - vd.code = code; - vd.relatedInformation = []; - vd.tags = []; - - for (const secondarySpan of secondarySpans) { - const related = mapSecondarySpanToRelated(secondarySpan); - if (related) { - vd.relatedInformation.push(related); - } - } - - const suggestedFixes = []; - for (const child of rd.children) { - const { related, suggestedFix, messageLine } = mapRustChildDiagnostic( - child, - ); - - if (related) { - vd.relatedInformation.push(related); - } - if (suggestedFix) { - suggestedFixes.push(suggestedFix); - } - if (messageLine) { - vd.message += `\n${messageLine}`; - - // These secondary messages usually duplicate the content of the - // primary span label. - primarySpanLabel = undefined; - } - } - - if (primarySpanLabel) { - vd.message += `\n${primarySpanLabel}`; - } - - if (isUnusedOrUnnecessary(rd)) { - vd.tags.push(vscode.DiagnosticTag.Unnecessary); - } - - if (isDeprecated(rd)) { - vd.tags.push(vscode.DiagnosticTag.Deprecated); - } - - return { - location, - diagnostic: vd, - suggestedFixes, - }; -} diff --git a/editors/code/src/utils/diagnostics/vscode.ts b/editors/code/src/utils/diagnostics/vscode.ts deleted file mode 100644 index f4a5450e2..000000000 --- a/editors/code/src/utils/diagnostics/vscode.ts +++ /dev/null @@ -1,14 +0,0 @@ -import * as vscode from 'vscode'; - -/** Compares two `vscode.Diagnostic`s for equality */ -export function areDiagnosticsEqual( - left: vscode.Diagnostic, - right: vscode.Diagnostic, -): boolean { - return ( - left.source === right.source && - left.severity === right.severity && - left.range.isEqual(right.range) && - left.message === right.message - ); -} -- cgit v1.2.3 From 178c23f50549298aad0dc0f098f8ed510a57f9d6 Mon Sep 17 00:00:00 2001 From: Emil Lauridsen Date: Wed, 25 Dec 2019 19:08:44 +0100 Subject: Re-implement status display using LSP 3.15 progress event --- editors/code/src/commands/watch_status.ts | 43 +++++++++++++++++++++++++++++++ editors/code/src/extension.ts | 8 ++++++ 2 files changed, 51 insertions(+) (limited to 'editors') diff --git a/editors/code/src/commands/watch_status.ts b/editors/code/src/commands/watch_status.ts index 8d64394c7..2404c3f16 100644 --- a/editors/code/src/commands/watch_status.ts +++ b/editors/code/src/commands/watch_status.ts @@ -57,7 +57,50 @@ export class StatusDisplay implements vscode.Disposable { this.statusBarItem.dispose(); } + public handleProgressNotification(params: ProgressParams) { + const { token, value } = params; + if (token !== "rustAnalyzer/cargoWatcher") { + return; + } + + console.log("Got progress notification", token, value) + switch (value.kind) { + case "begin": + this.show(); + break; + + case "report": + if (value.message) { + this.packageName = value.message; + } + break; + + case "end": + this.hide(); + break; + } + } + private frame() { return spinnerFrames[(this.i = ++this.i % spinnerFrames.length)]; } } + +// FIXME: Replace this once vscode-languageclient is updated to LSP 3.15 +interface ProgressParams { + token: string + value: WorkDoneProgress +} + +enum WorkDoneProgressKind { + Begin = "begin", + Report = "report", + End = "end" +} + +interface WorkDoneProgress { + kind: WorkDoneProgressKind, + message?: string + cancelable?: boolean + percentage?: string +} \ No newline at end of file diff --git a/editors/code/src/extension.ts b/editors/code/src/extension.ts index 72a4d4bf2..1507cb26e 100644 --- a/editors/code/src/extension.ts +++ b/editors/code/src/extension.ts @@ -8,6 +8,7 @@ import { SyntaxTreeContentProvider } from './commands/syntaxTree'; import * as events from './events'; import * as notifications from './notifications'; import { Server } from './server'; +import { StatusDisplay } from './commands/watch_status'; export async function activate(context: vscode.ExtensionContext) { function disposeOnDeactivation(disposable: vscode.Disposable) { @@ -83,6 +84,9 @@ export async function activate(context: vscode.ExtensionContext) { overrideCommand('type', commands.onEnter.handle); } + const watchStatus = new StatusDisplay(Server.config.cargoCheckOptions.command || 'check'); + disposeOnDeactivation(watchStatus); + // Notifications are events triggered by the language server const allNotifications: Iterable<[ string, @@ -92,6 +96,10 @@ export async function activate(context: vscode.ExtensionContext) { 'rust-analyzer/publishDecorations', notifications.publishDecorations.handle, ], + [ + '$/progress', + (params) => watchStatus.handleProgressNotification(params), + ] ]; const syntaxTreeContentProvider = new SyntaxTreeContentProvider(); const expandMacroContentProvider = new ExpandMacroContentProvider(); -- cgit v1.2.3 From b9c10ed97f22d665b75895a387c633dfa412ed2b Mon Sep 17 00:00:00 2001 From: Emil Lauridsen Date: Wed, 25 Dec 2019 19:10:30 +0100 Subject: Re-format VSCode extension changes --- editors/code/src/commands/watch_status.ts | 29 ++++++++++++++--------------- editors/code/src/extension.ts | 10 ++++++---- 2 files changed, 20 insertions(+), 19 deletions(-) (limited to 'editors') diff --git a/editors/code/src/commands/watch_status.ts b/editors/code/src/commands/watch_status.ts index 2404c3f16..10787b510 100644 --- a/editors/code/src/commands/watch_status.ts +++ b/editors/code/src/commands/watch_status.ts @@ -59,23 +59,22 @@ export class StatusDisplay implements vscode.Disposable { public handleProgressNotification(params: ProgressParams) { const { token, value } = params; - if (token !== "rustAnalyzer/cargoWatcher") { + if (token !== 'rustAnalyzer/cargoWatcher') { return; } - console.log("Got progress notification", token, value) switch (value.kind) { - case "begin": + case 'begin': this.show(); break; - case "report": + case 'report': if (value.message) { this.packageName = value.message; } break; - case "end": + case 'end': this.hide(); break; } @@ -88,19 +87,19 @@ export class StatusDisplay implements vscode.Disposable { // FIXME: Replace this once vscode-languageclient is updated to LSP 3.15 interface ProgressParams { - token: string - value: WorkDoneProgress + token: string; + value: WorkDoneProgress; } enum WorkDoneProgressKind { - Begin = "begin", - Report = "report", - End = "end" + Begin = 'begin', + Report = 'report', + End = 'end', } interface WorkDoneProgress { - kind: WorkDoneProgressKind, - message?: string - cancelable?: boolean - percentage?: string -} \ No newline at end of file + kind: WorkDoneProgressKind; + message?: string; + cancelable?: boolean; + percentage?: string; +} diff --git a/editors/code/src/extension.ts b/editors/code/src/extension.ts index 1507cb26e..36163b6bb 100644 --- a/editors/code/src/extension.ts +++ b/editors/code/src/extension.ts @@ -5,10 +5,10 @@ import * as commands from './commands'; import { ExpandMacroContentProvider } from './commands/expand_macro'; import { HintsUpdater } from './commands/inlay_hints'; import { SyntaxTreeContentProvider } from './commands/syntaxTree'; +import { StatusDisplay } from './commands/watch_status'; import * as events from './events'; import * as notifications from './notifications'; import { Server } from './server'; -import { StatusDisplay } from './commands/watch_status'; export async function activate(context: vscode.ExtensionContext) { function disposeOnDeactivation(disposable: vscode.Disposable) { @@ -84,7 +84,9 @@ export async function activate(context: vscode.ExtensionContext) { overrideCommand('type', commands.onEnter.handle); } - const watchStatus = new StatusDisplay(Server.config.cargoCheckOptions.command || 'check'); + const watchStatus = new StatusDisplay( + Server.config.cargoCheckOptions.command || 'check', + ); disposeOnDeactivation(watchStatus); // Notifications are events triggered by the language server @@ -98,8 +100,8 @@ export async function activate(context: vscode.ExtensionContext) { ], [ '$/progress', - (params) => watchStatus.handleProgressNotification(params), - ] + params => watchStatus.handleProgressNotification(params), + ], ]; const syntaxTreeContentProvider = new SyntaxTreeContentProvider(); const expandMacroContentProvider = new ExpandMacroContentProvider(); -- cgit v1.2.3 From 0cdbd0814958e174c5481d6bf16bd2a7e53ec981 Mon Sep 17 00:00:00 2001 From: Emil Lauridsen Date: Wed, 25 Dec 2019 20:23:44 +0100 Subject: Keep VSCode config mostly backwards compatible --- editors/code/package.json | 34 ++++++++++++++-------------------- editors/code/src/config.ts | 31 ++++++++++++++++++++----------- editors/code/src/extension.ts | 2 +- editors/code/src/server.ts | 8 +++++--- 4 files changed, 40 insertions(+), 35 deletions(-) (limited to 'editors') diff --git a/editors/code/package.json b/editors/code/package.json index 5f4123397..69298e917 100644 --- a/editors/code/package.json +++ b/editors/code/package.json @@ -188,11 +188,6 @@ "default": "ra_lsp_server", "description": "Path to ra_lsp_server executable" }, - "rust-analyzer.enableCargoCheck": { - "type": "boolean", - "default": true, - "description": "Run `cargo check` for diagnostics on save" - }, "rust-analyzer.excludeGlobs": { "type": "array", "default": [], @@ -203,16 +198,26 @@ "default": true, "description": "client provided file watching instead of notify watching." }, - "rust-analyzer.cargo-check.arguments": { + "rust-analyzer.cargo-watch.enable": { + "type": "boolean", + "default": true, + "description": "Run `cargo check` for diagnostics on save" + }, + "rust-analyzer.cargo-watch.arguments": { "type": "array", - "description": "`cargo-check` arguments. (e.g: `--features=\"shumway,pdf\"` will run as `cargo check --features=\"shumway,pdf\"` )", + "description": "`cargo-watch` arguments. (e.g: `--features=\"shumway,pdf\"` will run as `cargo watch -x \"check --features=\"shumway,pdf\"\"` )", "default": [] }, - "rust-analyzer.cargo-check.command": { + "rust-analyzer.cargo-watch.command": { "type": "string", - "description": "`cargo-check` command. (e.g: `clippy` will run as `cargo clippy` )", + "description": "`cargo-watch` command. (e.g: `clippy` will run as `cargo watch -x clippy` )", "default": "check" }, + "rust-analyzer.cargo-watch.allTargets": { + "type": "boolean", + "description": "Check all targets and tests (will be passed as `--all-targets`)", + "default": true + }, "rust-analyzer.trace.server": { "type": "string", "scope": "window", @@ -229,17 +234,6 @@ "default": "off", "description": "Trace requests to the ra_lsp_server" }, - "rust-analyzer.trace.cargo-watch": { - "type": "string", - "scope": "window", - "enum": [ - "off", - "error", - "verbose" - ], - "default": "off", - "description": "Trace output of cargo-watch" - }, "rust-analyzer.lruCapacity": { "type": "number", "default": null, diff --git a/editors/code/src/config.ts b/editors/code/src/config.ts index 96532e2c9..4b388b80c 100644 --- a/editors/code/src/config.ts +++ b/editors/code/src/config.ts @@ -4,10 +4,11 @@ import { Server } from './server'; const RA_LSP_DEBUG = process.env.__RA_LSP_SERVER_DEBUG; -export interface CargoCheckOptions { - enabled: boolean; +export interface CargoWatchOptions { + enable: boolean; arguments: string[]; - command: null | string; + command: string; + allTargets: boolean; } export interface CargoFeatures { @@ -29,10 +30,11 @@ export class Config { public featureFlags = {}; // for internal use public withSysroot: null | boolean = null; - public cargoCheckOptions: CargoCheckOptions = { - enabled: true, + public cargoWatchOptions: CargoWatchOptions = { + enable: true, arguments: [], - command: null, + command: '', + allTargets: true, }; public cargoFeatures: CargoFeatures = { noDefaultFeatures: false, @@ -91,27 +93,34 @@ export class Config { RA_LSP_DEBUG || (config.get('raLspServerPath') as string); } - if (config.has('enableCargoCheck')) { - this.cargoCheckOptions.enabled = config.get( - 'enableCargoCheck', + if (config.has('cargo-watch.enable')) { + this.cargoWatchOptions.enable = config.get( + 'cargo-watch.enable', true, ); } if (config.has('cargo-watch.arguments')) { - this.cargoCheckOptions.arguments = config.get( + this.cargoWatchOptions.arguments = config.get( 'cargo-watch.arguments', [], ); } if (config.has('cargo-watch.command')) { - this.cargoCheckOptions.command = config.get( + this.cargoWatchOptions.command = config.get( 'cargo-watch.command', '', ); } + if (config.has('cargo-watch.allTargets')) { + this.cargoWatchOptions.allTargets = config.get( + 'cargo-watch.allTargets', + true, + ); + } + if (config.has('lruCapacity')) { this.lruCapacity = config.get('lruCapacity') as number; } diff --git a/editors/code/src/extension.ts b/editors/code/src/extension.ts index 36163b6bb..1da10ebd0 100644 --- a/editors/code/src/extension.ts +++ b/editors/code/src/extension.ts @@ -85,7 +85,7 @@ export async function activate(context: vscode.ExtensionContext) { } const watchStatus = new StatusDisplay( - Server.config.cargoCheckOptions.command || 'check', + Server.config.cargoWatchOptions.command, ); disposeOnDeactivation(watchStatus); diff --git a/editors/code/src/server.ts b/editors/code/src/server.ts index 409d3b4b7..ae81af848 100644 --- a/editors/code/src/server.ts +++ b/editors/code/src/server.ts @@ -55,9 +55,11 @@ export class Server { publishDecorations: true, lruCapacity: Server.config.lruCapacity, maxInlayHintLength: Server.config.maxInlayHintLength, - cargoCheckEnable: Server.config.cargoCheckOptions.enabled, - cargoCheckCommand: Server.config.cargoCheckOptions.command, - cargoCheckArgs: Server.config.cargoCheckOptions.arguments, + cargoWatchEnable: Server.config.cargoWatchOptions.enable, + cargoWatchArgumets: Server.config.cargoWatchOptions.arguments, + cargoWatchCommand: Server.config.cargoWatchOptions.command, + cargoWatchAllTargets: + Server.config.cargoWatchOptions.allTargets, excludeGlobs: Server.config.excludeGlobs, useClientWatching: Server.config.useClientWatching, featureFlags: Server.config.featureFlags, -- cgit v1.2.3