-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathcode_analysis.ts
308 lines (265 loc) · 9.11 KB
/
code_analysis.ts
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import * as cp from "child_process";
import * as path from "path";
import {
window,
DiagnosticCollection,
Diagnostic,
Range,
Position,
DiagnosticSeverity,
Uri,
CodeAction,
CodeActionKind,
WorkspaceEdit,
OutputChannel,
StatusBarItem,
} from "vscode";
import { analysisProdPath, getAnalysisBinaryPath } from "../utils";
export let statusBarItem = {
setToStopText: (codeAnalysisRunningStatusBarItem: StatusBarItem) => {
codeAnalysisRunningStatusBarItem.text = "$(debug-stop) Stop Code Analyzer";
codeAnalysisRunningStatusBarItem.tooltip = null;
},
setToRunningText: (codeAnalysisRunningStatusBarItem: StatusBarItem) => {
codeAnalysisRunningStatusBarItem.text =
"$(loading~spin) Running code analysis...";
codeAnalysisRunningStatusBarItem.tooltip = null;
},
setToFailed: (codeAnalysisRunningStatusBarItem: StatusBarItem) => {
codeAnalysisRunningStatusBarItem.text = "$(alert) Failed";
codeAnalysisRunningStatusBarItem.tooltip =
"Something went wrong when running the code analysis.";
},
};
export type DiagnosticsResultCodeActionsMap = Map<
string,
{ range: Range; codeAction: CodeAction }[]
>;
export type DiagnosticsResultFormat = Array<{
name: string;
kind: string;
file: string;
range: [number, number, number, number];
message: string;
annotate?: {
line: number;
character: number;
text: string;
action: string;
};
}>;
enum ClassifiedMessage {
Removable,
Default,
}
let classifyMessage = (msg: string) => {
if (
msg.endsWith(" is never used") ||
msg.endsWith(" is never used and could have side effects") ||
msg.endsWith(" has no side effects and can be removed")
) {
return ClassifiedMessage.Removable;
}
return ClassifiedMessage.Default;
};
let resultsToDiagnostics = (
results: DiagnosticsResultFormat,
diagnosticsResultCodeActions: DiagnosticsResultCodeActionsMap
): {
diagnosticsMap: Map<string, Diagnostic[]>;
} => {
let diagnosticsMap: Map<string, Diagnostic[]> = new Map();
results.forEach((item) => {
{
let startPos: Position, endPos: Position;
let [startLine, startCharacter, endLine, endCharacter] = item.range;
// Detect if this diagnostic is for the entire file. If so, reanalyze will
// say that the issue is on line -1. This code below ensures
// that the full file is highlighted, if that's the case.
if (startLine < 0 || endLine < 0) {
startPos = new Position(0, 0);
endPos = new Position(99999, 0);
} else {
startPos = new Position(startLine, startCharacter);
endPos = new Position(endLine, endCharacter);
}
let issueLocationRange = new Range(startPos, endPos);
let diagnosticText = item.message.trim();
let diagnostic = new Diagnostic(
issueLocationRange,
diagnosticText,
DiagnosticSeverity.Warning
);
// Don't show reports about optional arguments.
if (item.name.toLowerCase().includes("unused argument")) {
return;
}
if (diagnosticsMap.has(item.file)) {
diagnosticsMap.get(item.file).push(diagnostic);
} else {
diagnosticsMap.set(item.file, [diagnostic]);
}
// If reanalyze suggests a fix, we'll set that up as a refactor code
// action in VSCode. This way, it'll be easy to suppress the issue
// reported if wanted. We also save the range of the issue, so we can
// leverage that to make looking up the code actions for each cursor
// position very cheap.
if (item.annotate != null) {
{
let { line, character, text, action } = item.annotate;
let codeAction = new CodeAction(action);
codeAction.kind = CodeActionKind.RefactorRewrite;
let codeActionEdit = new WorkspaceEdit();
codeActionEdit.replace(
Uri.parse(item.file),
// Make sure the full line is replaced
new Range(
new Position(line, character),
new Position(line, character)
),
// reanalyze seems to add two extra spaces at the start of the line
// content to replace.
text
);
codeAction.edit = codeActionEdit;
if (diagnosticsResultCodeActions.has(item.file)) {
diagnosticsResultCodeActions
.get(item.file)
.push({ range: issueLocationRange, codeAction });
} else {
diagnosticsResultCodeActions.set(item.file, [
{ range: issueLocationRange, codeAction },
]);
}
}
}
// This heuristic below helps only target dead code that can be removed
// safely by just removing its text.
if (classifyMessage(item.message) === ClassifiedMessage.Removable) {
{
let codeAction = new CodeAction("Remove unused");
codeAction.kind = CodeActionKind.RefactorRewrite;
let codeActionEdit = new WorkspaceEdit();
codeActionEdit.replace(
Uri.parse(item.file),
new Range(
new Position(item.range[0], item.range[1]),
new Position(item.range[2], item.range[3])
),
""
);
codeAction.command = {
command: "rescript-vscode.clear_diagnostic",
title: "Clear diagnostic",
arguments: [diagnostic],
};
codeAction.edit = codeActionEdit;
if (diagnosticsResultCodeActions.has(item.file)) {
diagnosticsResultCodeActions
.get(item.file)
.push({ range: issueLocationRange, codeAction });
} else {
diagnosticsResultCodeActions.set(item.file, [
{ range: issueLocationRange, codeAction },
]);
}
}
}
}
});
return {
diagnosticsMap,
};
};
export const runCodeAnalysisWithReanalyze = (
targetDir: string | null,
diagnosticsCollection: DiagnosticCollection,
diagnosticsResultCodeActions: DiagnosticsResultCodeActionsMap,
outputChannel: OutputChannel,
codeAnalysisRunningStatusBarItem: StatusBarItem
) => {
let currentDocument = window.activeTextEditor.document;
let cwd = targetDir ?? path.dirname(currentDocument.uri.fsPath);
let binaryPath = getAnalysisBinaryPath();
if (binaryPath === null) {
window.showErrorMessage("Binary executable not found.", analysisProdPath);
return;
}
statusBarItem.setToRunningText(codeAnalysisRunningStatusBarItem);
let opts = ["reanalyze", "-json"];
let p = cp.spawn(binaryPath, opts, {
cwd,
});
if (p.stdout == null) {
statusBarItem.setToFailed(codeAnalysisRunningStatusBarItem);
window.showErrorMessage("Something went wrong.");
return;
}
let data = "";
p.stdout.on("data", (d) => {
data += d;
});
p.stderr?.on("data", (e) => {
// Sometimes the compiler artifacts has been corrupted in some way, and
// reanalyze will spit out a "End_of_file" exception. The solution is to
// clean and rebuild the ReScript project, which we can tell the user about
// here.
if (e.includes("End_of_file")) {
window.showErrorMessage(
`Something went wrong trying to run reanalyze. Please try cleaning and rebuilding your ReScript project.`
);
} else {
window.showErrorMessage(
`Something went wrong trying to run reanalyze: '${e}'`
);
}
});
p.on("close", () => {
diagnosticsResultCodeActions.clear();
let json: DiagnosticsResultFormat | null = null;
try {
json = JSON.parse(data);
} catch (e) {
window
.showErrorMessage(
`Something went wrong when running the code analyzer.`,
"See details in error log"
)
.then((_choice) => {
outputChannel.show();
});
outputChannel.appendLine("\n\n>>>>");
outputChannel.appendLine(
"Parsing JSON from reanalyze failed. The raw, invalid JSON can be reproduced by following the instructions below. Please run that command and report the issue + failing JSON on the extension bug tracker: https://github.com/rescript-lang/rescript-vscode/issues"
);
outputChannel.appendLine(
`> To reproduce, run "${binaryPath} ${opts.join(
" "
)}" in directory: "${cwd}"`
);
outputChannel.appendLine("\n");
}
if (json == null) {
// If reanalyze failed for some reason we'll clear the diagnostics.
diagnosticsCollection.clear();
statusBarItem.setToFailed(codeAnalysisRunningStatusBarItem);
return;
}
let { diagnosticsMap } = resultsToDiagnostics(
json,
diagnosticsResultCodeActions
);
// This smoothens the experience of the diagnostics updating a bit by
// clearing only the visible diagnostics that has been fixed after the
// updated diagnostics has been applied.
diagnosticsCollection.forEach((uri, _) => {
if (!diagnosticsMap.has(uri.fsPath)) {
diagnosticsCollection.delete(uri);
}
});
diagnosticsMap.forEach((diagnostics, filePath) => {
diagnosticsCollection.set(Uri.parse(filePath), diagnostics);
});
statusBarItem.setToStopText(codeAnalysisRunningStatusBarItem);
});
};