aboutsummaryrefslogtreecommitdiff
path: root/editors/code/src/utils/diagnostics/SuggestedFix.ts
blob: b1be2a225b6ca4d09d5dd41209b2eafb10826a44 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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;
    }
}