-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathanalysis.ts
More file actions
529 lines (468 loc) · 15.3 KB
/
Copy pathanalysis.ts
File metadata and controls
529 lines (468 loc) · 15.3 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
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
import path from "node:path";
export type CompilerKind = "llvm" | "gcc" | "msvc" | "unknown";
export type ModuleCapability = "full" | "syntax-only" | "unavailable";
export type ModulesSupportMode = "auto" | "on" | "off";
export type CheckResult =
| "ready"
| "pcm-mismatch"
| "module-unavailable"
| "wrong-language-mode"
| "check-failed";
export interface CompilationDatabaseAnalysis {
kind: CompilerKind;
capability: ModuleCapability;
compilerPath?: string;
sourceFile?: string;
directory?: string;
arguments?: string[];
hasPrebuiltModules?: boolean;
modulePcmSourceDirectories?: string[];
modulePcmConsumerDirectories?: string[];
reason: string;
}
export interface ToolIdentity {
major: number;
minor: number;
patch: number;
revision?: string;
}
export interface ToolIdentityComparison {
compatible: boolean;
reason: string;
}
export interface ClangdArgumentOptions {
compilerPath: string;
compilationArguments?: readonly string[];
modulesSupport: ModulesSupportMode;
clangdIdentity?: ToolIdentity;
platform: NodeJS.Platform;
hasPrebuiltModules?: boolean;
workspaceFolder?: string;
}
export interface ClangdConfigurationPlan {
path: string;
arguments: string[];
changed: boolean;
}
interface CompilationCommand {
directory?: unknown;
file?: unknown;
arguments?: unknown;
command?: unknown;
}
interface CompilationCandidate extends CompilationDatabaseAnalysis {
moduleInterface: boolean;
projectSource: boolean;
moduleCompatibilityKey: string;
prebuiltModuleDirectory?: string;
}
function unavailable(reason: string): CompilationDatabaseAnalysis {
return {
kind: "unknown",
capability: "unavailable",
reason,
};
}
function splitCommand(command: string): string[] {
const result: string[] = [];
let token = "";
let quote: "'" | '"' | undefined;
for (let index = 0; index < command.length; index += 1) {
const character = command[index];
if (quote !== "'" && character === "\\" && index + 1 < command.length) {
const next = command[index + 1];
if (next === "\\" || next === "'" || next === '"' || /\s/.test(next)) {
token += next;
index += 1;
continue;
}
token += character;
continue;
}
if (character === "'" || character === '"') {
if (quote === character) {
quote = undefined;
} else if (quote === undefined) {
quote = character;
} else {
token += character;
}
continue;
}
if (/\s/.test(character) && quote === undefined) {
if (token.length > 0) {
result.push(token);
token = "";
}
continue;
}
token += character;
}
if (token.length > 0) {
result.push(token);
}
return result;
}
function commandArguments(command: CompilationCommand): string[] | undefined {
if (
Array.isArray(command.arguments)
&& command.arguments.length > 0
&& command.arguments.every((argument) => typeof argument === "string")
) {
return command.arguments;
}
if (typeof command.command === "string") {
const argumentsFromCommand = splitCommand(command.command);
return argumentsFromCommand.length > 0 ? argumentsFromCommand : undefined;
}
return undefined;
}
function compilerKind(compilerPath: string): CompilerKind {
const executable = path.win32.basename(compilerPath).toLowerCase();
const name = executable.endsWith(".exe") ? executable.slice(0, -4) : executable;
if (name === "clang" || name === "clang++" || name === "clang-cl") {
return "llvm";
}
if (name === "gcc" || name === "g++" || name === "c++") {
return "gcc";
}
if (name === "cl") {
return "msvc";
}
return "unknown";
}
function prebuiltModuleDirectory(arguments_: readonly string[]): string | undefined {
const flag = arguments_.find((argument) => argument.startsWith("-fprebuilt-module-path="));
if (flag === undefined) {
return undefined;
}
const value = flag.slice("-fprebuilt-module-path=".length);
return value.length >= 2 && value.startsWith('"') && value.endsWith('"')
? value.slice(1, -1)
: value;
}
function moduleCompatibilityKey(arguments_: readonly string[]): string {
const result: string[] = [];
for (let index = 1; index < arguments_.length; index += 1) {
const argument = arguments_[index];
if (argument === "-c" || argument === "-o" || argument === "-I") {
index += 1;
continue;
}
if (
argument.startsWith("-I")
|| argument.startsWith("-fmodule-file=")
|| argument.startsWith("-fprebuilt-module-path=")
) {
continue;
}
result.push(argument);
}
return result.join("\0");
}
export function analyzeCompilationDatabase(contents: string): CompilationDatabaseAnalysis {
let parsed: unknown;
try {
parsed = JSON.parse(contents);
} catch {
return unavailable("compile_commands.json 不是有效的 JSON");
}
if (!Array.isArray(parsed) || parsed.length === 0) {
return unavailable("compile_commands.json 至少需要包含一条编译命令");
}
const candidates: CompilationCandidate[] = [];
for (const value of parsed) {
if (value === null || typeof value !== "object") {
continue;
}
const command = value as CompilationCommand;
const args = commandArguments(command);
if (args === undefined) {
continue;
}
const kind = compilerKind(args[0]);
if (kind === "unknown") {
continue;
}
const hasPrebuiltModules = args.some((argument) => (
argument.startsWith("-fmodule-file=")
|| argument.startsWith("-fprebuilt-module-path=")
));
const directory = typeof command.directory === "string" ? command.directory : undefined;
const sourceFile = typeof command.file === "string"
? resolveCompilationSourceFile(directory, command.file)
: undefined;
const moduleInterface = /\.(?:cppm|ixx|mpp|ccm)$/i.test(sourceFile ?? "");
const projectSource = directory !== undefined
&& sourceFile !== undefined
&& isProjectSource(directory, sourceFile);
candidates.push({
kind,
capability: kind === "llvm" ? "full" : "syntax-only",
compilerPath: args[0],
sourceFile,
directory,
arguments: args,
hasPrebuiltModules,
moduleInterface,
projectSource,
moduleCompatibilityKey: moduleCompatibilityKey(args),
prebuiltModuleDirectory: prebuiltModuleDirectory(args),
reason: kind === "llvm"
? "Clang 编译命令可以由 clangd 使用"
: `${kind.toUpperCase()} 模块产物不能由 clangd 使用`,
});
}
if (candidates.length === 0) {
return unavailable("compile_commands.json 不包含受支持的编译器命令");
}
const score = (candidate: CompilationCandidate): number => {
const sourceFile = candidate.sourceFile ?? "";
const inProject = candidate.directory !== undefined && isWithinDirectory(candidate.directory, sourceFile);
return (inProject ? 200 : 0)
+ (candidate.projectSource ? 200 : 0)
+ (candidate.moduleInterface ? 0 : 100)
+ (candidate.hasPrebuiltModules ? 10 : 0);
};
const selected = candidates.reduce(
(best, candidate) => (score(candidate) > score(best) ? candidate : best),
);
const uniqueDirectories = (moduleInterface: boolean): string[] => [...new Set(
candidates
.filter((candidate) => (
candidate.kind === "llvm"
&& candidate.projectSource
&& candidate.moduleInterface === moduleInterface
&& candidate.compilerPath === selected.compilerPath
&& candidate.moduleCompatibilityKey === selected.moduleCompatibilityKey
))
.flatMap((candidate) => candidate.prebuiltModuleDirectory ?? []),
)];
const {
moduleInterface: _moduleInterface,
projectSource: _projectSource,
moduleCompatibilityKey: _moduleCompatibilityKey,
prebuiltModuleDirectory: _prebuiltModuleDirectory,
...analysis
} = selected;
return {
...analysis,
modulePcmSourceDirectories: uniqueDirectories(true),
modulePcmConsumerDirectories: uniqueDirectories(false),
};
}
function isWithinDirectory(directory: string, file: string): boolean {
const windows = /^[A-Za-z]:[\\/]/.test(directory) || directory.includes("\\")
|| /^[A-Za-z]:[\\/]/.test(file) || file.includes("\\");
const pathApi = windows ? path.win32 : path.posix;
const relative = pathApi.relative(pathApi.resolve(directory), pathApi.resolve(file));
return relative === ""
|| (relative !== ".." && !relative.startsWith(`..${pathApi.sep}`) && !pathApi.isAbsolute(relative));
}
function resolveCompilationSourceFile(directory: string | undefined, file: string): string {
if (directory === undefined) {
return file;
}
const windows = /^[A-Za-z]:[\\/]/.test(directory) || directory.includes("\\")
|| /^[A-Za-z]:[\\/]/.test(file) || file.includes("\\");
const pathApi = windows ? path.win32 : path.posix;
return pathApi.isAbsolute(file) ? file : pathApi.resolve(directory, file);
}
function isProjectSource(directory: string, file: string): boolean {
if (!isWithinDirectory(directory, file)) {
return false;
}
const windows = /^[A-Za-z]:[\\/]/.test(directory) || directory.includes("\\")
|| /^[A-Za-z]:[\\/]/.test(file) || file.includes("\\");
const pathApi = windows ? path.win32 : path.posix;
const relative = pathApi.relative(pathApi.resolve(directory), pathApi.resolve(file));
const firstComponent = relative.split(pathApi.sep)[0];
return firstComponent !== ".mcpp" && firstComponent !== "target";
}
function removeManagedArguments(arguments_: readonly string[]): string[] {
const result: string[] = [];
for (let index = 0; index < arguments_.length; index += 1) {
const argument = arguments_[index];
if (argument === "--experimental-modules-support") {
continue;
}
if (argument === "--query-driver") {
index += 1;
continue;
}
if (argument.startsWith("--query-driver=")) {
continue;
}
result.push(argument);
}
return result;
}
function hasExplicitLibcxxPath(arguments_: readonly string[]): boolean {
return arguments_.some((argument, index) => {
const value = argument === "-isystem"
? arguments_[index + 1] ?? ""
: argument.startsWith("-isystem")
? argument.slice("-isystem".length)
: "";
return /[\\/]include[\\/]c\+\+[\\/]v1(?:[\\/]|$)/.test(value);
});
}
function isHermeticClangCommand(arguments_: readonly string[] | undefined): boolean {
if (arguments_ === undefined) {
return false;
}
return arguments_.includes("--no-default-config")
&& arguments_.includes("-nostdinc++")
&& hasExplicitLibcxxPath(arguments_);
}
function expandWorkspaceVariables(argument: string, workspaceFolder?: string): string {
if (workspaceFolder === undefined) {
return argument;
}
return argument.replace(/\$\{workspace(?:Folder|Root)\}/g, () => workspaceFolder);
}
function shouldEnableExperimentalModules(options: ClangdArgumentOptions): boolean {
if (options.modulesSupport === "on") {
return true;
}
if (options.modulesSupport === "off") {
return false;
}
if (options.hasPrebuiltModules) {
return false;
}
const identity = options.clangdIdentity;
if (identity === undefined || identity.major < 21) {
return false;
}
return !(
options.platform === "win32"
&& identity.major === 20
&& identity.minor === 1
&& identity.patch === 7
);
}
export function buildClangdArguments(
existingArguments: readonly string[],
options: ClangdArgumentOptions,
): string[] {
const result = removeManagedArguments(existingArguments)
.map((argument) => expandWorkspaceVariables(argument, options.workspaceFolder));
if (!isHermeticClangCommand(options.compilationArguments)) {
result.push(`--query-driver=${options.compilerPath}`);
}
if (shouldEnableExperimentalModules(options)) {
result.push("--experimental-modules-support");
}
return result;
}
export function buildClangdConfigurationPlan(
currentPath: string,
currentArguments: readonly string[],
resolvedPath: string,
options: ClangdArgumentOptions,
): ClangdConfigurationPlan {
const arguments_ = buildClangdArguments(currentArguments, options);
return {
path: resolvedPath,
arguments: arguments_,
changed: currentPath !== resolvedPath
|| arguments_.length !== currentArguments.length
|| arguments_.some((argument, index) => argument !== currentArguments[index]),
};
}
export function parseToolIdentity(versionOutput: string): ToolIdentity | undefined {
const version = versionOutput.match(/\b(?:clangd|clang)(?:\s+version)?\s+(\d+)\.(\d+)(?:\.(\d+))?/i)
?? versionOutput.match(/\b(\d+)\.(\d+)(?:\.(\d+))?\b/);
if (version === null) {
return undefined;
}
const revision = versionOutput.match(/\b[0-9a-f]{7,40}\b/gi)?.at(-1);
return {
major: Number(version[1]),
minor: Number(version[2]),
patch: Number(version[3] ?? 0),
...(revision === undefined ? {} : { revision: revision.toLowerCase() }),
};
}
export function compareToolIdentities(
compiler: ToolIdentity | undefined,
clangd: ToolIdentity | undefined,
): ToolIdentityComparison {
if (compiler === undefined || clangd === undefined) {
return {
compatible: false,
reason: "无法确定两套 LLVM 工具的身份",
};
}
if (
compiler.major !== clangd.major
|| compiler.minor !== clangd.minor
|| compiler.patch !== clangd.patch
) {
return {
compatible: false,
reason: "编译器与 clangd 的 LLVM 版本不同",
};
}
if (compiler.revision === undefined || clangd.revision === undefined) {
return {
compatible: false,
reason: "LLVM 版本相同,但无法获得精确的 revision",
};
}
if (
!compiler.revision.startsWith(clangd.revision)
&& !clangd.revision.startsWith(compiler.revision)
) {
return {
compatible: false,
reason: "编译器与 clangd 的 LLVM revision 不同",
};
}
return {
compatible: true,
reason: "LLVM 版本和 revision 均匹配",
};
}
export function classifyCheckResult(exitCode: number, output: string): CheckResult {
if (exitCode === 0) {
return "ready";
}
const normalized = output.toLowerCase();
if (
normalized.includes("ast_file_different_branch")
|| normalized.includes("different branch")
|| normalized.includes("pch file uses an older pch format")
|| normalized.includes("ast_file_version_too_new")
|| normalized.includes("newer format that cannot be read")
|| normalized.includes("ast_file_version_too_old")
|| normalized.includes("older format that is no longer supported")
) {
return "pcm-mismatch";
}
if (
normalized.includes("don't get the module unit")
|| normalized.includes("failed to build module")
|| normalized.includes("module file not found")
|| /module ['\"].+['\"] not found/.test(normalized)
) {
return "module-unavailable";
}
if (
normalized.includes("unknown type name 'import'")
|| normalized.includes('unknown type name "import"')
|| normalized.includes("expected unqualified-id") && normalized.includes("import")
) {
return "wrong-language-mode";
}
if (normalized.includes("all checks completed")) {
const diagnostics = output
.split(/\r?\n/)
.filter((line) => /^\s*e\[/i.test(line));
if (diagnostics.length === 0 || diagnostics.every((line) => /\btweak:/i.test(line))) {
return "ready";
}
}
return "check-failed";
}