forked from mcpp-community/mcpp-vscode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.ts
More file actions
1249 lines (1171 loc) · 43.5 KB
/
Copy pathextension.ts
File metadata and controls
1249 lines (1171 loc) · 43.5 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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { existsSync, readFileSync } from "node:fs";
import process from "node:process";
import * as vscode from "vscode";
import {
analyzeCompilationDatabase,
buildClangdArguments,
buildClangdConfigurationPlan,
compareToolIdentities,
type CheckResult,
type CompilationDatabaseAnalysis,
type ModulesSupportMode,
type ToolIdentityComparison,
} from "./analysis";
import {
deriveClangdCandidates,
findNearestMcppProject,
type McppProjectDiscovery,
} from "./discovery";
import {
resolveXlingsExecutable,
llvmToolsVersionSpec,
xlingsInstallArgs,
} from "./llvmTools";
import { CLI_COMMANDS } from "./commands";
import { McppCliController } from "./cliController";
import { runClangdCheck, runToolVersion, type ToolVersionResult } from "./process";
import {
configurationReadyAfterRestart,
configurationAffectsModuleSupport,
createKeyedSingleFlightReconciler,
createLatestOperationTracker,
createSerialExecutor,
describeRefreshOutcome,
moduleSupportState,
registerCompilationDatabaseReconciliation,
shouldRestartClangd,
shouldCheckModuleSupport,
shouldRenderProjectStatus,
shouldUseWorkspaceClangd,
statusCommandForCapability,
workspaceAllowsToolExecution,
type ModuleSupportState,
} from "./workflow";
import { classifyTaskExit, type TaskCompletion } from "./tasks";
import { MCPP_MANIFEST_GLOB, registerInProjectContext } from "./inProject";
import { computeMcppTomlCompletions } from "./mcppTomlCompletion";
import {
buildModuleSetupPlan,
executeModuleSetup,
moduleSetupConfirmation,
type ModuleSetupBlockedReason,
type ModuleSetupStepResult,
} from "./moduleSetup";
const COMMAND_CONFIGURE = "mcpp.configureClangd";
const COMMAND_REFRESH = "mcpp.refreshCompilationDatabase";
const COMMAND_CHECK = "mcpp.checkModuleSupport";
interface ProjectContext {
project: McppProjectDiscovery;
analysis: CompilationDatabaseAnalysis;
}
interface ClangdResolution {
path: string;
version: ToolVersionResult;
comparison: ToolIdentityComparison;
}
interface ProjectReconciliation {
context: ProjectContext | undefined;
databaseFound: boolean;
configured: boolean;
}
interface ModuleStatus {
state: ModuleSupportState;
message: string;
}
type ConfigureMode = "automatic" | "interactive";
const moduleStatusByProject = new Map<string, ModuleStatus>();
const moduleCheckOperations = createLatestOperationTracker<string>();
let lastReconciledProjectRoot: string | undefined;
function findCurrentProject(): McppProjectDiscovery | undefined {
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor !== undefined) {
const activeUri = activeEditor.document.uri;
if (activeUri.scheme !== "file") {
return undefined;
}
const workspaceFolder = vscode.workspace.getWorkspaceFolder(activeUri);
if (workspaceFolder === undefined) {
return undefined;
}
return findNearestMcppProject(activeUri.fsPath, workspaceFolder.uri.fsPath);
}
for (const workspaceFolder of vscode.workspace.workspaceFolders ?? []) {
const project = findNearestMcppProject(workspaceFolder.uri.fsPath);
if (project !== undefined) {
return project;
}
}
return undefined;
}
function loadProjectContext(project: McppProjectDiscovery | undefined = findCurrentProject()): ProjectContext | undefined {
if (project === undefined) {
return undefined;
}
if (!existsSync(project.compilationDatabasePath)) {
return {
project,
analysis: {
kind: "unknown",
capability: "unavailable",
reason: `找不到编译数据库:${project.compilationDatabasePath}`,
},
};
}
try {
return {
project,
analysis: analyzeCompilationDatabase(readFileSync(project.compilationDatabasePath, "utf8")),
};
} catch (error) {
return {
project,
analysis: {
kind: "unknown",
capability: "unavailable",
reason: error instanceof Error ? error.message : String(error),
},
};
}
}
function moduleSetupBlockedMessage(reason: ModuleSetupBlockedReason): string {
switch (reason) {
case "project-toolchain-override":
return "当前项目显式固定了非 LLVM 工具链;一键配置不会修改 mcpp.toml,请先手动切换项目工具链。";
case "untrusted":
return "当前工作区未受信任,不会执行外部程序。请先信任工作区。";
case "busy":
return "已有 mcpp 操作正在运行,请等待完成后再试。";
case "unrecognized-inventory":
return "无法识别 mcpp 工具链状态,请查看 mcpp 输出频道并检查 mcpp 版本。";
}
}
function configurationTarget(uri: vscode.Uri): vscode.ConfigurationTarget {
return vscode.workspace.getWorkspaceFolder(uri) === undefined
? vscode.ConfigurationTarget.Workspace
: vscode.ConfigurationTarget.WorkspaceFolder;
}
function projectConfiguration(project: McppProjectDiscovery): vscode.WorkspaceConfiguration {
return vscode.workspace.getConfiguration("mcpp", vscode.Uri.file(project.root));
}
function officialClangdConfiguration(project: McppProjectDiscovery): vscode.WorkspaceConfiguration {
return vscode.workspace.getConfiguration("clangd", vscode.Uri.file(project.root));
}
function appendProcessOutput(
output: vscode.OutputChannel,
title: string,
executable: string,
args: string[],
result: { exitCode: number; stdout: string; stderr: string },
): void {
try {
output.appendLine(`\n[${new Date().toISOString()}] ${title}`);
output.appendLine(`$ ${executable} ${args.join(" ")}`);
if (result.stdout.length > 0) {
output.appendLine(result.stdout.trimEnd());
}
if (result.stderr.length > 0) {
output.appendLine(result.stderr.trimEnd());
}
output.appendLine(`[exit ${result.exitCode}]`);
} catch {
// 重载窗口时输出频道可能先于异步检查关闭。
}
}
function appendOutputLine(output: vscode.OutputChannel, value: string): void {
try {
output.appendLine(value);
} catch {
// 重载窗口时输出频道可能先于异步操作关闭。
}
}
async function resolveClangd(context: ProjectContext): Promise<ClangdResolution | undefined> {
const compilerPath = context.analysis.compilerPath;
if (compilerPath === undefined) {
return undefined;
}
const compilerVersion = await runToolVersion(compilerPath);
const configuredPath = projectConfiguration(context.project).get<string>("clangd.path", "").trim();
const candidates = configuredPath.length > 0
? [configuredPath]
: deriveClangdCandidates(compilerPath);
let fallback: ClangdResolution | undefined;
for (const candidate of candidates) {
if (candidate !== "clangd" && !existsSync(candidate)) {
continue;
}
const version = await runToolVersion(candidate);
if (version.exitCode !== 0 || version.identity === undefined) {
continue;
}
const comparison = compareToolIdentities(compilerVersion.identity, version.identity);
const resolution = { path: candidate, version, comparison };
if (comparison.compatible) {
return resolution;
}
fallback ??= resolution;
}
return fallback;
}
async function maybeDisableCppTools(project: McppProjectDiscovery): Promise<void> {
if (vscode.extensions.getExtension("ms-vscode.cpptools") === undefined) {
return;
}
if (!projectConfiguration(project).get<boolean>("configureCppTools", true)) {
return;
}
const uri = vscode.Uri.file(project.root);
const configuration = vscode.workspace.getConfiguration("C_Cpp", uri);
if (configuration.get<string>("intelliSenseEngine") === "disabled") {
return;
}
const disable = "关闭 IntelliSense";
const choice = await vscode.window.showWarningMessage(
"clangd 和 Microsoft C/C++ IntelliSense 都可能报告诊断。是否只关闭当前工作区的 cpptools IntelliSense?",
disable,
"保留 IntelliSense",
);
if (choice === disable) {
await configuration.update(
"intelliSenseEngine",
"disabled",
configurationTarget(uri),
);
}
}
async function restartClangd(): Promise<boolean> {
if (vscode.extensions.getExtension("llvm-vs-code-extensions.vscode-clangd") === undefined) {
return false;
}
try {
await vscode.commands.executeCommand("clangd.restart");
return true;
} catch {
// clangd 扩展可能尚未激活,但配置仍然已经写入。
return false;
}
}
async function configureClangd(
context: ProjectContext,
status: vscode.StatusBarItem,
output: vscode.OutputChannel,
mode: ConfigureMode,
forceRestart: boolean = false,
): Promise<boolean> {
const interactive = mode === "interactive";
if (context.analysis.capability === "syntax-only") {
if (interactive) {
await vscode.window.showWarningMessage(
`${context.analysis.kind.toUpperCase()} 模块产物无法由 clangd 读取。语法高亮仍然可用,但模块语义诊断需要 LLVM mcpp 工具链。`,
);
}
updateStatusBar(status, context);
return false;
}
if (context.analysis.capability !== "full" || context.analysis.compilerPath === undefined) {
if (interactive) {
await vscode.window.showWarningMessage(
`${context.analysis.reason} 请先运行“mcpp: 刷新编译数据库”。`,
);
}
return false;
}
if (!workspaceAllowsToolExecution(vscode.workspace.isTrusted)) {
const message = "当前工作区未受信任,mcpp 不会执行 CDB 中的编译器或 clangd,也不会接管 clangd 配置。";
if (interactive) {
await vscode.window.showWarningMessage(message);
} else {
appendOutputLine(output, `[自动配置] ${message}`);
}
return false;
}
const clangd = await resolveClangd(context);
if (clangd === undefined) {
const message = "没有找到可用的 clangd。请安装与 mcpp LLVM 编译器来自同一 revision 的 clangd,或设置 mcpp.clangd.path;clangd 可以来自 xlings llvm-tools,也可以独立安装。";
if (interactive) {
await vscode.window.showErrorMessage(message);
} else {
appendOutputLine(output, `[自动配置] ${message}`);
}
return false;
}
if (!clangd.comparison.compatible && !interactive) {
appendOutputLine(
output,
`[自动配置] 跳过不匹配的 clangd ${clangd.path}:${clangd.comparison.reason}。`,
);
return false;
}
const clangdConfiguration = officialClangdConfiguration(context.project);
const modulesSupport = projectConfiguration(context.project)
.get<ModulesSupportMode>("modulesSupport", "auto");
const plan = buildClangdConfigurationPlan(
clangdConfiguration.get<string>("path", "clangd"),
clangdConfiguration.get<string[]>("arguments", []),
clangd.path,
{
compilerPath: context.analysis.compilerPath,
compilationArguments: context.analysis.arguments,
modulesSupport,
clangdIdentity: clangd.version.identity,
platform: process.platform,
hasPrebuiltModules: context.analysis.hasPrebuiltModules,
workspaceFolder: context.project.root,
},
);
if (plan.changed) {
// clangd.arguments 不是资源域设置,必须与 clangd.path 一起写到工作区层级。
await clangdConfiguration.update("path", plan.path, vscode.ConfigurationTarget.Workspace);
await clangdConfiguration.update("arguments", plan.arguments, vscode.ConfigurationTarget.Workspace);
}
if (interactive) {
await maybeDisableCppTools(context.project);
}
const restartRequired = shouldRestartClangd(plan.changed, interactive, forceRestart);
const restartSucceeded = restartRequired ? await restartClangd() : false;
if (!configurationReadyAfterRestart(restartRequired, restartSucceeded)) {
const message = "clangd 配置已写入,但无法重启语言服务器。请查看 mcpp 输出频道,或手动执行 clangd 重启命令。";
if (interactive) {
await vscode.window.showErrorMessage(message);
} else {
appendOutputLine(output, `[自动配置] ${message}`);
}
return false;
}
updateStatusBar(status, context);
if (!clangd.comparison.compatible) {
await vscode.window.showWarningMessage(
`clangd 已配置,但 LLVM 身份与 mcpp 编译器不匹配:${clangd.comparison.reason}。`,
);
} else if (interactive) {
await vscode.window.showInformationMessage("mcpp 已为当前工作区配置匹配的 clangd。");
} else if (plan.changed) {
appendOutputLine(output, `[自动配置] clangd.path = ${plan.path}`);
}
return true;
}
function renderModuleStatus(status: vscode.StatusBarItem, moduleStatus: ModuleStatus): void {
status.command = COMMAND_CHECK;
status.show();
status.text = moduleStatus.state === "available"
? "$(pass) mcpp: 模块可用"
: "$(warning) mcpp: 模块不可用";
status.tooltip = moduleStatus.message;
}
function invalidateModuleStatus(projectRoot: string): void {
moduleCheckOperations.invalidate(projectRoot);
moduleStatusByProject.delete(projectRoot);
}
function storeModuleStatus(
status: vscode.StatusBarItem,
context: ProjectContext,
moduleStatus: ModuleStatus,
checkToken?: number,
): boolean {
if (
checkToken !== undefined
&& !moduleCheckOperations.isCurrent(context.project.root, checkToken)
) {
return false;
}
moduleStatusByProject.set(context.project.root, moduleStatus);
if (shouldRenderProjectStatus(findCurrentProject()?.root, context.project.root)) {
renderModuleStatus(status, moduleStatus);
}
return true;
}
function updateStatusBar(status: vscode.StatusBarItem, context?: ProjectContext): void {
const currentProjectRoot = findCurrentProject()?.root;
if (context === undefined) {
if (currentProjectRoot === undefined) {
status.hide();
}
return;
}
if (context.analysis.capability !== "full") {
invalidateModuleStatus(context.project.root);
}
if (!shouldRenderProjectStatus(currentProjectRoot, context.project.root)) {
return;
}
status.command = statusCommandForCapability(context.analysis.capability);
status.show();
if (context.analysis.capability === "full") {
const moduleStatus = moduleStatusByProject.get(context.project.root);
if (moduleStatus !== undefined) {
renderModuleStatus(status, moduleStatus);
return;
}
status.text = "$(symbol-interface) mcpp: LLVM 模块";
status.tooltip = "正在等待 clangd 检查模块编译命令和 PCM。";
return;
}
if (context.analysis.capability === "syntax-only") {
status.text = `$(info) mcpp: 仅${context.analysis.kind.toUpperCase()}语法`;
status.tooltip = `${context.analysis.reason} 模块语法高亮仍然可用。`;
return;
}
status.text = "$(warning) mcpp: 缺少模块 CDB";
status.tooltip = context.analysis.reason;
}
function checkResultMessage(classification: CheckResult): string {
switch (classification) {
case "ready":
return "clangd 已加载 mcpp 编译命令和模块产物。";
case "pcm-mismatch":
return "clangd 与 mcpp 编译器或 PCM 来自不同的 LLVM 构建。建议运行“一键配置模块代码提示”安装匹配的 llvm-tools,或设置 mcpp.clangd.path。";
case "module-unavailable":
return "clangd 无法加载所需模块产物,请运行“mcpp: 刷新编译数据库”,并检查 CDB 中的 PCM 路径。";
case "wrong-language-mode":
return "clangd 没有为当前文件读取 C++20 或更高版本的编译命令。";
default:
return "clangd 模块检查失败,完整诊断请查看 mcpp 输出频道。";
}
}
async function runModuleSupportCheck(
context: ProjectContext,
status: vscode.StatusBarItem,
output: vscode.OutputChannel,
mode: ConfigureMode,
): Promise<ModuleStatus | undefined> {
const interactive = mode === "interactive";
if (context.analysis.capability === "syntax-only") {
const message = `${context.analysis.kind.toUpperCase()} 模块产物不能由 clangd 消费,模块代码提示不可用。语法高亮仍然可用。`;
updateStatusBar(status, context);
if (interactive) {
const configure = "一键配置";
const choice = await vscode.window.showWarningMessage(
`${message}\n\n如需启用模块代码提示,请切换到 LLVM 工具链后重新构建。`,
configure,
"关闭",
);
if (choice === configure) {
await vscode.commands.executeCommand(CLI_COMMANDS.autoConfigureModules);
}
}
return undefined;
}
if (
context.analysis.capability !== "full"
|| context.analysis.compilerPath === undefined
|| context.analysis.sourceFile === undefined
) {
invalidateModuleStatus(context.project.root);
const message = context.analysis.capability === "full"
? "compile_commands.json 没有可供 clangd 检查的源文件。"
: context.analysis.reason;
if (context.analysis.capability === "full") {
storeModuleStatus(status, context, { state: "unavailable", message });
}
if (interactive) {
await vscode.window.showWarningMessage(message);
}
return context.analysis.capability === "full"
? { state: "unavailable", message }
: undefined;
}
if (!workspaceAllowsToolExecution(vscode.workspace.isTrusted)) {
invalidateModuleStatus(context.project.root);
const message = "当前工作区未受信任,不会执行 clangd 模块检查。信任工作区后扩展会自动重新检查。";
const moduleStatus = { state: "unavailable", message } as const;
storeModuleStatus(status, context, moduleStatus);
if (interactive) {
await vscode.window.showWarningMessage(message);
} else {
appendOutputLine(output, `[自动检查] ${message}`);
}
return moduleStatus;
}
const checkToken = moduleCheckOperations.begin(context.project.root);
moduleStatusByProject.delete(context.project.root);
if (shouldRenderProjectStatus(findCurrentProject()?.root, context.project.root)) {
status.command = COMMAND_CHECK;
status.text = "$(sync~spin) mcpp: 正在检查模块";
status.tooltip = "正在使用 clangd 检查模块编译命令和 PCM。";
status.show();
}
const clangd = await resolveClangd(context);
if (clangd === undefined) {
const message = "当前 LLVM 工具链没有找到可用的 clangd。请设置 mcpp.clangd.path。";
const moduleStatus = { state: "unavailable", message } as const;
if (!storeModuleStatus(status, context, moduleStatus, checkToken)) {
return undefined;
}
if (interactive) {
await vscode.window.showErrorMessage(message);
} else {
appendOutputLine(output, `[自动检查] ${message}`);
}
return moduleStatus;
}
const arguments_ = buildClangdArguments(
officialClangdConfiguration(context.project).get<string[]>("arguments", []),
{
compilerPath: context.analysis.compilerPath,
compilationArguments: context.analysis.arguments,
modulesSupport: projectConfiguration(context.project)
.get<ModulesSupportMode>("modulesSupport", "auto"),
clangdIdentity: clangd.version.identity,
platform: process.platform,
hasPrebuiltModules: context.analysis.hasPrebuiltModules,
workspaceFolder: context.project.root,
},
);
const result = await runClangdCheck(
clangd.path,
context.analysis.sourceFile,
context.project.root,
arguments_,
);
appendProcessOutput(
output,
interactive ? "检查模块支持" : "自动检查模块支持",
clangd.path,
[`--check=${context.analysis.sourceFile}`, ...arguments_],
result,
);
if (interactive) {
output.show(true);
}
const message = checkResultMessage(result.classification);
const moduleStatus = {
state: moduleSupportState(result.classification),
message,
};
if (!storeModuleStatus(status, context, moduleStatus, checkToken)) {
return undefined;
}
if (interactive) {
if (moduleStatus.state === "available") {
await vscode.window.showInformationMessage(message);
} else {
await vscode.window.showErrorMessage(message);
}
} else {
appendOutputLine(output, `[自动检查] ${message}`);
}
return moduleStatus;
}
async function updateModuleSupportForContext(
context: ProjectContext,
configured: boolean,
status: vscode.StatusBarItem,
output: vscode.OutputChannel,
): Promise<boolean> {
if (shouldCheckModuleSupport(
context.analysis.capability,
configured,
context.analysis.sourceFile,
)) {
const moduleStatus = await runModuleSupportCheck(context, status, output, "automatic");
return moduleStatus?.state === "available";
}
if (context.analysis.capability === "full") {
invalidateModuleStatus(context.project.root);
const message = configured
? "compile_commands.json 没有可供 clangd 检查的源文件。"
: "clangd 未完成配置,模块语义当前不可用。详情请查看 mcpp 输出频道。";
storeModuleStatus(status, context, { state: "unavailable", message });
}
return false;
}
async function executeXlingsInstallTask(
xlingsPath: string,
args: string[],
cwd: string,
): Promise<TaskCompletion> {
const task = new vscode.Task(
{ type: "mcpp-xlings", command: args[0] ?? "xlings" },
vscode.TaskScope.Workspace,
"mcpp: 安装 llvm-tools",
"mcpp",
new vscode.ProcessExecution(xlingsPath, args, { cwd }),
);
task.presentationOptions = {
reveal: vscode.TaskRevealKind.Always,
panel: vscode.TaskPanelKind.Dedicated,
focus: true,
clear: true,
showReuseMessage: false,
};
let execution: vscode.TaskExecution | undefined;
let earlyCompletion: TaskCompletion | undefined;
let settled = false;
let processEndSubscription: vscode.Disposable | undefined;
let taskEndSubscription: vscode.Disposable | undefined;
const disposeListeners = (): void => {
processEndSubscription?.dispose();
taskEndSubscription?.dispose();
};
const finish = (completion: TaskCompletion): void => {
if (settled) {
return;
}
settled = true;
disposeListeners();
resolveCompletion?.(completion);
};
let resolveCompletion: ((completion: TaskCompletion) => void) | undefined;
const completion = new Promise<TaskCompletion>((resolve) => {
resolveCompletion = resolve;
processEndSubscription = vscode.tasks.onDidEndTaskProcess((event) => {
if (event.execution.task !== task) {
return;
}
const classified = classifyTaskExit(event.exitCode);
if (execution === undefined) {
earlyCompletion ??= classified;
return;
}
finish(classified);
});
taskEndSubscription = vscode.tasks.onDidEndTask((event) => {
if (event.execution.task !== task) {
return;
}
const classified = classifyTaskExit(undefined);
if (execution === undefined) {
earlyCompletion ??= classified;
return;
}
finish(classified);
});
});
try {
execution = await vscode.tasks.executeTask(task);
} catch (error) {
disposeListeners();
throw error;
}
if (earlyCompletion !== undefined) {
finish(earlyCompletion);
}
return completion;
}
async function autoConfigureModulesWizard(
context: ProjectContext,
status: vscode.StatusBarItem,
output: vscode.OutputChannel,
cliController: McppCliController,
): Promise<void> {
appendOutputLine(output, "[一键配置] 开始一键配置模块代码提示...");
if (!vscode.workspace.isTrusted) {
await vscode.window.showWarningMessage(moduleSetupBlockedMessage("untrusted"));
return;
}
const inventory = await cliController.readToolchainInventory(context.project);
if (inventory === undefined) {
return;
}
const decision = buildModuleSetupPlan(
inventory,
context.analysis.capability,
vscode.workspace.isTrusted,
cliController.isBusy(),
);
if (decision.kind === "blocked") {
await vscode.window.showWarningMessage(moduleSetupBlockedMessage(decision.reason));
return;
}
const confirmation = moduleSetupConfirmation(context.analysis.capability, decision);
const choice = await vscode.window.showWarningMessage(
confirmation.message,
{ modal: true, detail: confirmation.detail },
"确认一键配置",
);
if (choice !== "确认一键配置") {
return;
}
let currentContext = context;
const outcome = await executeModuleSetup(decision, {
preparePlan: () => cliController.runAutomaticModuleSetup(decision),
reload: async (): Promise<ModuleSetupStepResult> => {
const refreshed = loadProjectContext(context.project);
if (refreshed === undefined) {
return { stage: "reload", state: "failed", detail: "无法重新加载 mcpp 工程。" };
}
currentContext = refreshed;
updateStatusBar(status, currentContext);
if (currentContext.analysis.capability !== "full" || currentContext.analysis.kind !== "llvm") {
return {
stage: "reload",
state: "failed",
detail: "构建后没有得到可供 clangd 使用的 LLVM 编译数据库。",
};
}
return { stage: "reload", state: "succeeded" };
},
ensureClangd: async (): Promise<ModuleSetupStepResult> => {
const clangd = await resolveClangd(currentContext);
if (clangd?.comparison.compatible) {
const configured = await configureClangd(currentContext, status, output, "automatic", true);
return configured
? { stage: "clangd", state: "succeeded" }
: { stage: "clangd", state: "failed", detail: "clangd 配置未完成。" };
}
const xlingsPath = await resolveXlingsExecutable(
cliController.mcppExecutable(currentContext.project),
);
const compilerPath = currentContext.analysis.compilerPath;
if (xlingsPath === undefined || compilerPath === undefined) {
return {
stage: "clangd",
state: "failed",
detail: "未找到 xlings 或 LLVM 编译器,无法安装匹配的 llvm-tools。",
};
}
const compilerVersion = await runToolVersion(compilerPath);
const installArgs = xlingsInstallArgs(
compilerVersion.identity === undefined ? undefined : llvmToolsVersionSpec(compilerVersion.identity),
);
const installed = await executeXlingsInstallTask(xlingsPath, installArgs, currentContext.project.root);
appendOutputLine(
output,
`[一键配置] xlings install 完成(退出码 ${installed.exitCode ?? "未知"})`,
);
if (installed.state !== "succeeded") {
return {
stage: "clangd",
state: installed.state,
exitCode: installed.exitCode,
detail: installed.state === "cancelled" ? "llvm-tools 安装已取消。" : "llvm-tools 安装失败。",
};
}
const refreshed = loadProjectContext(currentContext.project);
if (refreshed === undefined) {
return { stage: "clangd", state: "failed", detail: "安装 llvm-tools 后无法重新加载工程。" };
}
currentContext = refreshed;
updateStatusBar(status, currentContext);
const resolved = await resolveClangd(currentContext);
if (resolved === undefined || !resolved.comparison.compatible) {
return { stage: "clangd", state: "failed", detail: "未找到与 LLVM 编译器匹配的 clangd。" };
}
const configured = await configureClangd(currentContext, status, output, "automatic", true);
return configured
? { stage: "clangd", state: "succeeded" }
: { stage: "clangd", state: "failed", detail: "clangd 配置未完成。" };
},
checkModules: async (): Promise<ModuleSetupStepResult> => {
const moduleStatus = await runModuleSupportCheck(currentContext, status, output, "automatic");
return moduleStatus?.state === "available"
? { stage: "check", state: "succeeded" }
: { stage: "check", state: "failed", detail: "模块支持检查未通过。" };
},
});
if (outcome.state === "succeeded") {
if (outcome.degraded) {
await vscode.window.showWarningMessage("构建失败,语言服务已刷新。请查看任务终端获取构建错误。");
} else {
await vscode.window.showInformationMessage("mcpp 模块代码提示一键配置完成。");
}
} else if (outcome.state === "cancelled") {
await vscode.window.showWarningMessage(`一键配置已取消(${outcome.stage})。`);
} else {
await vscode.window.showErrorMessage(`一键配置失败(${outcome.stage})。${outcome.steps.at(-1)?.detail ?? "请查看 mcpp 输出频道。"}`);
}
}
// mcpp.toml 结构补全:建议由纯函数 computeMcppTomlCompletions 计算,这里只做
// vscode 类型映射。范围:段头 snippet + 开放词汇段的写法模板;不含字段键/枚举
// 与依赖数据(分别等上游版本化 schema 与批量 catalog 接口)。
const mcppTomlCompletionKinds = {
section: vscode.CompletionItemKind.Folder,
template: vscode.CompletionItemKind.Snippet,
} as const;
const mcppTomlCompletionProvider: vscode.CompletionItemProvider = {
provideCompletionItems(document, position) {
// mcpp.toml 结构补全由 mcpp.tomlCompletion 控制,按文档作用域读取。
if (!vscode.workspace.getConfiguration("mcpp", document.uri).get<boolean>("tomlCompletion", true)) {
return undefined;
}
const lines: string[] = [];
for (let line = 0; line <= position.line; line += 1) {
lines.push(document.lineAt(line).text);
}
return computeMcppTomlCompletions(lines, position.line, position.character).map((suggestion) => {
const item = new vscode.CompletionItem(
suggestion.label,
mcppTomlCompletionKinds[suggestion.kind],
);
item.detail = suggestion.detail;
if (suggestion.documentation !== undefined) {
item.documentation = new vscode.MarkdownString(suggestion.documentation);
}
if (suggestion.insertSnippet !== undefined) {
item.insertText = new vscode.SnippetString(suggestion.insertSnippet);
}
item.range = new vscode.Range(
position.line,
suggestion.range.startCharacter,
position.line,
suggestion.range.endCharacter,
);
return item;
});
},
};
export async function activate(extensionContext: vscode.ExtensionContext): Promise<void> {
moduleStatusByProject.clear();
moduleCheckOperations.clear();
const output = vscode.window.createOutputChannel("mcpp");
const status = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 50);
const refreshStatus = (): void => updateStatusBar(status, loadProjectContext());
const runGuarded = (operation: () => Promise<void>): (() => Promise<void>) => async () => {
try {
await operation();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
appendOutputLine(output, `发生未预期错误:${message}`);
void vscode.window.showErrorMessage(`mcpp:${message}`);
}
};
const manifestWatcher = vscode.workspace.createFileSystemWatcher(MCPP_MANIFEST_GLOB);
const compilationDatabaseWatcher = vscode.workspace.createFileSystemWatcher("**/compile_commands.json");
const inProjectContext = registerInProjectContext({
currentProject: findCurrentProject,
setContextValue: (key, value) => vscode.commands.executeCommand("setContext", key, value),
subscribe: (listener) => [
vscode.window.onDidChangeActiveTextEditor(listener),
vscode.workspace.onDidChangeWorkspaceFolders(listener),
manifestWatcher.onDidCreate(listener),
manifestWatcher.onDidDelete(listener),
],
});
const executeWithWorkspaceClangd = createSerialExecutor();
const reconcileProjectContext = async (
project: McppProjectDiscovery | undefined,
forceRestart: boolean,
): Promise<ProjectReconciliation> => {
const context = loadProjectContext(project);
updateStatusBar(status, context);
if (context === undefined) {
return {
context,
databaseFound: false,
configured: false,
};
}
const configured = await configureClangd(
context,
status,
output,
"automatic",
forceRestart,
);
await updateModuleSupportForContext(context, configured, status, output);
return {
context,
databaseFound: existsSync(context.project.compilationDatabasePath),
configured,
};
};
const reconcileProjectByRoot = createKeyedSingleFlightReconciler(
(projectRoot: string, forceRestart) => executeWithWorkspaceClangd(
async () => {
const project = findNearestMcppProject(projectRoot);
if (!shouldUseWorkspaceClangd(findCurrentProject()?.root, projectRoot)) {
const context = loadProjectContext(project);
return {
context,
databaseFound: context !== undefined
&& existsSync(context.project.compilationDatabasePath),
configured: false,
};
}
return reconcileProjectContext(project, forceRestart);
},
),
);
const reconcileProject = (
project: McppProjectDiscovery,
forceRestart: boolean = false,
): Promise<ProjectReconciliation> => {
invalidateModuleStatus(project.root);
return reconcileProjectByRoot(project.root, forceRestart);
};
const requestAutomaticReconciliation = (
compilationDatabase: vscode.Uri,
forceRestart: boolean,
): void => {
const project = findNearestMcppProject(compilationDatabase.fsPath);
if (project === undefined) {
return;
}
invalidateModuleStatus(project.root);
if (!shouldUseWorkspaceClangd(findCurrentProject()?.root, project.root)) {
return;
}
void reconcileProject(project, forceRestart).catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
appendOutputLine(output, `[自动配置] ${message}`);
});
};
const requestCurrentProjectReconciliation = (forceRestart: boolean): void => {
const project = findCurrentProject();
if (project === undefined) {
refreshStatus();
return;
}
void reconcileProject(project, forceRestart).catch((error: unknown) => {
const message = error instanceof Error ? error.message : String(error);
appendOutputLine(output, `[自动配置] ${message}`);
});
};
const configurationWatcher = vscode.workspace.onDidChangeConfiguration((event) => {
const project = findCurrentProject();
if (project === undefined) {
return;
}
const uri = vscode.Uri.file(project.root);
if (configurationAffectsModuleSupport(
(section) => event.affectsConfiguration(section, uri),
)) {
requestCurrentProjectReconciliation(true);
}
});
const trustWatcher = vscode.workspace.onDidGrantWorkspaceTrust(() => {
requestCurrentProjectReconciliation(true);
});
const afterProjectTask = async (
project: McppProjectDiscovery,
kind: "build" | "run" | "test" | "clean",
completion: { state: "succeeded" | "failed" | "cancelled"; exitCode?: number },