-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathextension.ts
More file actions
343 lines (298 loc) · 12.9 KB
/
extension.ts
File metadata and controls
343 lines (298 loc) · 12.9 KB
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
import * as vscode from 'vscode';
import * as cp from 'child_process';
import * as path from "path";
import * as xml2js from 'xml2js';
import { runScript } from './util/scripts';
import { resolvePath } from './util/path';
enum SeverityNumber {
Info = 0,
Warning = 1,
Error = 2
}
// If a script generates arguments at extension activation they are saved in dynamicArgs
const dynamicArgs : Array<string> = [];
const criticalWarningTypes = [
'cppcheckError',
'cppcheckLimit',
'includeNestedTooDeeply',
'internalAstError',
'instantiationError',
'internalError',
'missingFile',
'premium-internalError',
'premium-invalidArgument',
'premium-invalidLicense',
'preprocessorErrorDirective',
'syntaxError',
'unhandledChar',
'unknownMacro'
];
function parseSeverity(str: string): vscode.DiagnosticSeverity {
const lower = str.toLowerCase();
if (lower.includes("error")) {
return vscode.DiagnosticSeverity.Error;
} else if (lower.includes("warning")) {
return vscode.DiagnosticSeverity.Warning;
} else {
return vscode.DiagnosticSeverity.Information;
}
}
function severityToNumber(sev: vscode.DiagnosticSeverity): SeverityNumber {
switch (sev) {
case vscode.DiagnosticSeverity.Error: return SeverityNumber.Error;
case vscode.DiagnosticSeverity.Warning: return SeverityNumber.Warning;
default: return SeverityNumber.Info;
}
}
function parseMinSeverity(str: string): SeverityNumber {
switch (str.toLowerCase()) {
case "error": return SeverityNumber.Error;
case "warning": return SeverityNumber.Warning;
default: return SeverityNumber.Info;
}
}
// This method is called when your extension is activated.
// Your extension is activated the very first time the command is executed.
export async function activate(context: vscode.ExtensionContext) {
// Create a diagnostic collection.
const diagnosticCollection = vscode.languages.createDiagnosticCollection("Cppcheck");
context.subscriptions.push(diagnosticCollection);
// If an argument requires us to run any scripts we do it here
const config = vscode.workspace.getConfiguration();
const args = config.get<string>("cppcheck-official.arguments", "");
const argsWithScripts = args.split("--").filter((arg) => arg.includes('${'));
for (const arg of argsWithScripts) {
// argType will look like e.g. --project
const argType = arg.split("=")[0];
const argValue = arg.split("=")[1];
// Remove ${ from the beginning and slice } away from the end of argValue
const scriptCommand = argValue.split("{")[1].split("}")[0];
const scriptOutput = await runScript(scriptCommand);
// We expect the script output that we are to set the argument to will be wrapped with ${}
const scriptOutputPath = scriptOutput.split("${")[1].split("}")[0];
dynamicArgs.push(`${argType}=${scriptOutputPath}`);
};
// set up a map of timers per document URI for debounce for continuous analysis triggers
// I.e. document has been changed -> DEBOUNCE_MS time passed since last change -> run cppcheck
const debounceTimers: Map<string, NodeJS.Timeout> = new Map();
const DEBOUNCE_MS = 1000;
async function handleDocument(document: vscode.TextDocument) {
// Only process C/C++ files.
if (!["c", "cpp"].includes(document.languageId)) {
// Not a C/C++ file, skip
return;
}
// Check if the document is visible in any editor
const isVisible = vscode.window.visibleTextEditors.some(editor =>
editor.document.uri.toString().replaceAll('\\', '/') === document.uri.toString().replaceAll('\\', '/'));
if (!isVisible) {
// Document is not visible, skip
return;
}
const config = vscode.workspace.getConfiguration();
const isEnabled = config.get<boolean>("cppcheck-official.enable", true);
const extraArgs = config.get<string>("cppcheck-official.arguments", "");
const minSevString = config.get<string>("cppcheck-official.minSeverity", "info");
const userPath = config.get<string>("cppcheck-official.path")?.trim() || "";
const commandPath = userPath ? resolvePath(userPath) : "cppcheck";
// If disabled, clear any existing diagnostics for this doc.
if (!isEnabled) {
diagnosticCollection.delete(document.uri);
return;
}
// Check if cppcheck is available
cp.exec(`"${commandPath}" --version`, (error) => {
if (error) {
vscode.window.showErrorMessage(
`Cppcheck: Could not find or run '${commandPath}'. ` +
`Please install cppcheck or set 'cppcheck-official.path' correctly.`
);
return;
}
});
await runCppcheckOnFileXML(
document,
commandPath,
extraArgs,
minSevString,
diagnosticCollection
);
}
// TODO: Reimplement continuous analysis. Requires cppcheck update (expected in 2.20)
async function handleDocumentContinuous(e: vscode.TextDocumentChangeEvent) {
const document : vscode.TextDocument = e.document;
const uriKey = document.uri.toString();
// clear any existing timer for this document
if (debounceTimers.has(uriKey)) {
clearTimeout(debounceTimers.get(uriKey)!);
}
// schedule a new run
const timer = setTimeout(async () => {
debounceTimers.delete(uriKey);
await handleDocument(document);
}, DEBOUNCE_MS);
debounceTimers.set(uriKey, timer);
}
// Run cppcheck when document is changed, with debounce
// vscode.workspace.onDidChangeTextDocument(handleDocumentContinuous, null, context.subscriptions);
// Listen for file saves.
vscode.workspace.onDidSaveTextDocument(handleDocument, null, context.subscriptions);
// Run cppcheck when a file is opened
vscode.workspace.onDidOpenTextDocument(handleDocument, null, context.subscriptions);
// Run cppcheck for all open files when the workspace is opened
vscode.workspace.onDidChangeWorkspaceFolders(() => {
vscode.workspace.textDocuments.forEach(handleDocument);
}, null, context.subscriptions);
// Run cppcheck for all open files at activation (for already opened workspaces)
vscode.workspace.textDocuments.forEach(handleDocument);
// Clean up diagnostics when a file is closed
vscode.workspace.onDidCloseTextDocument((document: vscode.TextDocument) => {
diagnosticCollection.delete(document.uri);
}, null, context.subscriptions);
}
async function runCppcheckOnFileXML(
document: vscode.TextDocument,
commandPath: string,
extraArgs: string,
minSevString: string,
diagnosticCollection: vscode.DiagnosticCollection
): Promise<void> {
// Clear existing diagnostics for this file
diagnosticCollection.delete(document.uri);
// Replace backslashes (used in paths in Windows environment)
const filePath = document.fileName.replaceAll('\\', '/');
const minSevNum = parseMinSeverity(minSevString);
// Arguments specified with scripts are replaced with script output (dynamicArgs)
const staticArgs = extraArgs.split("--").filter((arg) => !arg.includes("${"));
const allArgs = staticArgs.concat(dynamicArgs);
// Resolve paths for arguments where applicable
const extraArgsParsed = allArgs.map((arg) => {
if (arg.startsWith('project')) {
const splitArg = arg.split('=');
return `--${splitArg[0]}=${resolvePath(splitArg[1])}`;
}
return arg;
});
let proc;
if (extraArgs.includes("--project")) {
const args = [
'--enable=all',
'--inline-suppr',
'--xml',
'--suppress=unusedFunction',
'--suppress=missingInclude',
'--suppress=missingIncludeSystem',
`--file-filter=${filePath}`,
...extraArgsParsed,
].filter(Boolean);
proc = cp.spawn(commandPath, args, {
cwd: path.dirname(document.fileName),
});
} else {
const args = [
'--enable=all',
'--inline-suppr',
'--xml',
'--suppress=unusedFunction',
'--suppress=missingInclude',
'--suppress=missingIncludeSystem',
...extraArgsParsed,
filePath,
].filter(Boolean);
proc = cp.spawn(commandPath, args, {
cwd: path.dirname(document.fileName),
});
}
// if spawn fails (e.g. ENOENT or permission denied)
proc.on("error", (err) => {
console.error("Failed to start cppcheck:", err);
vscode.window.showErrorMessage(`Cppcheck failed to start: ${err.message}`);
});
let xmlOutput = "";
let out = "";
proc.stderr.on("data", d => xmlOutput += d.toString());
proc.stdout.on("data", d => out += d.toString());
proc.on("close", code => {
if (code && code > 0) {
// Non-zero code means an error has occured
let errorMessage = `Cppcheck failed with code ${code} (unknown error)`;
if (out.trim().length > 0) {
errorMessage = out.trim();
}
vscode.window.showErrorMessage(errorMessage);
}
const parser = new xml2js.Parser({ explicitArray: true });
parser.parseString(xmlOutput, (err, result) => {
if (err) {
console.error("XML parse error:", err);
return;
}
const errors = result.results?.errors?.[0]?.error || [];
const diagnostics: vscode.Diagnostic[] = [];
for (const e of errors) {
const isCriticalError = criticalWarningTypes.includes(e.$.id);
const locations = e.location || [];
if (!locations.length) {
continue;
}
const mainLoc = locations[locations.length - 1].$;
// If main location is not current file, then skip displaying warning unless it is critical
if (!isCriticalError && !filePath.endsWith(mainLoc.file)) {
continue;
}
// Cppcheck line number is 1-indexed, while VS Code uses 0-indexing
let line = Number(mainLoc.line) - 1;
// Invalid line number usually means non-analysis output
if (isNaN(line) || line < 0 || line >= document.lineCount) {
if (isCriticalError) {
line = 0;
} else {
continue;
}
}
// Cppcheck col number is 1-indexed, while VS Code uses 0-indexing
let col = Number(mainLoc.column) - 1;
if (isNaN(col) || col < 0 || col > document.lineAt(line).text.length) {
col = 0;
}
const severity = parseSeverity(e.$.severity);
if (!isCriticalError && severityToNumber(severity) < minSevNum) {
continue;
}
const range = new vscode.Range(line, col, line, document.lineAt(line).text.length);
const diagnostic = new vscode.Diagnostic(range, e.$.msg, severity);
diagnostic.source = "cppcheck";
diagnostic.code = e.$.id;
// Related Information
const relatedInfos: vscode.DiagnosticRelatedInformation[] = [];
for (let i = 1; i <= locations.length; i++) {
// Related information is ordered in reverse in XML object
const loc = locations[locations.length - i].$;
const msg = loc.info;
const lLine = Number(loc.line) - 1;
const lCol = Number(loc.col) - 1;
if (msg === null || msg === undefined || isNaN(lLine) || lLine < 0 || lLine >= document.lineCount) {
continue;
}
const relatedRange = new vscode.Range(
lLine, lCol,
lLine, document.lineAt(lLine).text.length
);
relatedInfos.push(
new vscode.DiagnosticRelatedInformation(
new vscode.Location(document.uri, relatedRange),
msg
)
);
}
if (relatedInfos.length > 0) {
diagnostic.relatedInformation = relatedInfos;
}
diagnostics.push(diagnostic);
}
diagnosticCollection.set(document.uri, diagnostics);
});
});
}
// This method is called when your extension is deactivated
export function deactivate() {}