forked from swiftlang/vscode-swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDiagnosticsManager.ts
381 lines (350 loc) · 15.6 KB
/
DiagnosticsManager.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
//===----------------------------------------------------------------------===//
//
// This source file is part of the VS Code Swift open source project
//
// Copyright (c) 2024 the VS Code Swift project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of VS Code Swift project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import * as vscode from "vscode";
import stripAnsi = require("strip-ansi");
import configuration from "./configuration";
import { SwiftExecution } from "./tasks/SwiftExecution";
import { WorkspaceContext } from "./WorkspaceContext";
import { checkIfBuildComplete } from "./utilities/tasks";
interface ParsedDiagnostic {
uri: string;
diagnostic: vscode.Diagnostic;
}
type DiagnosticsMap = Map<string, vscode.Diagnostic[]>;
type SourcePredicate = (source: string) => boolean;
type DiagnosticPredicate = (diagnostic: vscode.Diagnostic) => boolean;
const isEqual = (d1: vscode.Diagnostic, d2: vscode.Diagnostic) =>
d1.range.start.isEqual(d2.range.start) && d1.message === d2.message;
const isSource = (diagnostic: vscode.Diagnostic, sourcesPredicate: SourcePredicate) =>
sourcesPredicate(diagnostic.source ?? "");
const isSwiftc: DiagnosticPredicate = diagnostic =>
isSource(diagnostic, DiagnosticsManager.isSwiftc);
const isSourceKit: DiagnosticPredicate = diagnostic =>
isSource(diagnostic, DiagnosticsManager.isSourcekit);
/**
* Handles the collection and deduplication of diagnostics from
* various {@link vscode.Diagnostic.source | Diagnostic sources}.
*
* Listens for running {@link SwiftExecution} tasks and allows
* external clients to call {@link handleDiagnostics} to provide
* thier own diagnostics.
*/
export class DiagnosticsManager implements vscode.Disposable {
private static swiftc: string = "swiftc";
static isSourcekit: SourcePredicate = source => this.swiftc !== source;
static isSwiftc: SourcePredicate = source => this.swiftc === source;
private diagnosticCollection: vscode.DiagnosticCollection =
vscode.languages.createDiagnosticCollection("swift");
private allDiagnostics: Map<string, vscode.Diagnostic[]> = new Map();
constructor(context: WorkspaceContext) {
this.onDidChangeConfigurationDisposible = vscode.workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration("swift.diagnosticsCollection")) {
this.diagnosticCollection.clear();
this.allDiagnostics.forEach((_, uri) =>
this.updateDiagnosticsCollection(vscode.Uri.file(uri))
);
}
});
this.onDidStartTaskDisposible = vscode.tasks.onDidStartTask(event => {
// Will only try to provide diagnostics for `swift` tasks
const task = event.execution.task;
if (task.definition.type !== "swift") {
return;
}
if (!this.includeSwiftcDiagnostics()) {
return;
}
// Provide new list of diagnostics
const swiftExecution = task.execution as SwiftExecution;
const provideDiagnostics: Promise<DiagnosticsMap> =
this.parseDiagnostics(swiftExecution);
provideDiagnostics
.then(map => {
// Clean up old "swiftc" diagnostics
this.removeSwiftcDiagnostics();
map.forEach((diagnostics, uri) =>
this.handleDiagnostics(
vscode.Uri.file(uri),
DiagnosticsManager.isSwiftc,
diagnostics
)
);
})
.catch(e =>
context.outputChannel.log(`${e}`, 'Failed to provide "swiftc" diagnostics')
);
});
}
/**
* Provide a new list of diagnostics for a given file
*
* @param uri {@link vscode.Uri Uri} of the file these diagonstics apply to
* @param sourcePredicate Diagnostics of a source that satisfies the predicate will apply for cleaning
* up diagnostics that have been removed. See {@link isSwiftc} and {@link isSourceKit}
* @param newDiagnostics Array of {@link vscode.Diagnostic}. This can be empty to remove old diagnostics satisfying `sourcePredicate`.
*/
handleDiagnostics(
uri: vscode.Uri,
sourcePredicate: SourcePredicate,
newDiagnostics: vscode.Diagnostic[]
): void {
const isFromSourceKit = !sourcePredicate(DiagnosticsManager.swiftc);
// Is a descrepency between SourceKit-LSP and older versions
// of Swift as to whether the first letter is capitalized or not,
// so we'll always display messages capitalized to user and this
// also will allow comparing messages when merging
newDiagnostics = newDiagnostics.map(this.capitalizeMessage).map(this.cleanMessage);
const allDiagnostics = this.allDiagnostics.get(uri.fsPath)?.slice() || [];
// Remove the old set of diagnostics from this source
const removedDiagnostics = this.removeDiagnostics(allDiagnostics, d =>
isSource(d, sourcePredicate)
);
// Clean up any "fixed" swiftc diagnostics
if (isFromSourceKit) {
this.removeDiagnostics(
removedDiagnostics,
d1 => !!newDiagnostics.find(d2 => isEqual(d1, d2))
);
this.removeDiagnostics(
allDiagnostics,
d1 => isSwiftc(d1) && !!removedDiagnostics.find(d2 => isEqual(d1, d2))
);
}
// Append the new diagnostics we just received
allDiagnostics.push(...newDiagnostics);
this.allDiagnostics.set(uri.fsPath, allDiagnostics);
// Update the collection
this.updateDiagnosticsCollection(uri);
}
private updateDiagnosticsCollection(uri: vscode.Uri): void {
const diagnostics = this.allDiagnostics.get(uri.fsPath) ?? [];
const swiftcDiagnostics = diagnostics.filter(isSwiftc);
const sourceKitDiagnostics = diagnostics.filter(isSourceKit);
const mergedDiagnostics: vscode.Diagnostic[] = [];
switch (configuration.diagnosticsCollection) {
case "keepSourceKit":
mergedDiagnostics.push(...swiftcDiagnostics);
this.mergeDiagnostics(mergedDiagnostics, sourceKitDiagnostics, isSourceKit);
break;
case "keepSwiftc":
mergedDiagnostics.push(...sourceKitDiagnostics);
this.mergeDiagnostics(mergedDiagnostics, swiftcDiagnostics, isSwiftc);
break;
case "onlySourceKit":
mergedDiagnostics.push(...sourceKitDiagnostics);
break;
case "onlySwiftc":
mergedDiagnostics.push(...swiftcDiagnostics);
break;
case "keepAll":
mergedDiagnostics.push(...sourceKitDiagnostics);
mergedDiagnostics.push(...swiftcDiagnostics);
break;
}
this.diagnosticCollection.set(uri, mergedDiagnostics);
}
private mergeDiagnostics(
mergedDiagnostics: vscode.Diagnostic[],
newDiagnostics: vscode.Diagnostic[],
precedencePredicate: DiagnosticPredicate
): void {
for (const diagnostic of newDiagnostics) {
// See if a duplicate diagnostic exists
const currentDiagnostic = mergedDiagnostics.find(d => isEqual(d, diagnostic));
if (currentDiagnostic) {
mergedDiagnostics.splice(mergedDiagnostics.indexOf(currentDiagnostic), 1);
}
// Perform de-duplication
if (precedencePredicate(diagnostic)) {
mergedDiagnostics.push(diagnostic);
continue;
}
if (!currentDiagnostic || !precedencePredicate(currentDiagnostic)) {
mergedDiagnostics.push(diagnostic);
continue;
}
mergedDiagnostics.push(currentDiagnostic);
}
}
private removeSwiftcDiagnostics() {
this.allDiagnostics.forEach((diagnostics, path) => {
const newDiagnostics = diagnostics.slice();
this.removeDiagnostics(newDiagnostics, isSwiftc);
if (diagnostics.length !== newDiagnostics.length) {
this.allDiagnostics.set(path, newDiagnostics);
}
this.updateDiagnosticsCollection(vscode.Uri.file(path));
});
}
private removeDiagnostics(
diagnostics: vscode.Diagnostic[],
matches: DiagnosticPredicate
): vscode.Diagnostic[] {
const removed: vscode.Diagnostic[] = [];
let i = diagnostics.length;
while (i--) {
if (matches(diagnostics[i])) {
removed.push(...diagnostics.splice(i, 1));
}
}
return removed;
}
/**
* Clear the `swift` diagnostics collection. Mostly meant for testing purposes.
*/
clear(): void {
this.diagnosticCollection.clear();
this.allDiagnostics.clear();
}
dispose() {
this.diagnosticCollection.dispose();
this.onDidStartTaskDisposible.dispose();
this.onDidChangeConfigurationDisposible.dispose();
}
private includeSwiftcDiagnostics(): boolean {
return configuration.diagnosticsCollection !== "onlySourceKit";
}
private parseDiagnostics(swiftExecution: SwiftExecution): Promise<DiagnosticsMap> {
return new Promise<DiagnosticsMap>(res => {
const diagnostics = new Map();
const disposables: vscode.Disposable[] = [];
const done = () => {
disposables.forEach(d => d.dispose());
res(diagnostics);
};
let remainingData: string | undefined;
let lastDiagnostic: vscode.Diagnostic | undefined;
disposables.push(
swiftExecution.onDidWrite(data => {
const sanitizedData = (remainingData || "") + stripAnsi(data);
const lines = sanitizedData.split(/\r\n|\n|\r/gm);
// If ends with \n then will be "" and there's no affect.
// Otherwise want to keep remaining data to pre-pend next write
remainingData = lines.pop();
for (const line of lines) {
if (checkIfBuildComplete(line)) {
done();
return;
}
const result = this.parseDiagnostic(line);
if (!result) {
continue;
}
if (result instanceof vscode.DiagnosticRelatedInformation) {
if (!lastDiagnostic) {
continue;
}
const relatedInformation =
result as vscode.DiagnosticRelatedInformation;
if (
lastDiagnostic.relatedInformation?.find(
d =>
d.message === relatedInformation.message &&
d.location.uri.fsPath ===
relatedInformation.location.uri.fsPath &&
d.location.range.isEqual(relatedInformation.location.range)
)
) {
// De-duplicate duplicate notes from SwiftPM
// TODO remove when https://github.com/apple/swift/issues/73973 is fixed
continue;
}
lastDiagnostic.relatedInformation = (
lastDiagnostic.relatedInformation || []
).concat(relatedInformation);
continue;
}
const { uri, diagnostic } = result as ParsedDiagnostic;
const currentUriDiagnostics: vscode.Diagnostic[] =
diagnostics.get(uri) || [];
if (
currentUriDiagnostics.find(
d =>
d.message === diagnostic.message &&
d.range.isEqual(diagnostic.range)
)
) {
// De-duplicate duplicate diagnostics from SwiftPM
// TODO remove when https://github.com/apple/swift/issues/73973 is fixed
lastDiagnostic = undefined;
continue;
}
lastDiagnostic = diagnostic;
diagnostics.set(uri, [...currentUriDiagnostics, diagnostic]);
}
}),
swiftExecution.onDidClose(done)
);
});
}
private parseDiagnostic(
line: string
): ParsedDiagnostic | vscode.DiagnosticRelatedInformation | undefined {
const diagnosticRegex = /^(.*?):(\d+)(?::(\d+))?:\s+(warning|error|note):\s+([^\\[]*)/g;
const match = diagnosticRegex.exec(line);
if (!match) {
return;
}
const uri = match[1];
const message = this.capitalize(match[5]).trim();
const range = this.range(match[2], match[3]);
const severity = this.severity(match[4]);
if (severity === vscode.DiagnosticSeverity.Information) {
return new vscode.DiagnosticRelatedInformation(
new vscode.Location(vscode.Uri.file(uri), range),
message
);
}
const diagnostic = new vscode.Diagnostic(range, message, severity);
diagnostic.source = DiagnosticsManager.swiftc;
return { uri, diagnostic };
}
private range(lineString: string, columnString: string): vscode.Range {
// Output from `swift` is 1-based but vscode expects 0-based lines and columns
const line = parseInt(lineString) - 1;
const col = parseInt(columnString) - 1;
const position = new vscode.Position(line, col);
return new vscode.Range(position, position);
}
private severity(severityString: string): vscode.DiagnosticSeverity {
let severity = vscode.DiagnosticSeverity.Error;
switch (severityString) {
case "warning":
severity = vscode.DiagnosticSeverity.Warning;
break;
case "note":
severity = vscode.DiagnosticSeverity.Information;
break;
default:
break;
}
return severity;
}
private capitalize(message: string): string {
return message.charAt(0).toUpperCase() + message.slice(1);
}
private capitalizeMessage = (diagnostic: vscode.Diagnostic): vscode.Diagnostic => {
const message = diagnostic.message;
diagnostic = { ...diagnostic };
diagnostic.message = this.capitalize(message);
return diagnostic;
};
private cleanMessage = (diagnostic: vscode.Diagnostic) => {
diagnostic = { ...diagnostic };
diagnostic.message = diagnostic.message.replace("(fix available)", "").trim();
return diagnostic;
};
private onDidStartTaskDisposible: vscode.Disposable;
private onDidChangeConfigurationDisposible: vscode.Disposable;
}