-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathextension.ts
1389 lines (1235 loc) · 65.8 KB
/
extension.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
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
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved.
* See 'LICENSE' in the project root for license information.
* ------------------------------------------------------------------------------------------ */
'use strict';
import * as fs from 'fs';
// Node.js 18 fetch isn't available until VS 1.82.
import fetch from 'node-fetch';
import * as StreamZip from 'node-stream-zip';
import * as os from 'os';
import * as path from 'path';
import * as vscode from 'vscode';
import { Range } from 'vscode-languageclient';
import * as nls from 'vscode-nls';
import { TargetPopulation } from 'vscode-tas-client';
import * as which from 'which';
import { logAndReturn } from '../Utility/Async/returns';
import * as util from '../common';
import { getCrashCallStacksChannel } from '../logger';
import { PlatformInformation } from '../platform';
import * as telemetry from '../telemetry';
import { Client, DefaultClient, DoxygenCodeActionCommandArguments, openFileVersions } from './client';
import { ClientCollection } from './clientCollection';
import { CodeActionDiagnosticInfo, CodeAnalysisDiagnosticIdentifiersAndUri, codeAnalysisAllFixes, codeAnalysisCodeToFixes, codeAnalysisFileToCodeActions } from './codeAnalysis';
import { registerRelatedFilesProvider } from './copilotProviders';
import { CppBuildTaskProvider } from './cppBuildTaskProvider';
import { getCustomConfigProviders } from './customProviders';
import { getLanguageConfig } from './languageConfig';
import { CppConfigurationLanguageModelTool } from './lmTool';
import { PersistentState } from './persistentState';
import { NodeType, TreeNode } from './referencesModel';
import { CppSettings } from './settings';
import { LanguageStatusUI, getUI } from './ui';
import { makeLspRange, rangeEquals, showInstallCompilerWalkthrough } from './utils';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
export const CppSourceStr: string = "C/C++";
export const configPrefix: string = "C/C++: ";
let prevMacCrashFile: string;
let prevCppCrashFile: string;
let prevCppCrashCallStackData: string = "";
export let clients: ClientCollection;
let activeDocument: vscode.TextDocument | undefined;
let ui: LanguageStatusUI;
const disposables: vscode.Disposable[] = [];
const commandDisposables: vscode.Disposable[] = [];
let languageConfigurations: vscode.Disposable[] = [];
let intervalTimer: NodeJS.Timeout;
let codeActionProvider: vscode.Disposable;
export const intelliSenseDisabledError: string = "Do not activate the extension when IntelliSense is disabled.";
type VcpkgDatabase = Record<string, string[]>; // Stored as <header file entry> -> [<port name>]
let vcpkgDbPromise: Promise<VcpkgDatabase>;
async function initVcpkgDatabase(): Promise<VcpkgDatabase> {
const database: VcpkgDatabase = {};
try {
const zip = new StreamZip.async({ file: util.getExtensionFilePath('VCPkgHeadersDatabase.zip') });
try {
const data = await zip.entryData('VCPkgHeadersDatabase.txt');
const lines = data.toString().split('\n');
lines.forEach(line => {
const portFilePair: string[] = line.split(':');
if (portFilePair.length !== 2) {
return;
}
const portName: string = portFilePair[0];
const relativeHeader: string = portFilePair[1].trimEnd();
if (!database[relativeHeader]) {
database[relativeHeader] = [];
}
database[relativeHeader].push(portName);
});
} catch {
console.log("Unable to parse vcpkg database file.");
}
await zip.close();
} catch {
console.log("Unable to open vcpkg database file.");
}
return database;
}
function getVcpkgHelpAction(): vscode.CodeAction {
const dummy: any[] = [{}]; // To distinguish between entry from CodeActions and the command palette
return {
command: { title: 'vcpkgOnlineHelpSuggested', command: 'C_Cpp.VcpkgOnlineHelpSuggested', arguments: dummy },
title: localize("learn.how.to.install.a.library", "Learn how to install a library for this header with vcpkg"),
kind: vscode.CodeActionKind.QuickFix
};
}
function getVcpkgClipboardInstallAction(port: string): vscode.CodeAction {
return {
command: { title: 'vcpkgClipboardInstallSuggested', command: 'C_Cpp.VcpkgClipboardInstallSuggested', arguments: [[port]] },
title: localize("copy.vcpkg.command", "Copy vcpkg command to install '{0}' to the clipboard", port),
kind: vscode.CodeActionKind.QuickFix
};
}
async function lookupIncludeInVcpkg(document: vscode.TextDocument, line: number): Promise<string[]> {
const matches: RegExpMatchArray | null = document.lineAt(line).text.match(/#include\s*[<"](?<includeFile>[^>"]*)[>"]/);
if (!matches || !matches.length || !matches.groups) {
return [];
}
const missingHeader: string = matches.groups.includeFile.replace(/\//g, '\\');
let portsWithHeader: string[] | undefined;
const vcpkgDb: VcpkgDatabase = await vcpkgDbPromise;
if (vcpkgDb) {
portsWithHeader = vcpkgDb[missingHeader];
}
return portsWithHeader ? portsWithHeader : [];
}
function isMissingIncludeDiagnostic(diagnostic: vscode.Diagnostic): boolean {
const missingIncludeCode: number = 1696;
if (diagnostic.code === null || diagnostic.code === undefined || !diagnostic.source) {
return false;
}
return diagnostic.code === missingIncludeCode && diagnostic.source === 'C/C++';
}
function sendActivationTelemetry(): void {
const activateEvent: Record<string, string> = {};
// Don't log telemetry for machineId if it's a special value used by the dev host: someValue.machineid
if (vscode.env.machineId !== "someValue.machineId") {
const machineIdPersistentState: PersistentState<string | undefined> = new PersistentState<string | undefined>("CPP.machineId", undefined);
if (!machineIdPersistentState.Value) {
activateEvent.newMachineId = vscode.env.machineId;
} else if (machineIdPersistentState.Value !== vscode.env.machineId) {
activateEvent.newMachineId = vscode.env.machineId;
activateEvent.oldMachineId = machineIdPersistentState.Value;
}
machineIdPersistentState.Value = vscode.env.machineId;
}
if (vscode.env.uiKind === vscode.UIKind.Web) {
activateEvent.WebUI = "1";
}
telemetry.logLanguageServerEvent("Activate", activateEvent);
}
/**
* activate: set up the extension for language services
*/
export async function activate(): Promise<void> {
sendActivationTelemetry();
const checkForConflictingExtensions: PersistentState<boolean> = new PersistentState<boolean>("CPP." + util.packageJson.version + ".checkForConflictingExtensions", true);
if (checkForConflictingExtensions.Value) {
checkForConflictingExtensions.Value = false;
const clangCommandAdapterActive: boolean = vscode.extensions.all.some((extension: vscode.Extension<any>): boolean =>
extension.isActive && extension.id === "mitaki28.vscode-clang");
if (clangCommandAdapterActive) {
telemetry.logLanguageServerEvent("conflictingExtension");
}
}
clients = new ClientCollection();
ui = getUI();
// There may have already been registered CustomConfigurationProviders.
// Request for configurations from those providers.
clients.forEach(client => {
getCustomConfigProviders().forEach(provider => void client.onRegisterCustomConfigurationProvider(provider));
});
disposables.push(vscode.workspace.onDidChangeConfiguration(onDidChangeSettings));
disposables.push(vscode.workspace.onDidChangeTextDocument(onDidChangeTextDocument));
disposables.push(vscode.window.onDidChangeTextEditorVisibleRanges((e) => clients.ActiveClient.enqueue(async () => onDidChangeTextEditorVisibleRanges(e))));
disposables.push(vscode.window.onDidChangeActiveTextEditor((e) => clients.ActiveClient.enqueue(async () => onDidChangeActiveTextEditor(e))));
ui.didChangeActiveEditor(); // Handle already active documents (for non-cpp files that we don't register didOpen).
disposables.push(vscode.window.onDidChangeTextEditorSelection((e) => clients.ActiveClient.enqueue(async () => onDidChangeTextEditorSelection(e))));
disposables.push(vscode.window.onDidChangeVisibleTextEditors((e) => clients.ActiveClient.enqueue(async () => onDidChangeVisibleTextEditors(e))));
updateLanguageConfigurations();
reportMacCrashes();
vcpkgDbPromise = initVcpkgDatabase();
void clients.ActiveClient.ready.then(() => intervalTimer = global.setInterval(onInterval, 2500));
await registerCommands(true);
vscode.tasks.onDidStartTask(() => getActiveClient().PauseCodeAnalysis());
vscode.tasks.onDidEndTask(event => {
getActiveClient().ResumeCodeAnalysis();
if (event.execution.task.definition.type === CppBuildTaskProvider.CppBuildScriptType
|| event.execution.task.name.startsWith(configPrefix)) {
if (event.execution.task.scope !== vscode.TaskScope.Global && event.execution.task.scope !== vscode.TaskScope.Workspace) {
const folder: vscode.WorkspaceFolder | undefined = event.execution.task.scope;
if (folder) {
const settings: CppSettings = new CppSettings(folder.uri);
if (settings.codeAnalysisRunOnBuild && settings.clangTidyEnabled) {
void clients.getClientFor(folder.uri).handleRunCodeAnalysisOnAllFiles().catch(logAndReturn.undefined);
}
return;
}
}
const settings: CppSettings = new CppSettings();
if (settings.codeAnalysisRunOnBuild && settings.clangTidyEnabled) {
void clients.ActiveClient.handleRunCodeAnalysisOnAllFiles().catch(logAndReturn.undefined);
}
}
});
const selector: vscode.DocumentSelector = [
{ scheme: 'file', language: 'c' },
{ scheme: 'file', language: 'cpp' },
{ scheme: 'file', language: 'cuda-cpp' }
];
codeActionProvider = vscode.languages.registerCodeActionsProvider(selector, {
provideCodeActions: async (document: vscode.TextDocument, range: vscode.Range, context: vscode.CodeActionContext): Promise<vscode.CodeAction[]> => {
if (!await clients.ActiveClient.getVcpkgEnabled()) {
return [];
}
// Generate vcpkg install/help commands if the incoming doc/range is a missing include error
if (!context.diagnostics.some(isMissingIncludeDiagnostic)) {
return [];
}
const ports: string[] = await lookupIncludeInVcpkg(document, range.start.line);
if (ports.length <= 0) {
return [];
}
telemetry.logLanguageServerEvent('codeActionsProvided', { "source": "vcpkg" });
if (!await clients.ActiveClient.getVcpkgInstalled()) {
return [getVcpkgHelpAction()];
}
const actions: vscode.CodeAction[] = ports.map<vscode.CodeAction>(getVcpkgClipboardInstallAction);
return actions;
}
});
await vscode.commands.executeCommand('setContext', 'cpptools.msvcEnvironmentFound', util.hasMsvcEnvironment());
// Log cold start.
const activeEditor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (activeEditor) {
clients.timeTelemetryCollector.setFirstFile(activeEditor.document.uri);
activeDocument = activeEditor.document;
}
if (util.extensionContext) {
// lmTools wasn't stabilized until 1.95, but (as of October 2024)
// cpptools can be installed on older versions of VS Code. See
// https://github.com/microsoft/vscode-cpptools/blob/main/Extension/package.json#L14
const version = util.getVsCodeVersion();
if (version[0] > 1 || (version[0] === 1 && version[1] >= 95)) {
const tool = vscode.lm.registerTool('cpptools-lmtool-configuration', new CppConfigurationLanguageModelTool());
disposables.push(tool);
}
}
await registerRelatedFilesProvider();
}
export function updateLanguageConfigurations(): void {
languageConfigurations.forEach(d => d.dispose());
languageConfigurations = [];
languageConfigurations.push(vscode.languages.setLanguageConfiguration('c', getLanguageConfig('c')));
languageConfigurations.push(vscode.languages.setLanguageConfiguration('cpp', getLanguageConfig('cpp')));
languageConfigurations.push(vscode.languages.setLanguageConfiguration('cuda-cpp', getLanguageConfig('cuda-cpp')));
}
/**
* workspace events
*/
async function onDidChangeSettings(event: vscode.ConfigurationChangeEvent): Promise<void> {
const client: Client = clients.getDefaultClient();
if (client instanceof DefaultClient) {
const defaultClient: DefaultClient = client as DefaultClient;
const changedDefaultClientSettings: Record<string, string> = await defaultClient.onDidChangeSettings(event);
clients.forEach(client => {
if (client !== defaultClient) {
void client.onDidChangeSettings(event).catch(logAndReturn.undefined);
}
});
const newUpdateChannel: string = changedDefaultClientSettings.updateChannel;
if (newUpdateChannel || event.affectsConfiguration("extensions.autoUpdate")) {
UpdateInsidersAccess();
}
}
}
async function onDidChangeTextDocument(event: vscode.TextDocumentChangeEvent): Promise<void> {
const me: Client = clients.getClientFor(event.document.uri);
me.onDidChangeTextDocument(event);
}
let noActiveEditorTimeout: NodeJS.Timeout | undefined;
async function onDidChangeTextEditorVisibleRanges(event: vscode.TextEditorVisibleRangesChangeEvent): Promise<void> {
if (util.isCpp(event.textEditor.document)) {
await clients.getDefaultClient().onDidChangeTextEditorVisibleRanges(event.textEditor.document.uri);
}
}
function onDidChangeActiveTextEditor(editor?: vscode.TextEditor): void {
/* need to notify the affected client(s) */
console.assert(clients !== undefined, "client should be available before active editor is changed");
if (clients === undefined) {
return;
}
if (noActiveEditorTimeout) {
clearTimeout(noActiveEditorTimeout);
noActiveEditorTimeout = undefined;
}
if (!editor) {
// When switching between documents, VS Code is setting the active editor to undefined
// temporarily, so this prevents the C++-related status bar items from flickering off/on.
noActiveEditorTimeout = setTimeout(() => {
activeDocument = undefined;
ui.didChangeActiveEditor();
noActiveEditorTimeout = undefined;
}, 100);
void clients.didChangeActiveEditor(undefined).catch(logAndReturn.undefined);
} else {
ui.didChangeActiveEditor();
if (util.isCppOrRelated(editor.document)) {
if (util.isCpp(editor.document)) {
activeDocument = editor.document;
void clients.didChangeActiveEditor(editor).catch(logAndReturn.undefined);
} else {
activeDocument = undefined;
void clients.didChangeActiveEditor(undefined).catch(logAndReturn.undefined);
}
//clients.ActiveClient.selectionChanged(makeLspRange(editor.selection));
} else {
activeDocument = undefined;
}
}
}
function onDidChangeTextEditorSelection(event: vscode.TextEditorSelectionChangeEvent): void {
if (!util.isCpp(event.textEditor.document)) {
return;
}
clients.ActiveClient.selectionChanged(makeLspRange(event.selections[0]));
}
async function onDidChangeVisibleTextEditors(editors: readonly vscode.TextEditor[]): Promise<void> {
const cppEditors: vscode.TextEditor[] = editors.filter(e => util.isCpp(e.document));
await clients.getDefaultClient().onDidChangeVisibleTextEditors(cppEditors);
}
function onInterval(): void {
// TODO: do we need to pump messages to all clients? depends on what we do with the icons, I suppose.
clients.ActiveClient.onInterval();
}
/**
* registered commands
*/
export async function registerCommands(enabled: boolean): Promise<void> {
commandDisposables.forEach(d => d.dispose());
commandDisposables.length = 0;
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.SwitchHeaderSource', enabled ? onSwitchHeaderSource : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ResetDatabase', enabled ? onResetDatabase : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.SelectIntelliSenseConfiguration', enabled ? selectIntelliSenseConfiguration : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.InstallCompiler', enabled ? installCompiler : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationSelect', enabled ? onSelectConfiguration : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationProviderSelect', enabled ? onSelectConfigurationProvider : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEditJSON', enabled ? onEditConfigurationJSON : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEditUI', enabled ? onEditConfigurationUI : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ConfigurationEdit', enabled ? onEditConfiguration : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.AddToIncludePath', enabled ? onAddToIncludePath : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.EnableErrorSquiggles', enabled ? onEnableSquiggles : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.DisableErrorSquiggles', enabled ? onDisableSquiggles : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ToggleDimInactiveRegions', enabled ? onToggleDimInactiveRegions : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.PauseParsing', enabled ? onPauseParsing : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ResumeParsing', enabled ? onResumeParsing : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.PauseCodeAnalysis', enabled ? onPauseCodeAnalysis : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ResumeCodeAnalysis', enabled ? onResumeCodeAnalysis : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.CancelCodeAnalysis', enabled ? onCancelCodeAnalysis : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ShowActiveCodeAnalysisCommands', enabled ? onShowActiveCodeAnalysisCommands : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ShowIdleCodeAnalysisCommands', enabled ? onShowIdleCodeAnalysisCommands : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ShowReferencesProgress', enabled ? onShowReferencesProgress : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.TakeSurvey', enabled ? onTakeSurvey : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.LogDiagnostics', enabled ? onLogDiagnostics : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.RescanWorkspace', enabled ? onRescanWorkspace : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ShowReferenceItem', enabled ? onShowRefCommand : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.referencesViewGroupByType', enabled ? onToggleRefGroupView : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.referencesViewUngroupByType', enabled ? onToggleRefGroupView : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.VcpkgClipboardInstallSuggested', enabled ? onVcpkgClipboardInstallSuggested : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.VcpkgOnlineHelpSuggested', enabled ? onVcpkgOnlineHelpSuggested : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.GenerateEditorConfig', enabled ? onGenerateEditorConfig : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.GoToNextDirectiveInGroup', enabled ? onGoToNextDirectiveInGroup : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.GoToPrevDirectiveInGroup', enabled ? onGoToPrevDirectiveInGroup : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.RunCodeAnalysisOnActiveFile', enabled ? onRunCodeAnalysisOnActiveFile : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.RunCodeAnalysisOnOpenFiles', enabled ? onRunCodeAnalysisOnOpenFiles : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.RunCodeAnalysisOnAllFiles', enabled ? onRunCodeAnalysisOnAllFiles : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.RemoveCodeAnalysisProblems', enabled ? onRemoveCodeAnalysisProblems : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.RemoveAllCodeAnalysisProblems', enabled ? onRemoveAllCodeAnalysisProblems : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.FixThisCodeAnalysisProblem', enabled ? onFixThisCodeAnalysisProblem : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.FixAllTypeCodeAnalysisProblems', enabled ? onFixAllTypeCodeAnalysisProblems : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.FixAllCodeAnalysisProblems', enabled ? onFixAllCodeAnalysisProblems : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.DisableAllTypeCodeAnalysisProblems', enabled ? onDisableAllTypeCodeAnalysisProblems : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ShowCodeAnalysisDocumentation', enabled ? (uri) => vscode.env.openExternal(uri) : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('cpptools.activeConfigName', enabled ? onGetActiveConfigName : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('cpptools.activeConfigCustomVariable', enabled ? onGetActiveConfigCustomVariable : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('cpptools.setActiveConfigName', enabled ? onSetActiveConfigName : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.RestartIntelliSenseForFile', enabled ? onRestartIntelliSenseForFile : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.GenerateDoxygenComment', enabled ? onGenerateDoxygenComment : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.CreateDeclarationOrDefinition', enabled ? onCreateDeclarationOrDefinition : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.CopyDeclarationOrDefinition', enabled ? onCopyDeclarationOrDefinition : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.RescanCompilers', enabled ? onRescanCompilers : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.AddMissingInclude', enabled ? onAddMissingInclude : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ExtractToFunction', enabled ? () => onExtractToFunction(false, false) : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ExtractToFreeFunction', enabled ? () => onExtractToFunction(true, false) : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ExtractToMemberFunction', enabled ? () => onExtractToFunction(false, true) : onDisabledCommand));
commandDisposables.push(vscode.commands.registerCommand('C_Cpp.ExpandSelection', enabled ? (r: Range) => onExpandSelection(r) : onDisabledCommand));
}
function onDisabledCommand() {
const message: string = localize(
{
key: "on.disabled.command",
comment: [
"Markdown text between `` should not be translated or localized (they represent literal text) and the capitalization, spacing, and punctuation (including the ``) should not be altered."
]
},
"IntelliSense-related commands cannot be executed when `C_Cpp.intelliSenseEngine` is set to `disabled`.");
return vscode.window.showWarningMessage(message);
}
async function onRestartIntelliSenseForFile() {
const activeEditor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (!activeEditor || !util.isCpp(activeEditor.document)) {
return;
}
return clients.ActiveClient.restartIntelliSenseForFile(activeEditor.document);
}
async function onSwitchHeaderSource(): Promise<void> {
const activeEditor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (!activeEditor || !util.isCpp(activeEditor.document)) {
return;
}
let rootUri: vscode.Uri | undefined = clients.ActiveClient.RootUri;
const fileName: string = activeEditor.document.fileName;
if (!rootUri) {
rootUri = vscode.Uri.file(path.dirname(fileName)); // When switching without a folder open.
}
let targetFileName: string = await clients.ActiveClient.requestSwitchHeaderSource(rootUri, fileName);
// If the targetFileName has a path that is a symlink target of a workspace folder,
// then replace the RootRealPath with the RootPath (the symlink path).
let targetFileNameReplaced: boolean = false;
clients.forEach(client => {
if (!targetFileNameReplaced && client.RootRealPath && client.RootPath !== client.RootRealPath
&& targetFileName.startsWith(client.RootRealPath)) {
targetFileName = client.RootPath + targetFileName.substring(client.RootRealPath.length);
targetFileNameReplaced = true;
}
});
const document: vscode.TextDocument = await vscode.workspace.openTextDocument(targetFileName);
const workbenchConfig: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("workbench");
let foundEditor: boolean = false;
if (workbenchConfig.get("editor.revealIfOpen")) {
// If the document is already visible in another column, open it there.
vscode.window.visibleTextEditors.forEach(editor => {
if (editor.document === document && !foundEditor) {
foundEditor = true;
void vscode.window.showTextDocument(document, editor.viewColumn).then(undefined, logAndReturn.undefined);
}
});
}
if (!foundEditor) {
void vscode.window.showTextDocument(document).then(undefined, logAndReturn.undefined);
}
}
/**
* Allow the user to select a workspace when multiple workspaces exist and get the corresponding Client back.
* The resulting client is used to handle some command that was previously invoked.
*/
async function selectClient(): Promise<Client> {
if (clients.Count === 1) {
return clients.ActiveClient;
} else {
const key: string | undefined = await ui.showWorkspaces(clients.Names);
if (key !== undefined && key !== "") {
const client: Client | undefined = clients.get(key);
if (client) {
return client;
} else {
console.assert("client not found");
}
}
throw new Error(localize("client.not.found", "client not found"));
}
}
async function onResetDatabase(): Promise<void> {
await clients.ActiveClient.ready;
clients.ActiveClient.resetDatabase();
}
async function onRescanCompilers(sender?: any): Promise<void> {
await clients.ActiveClient.ready;
return clients.ActiveClient.rescanCompilers(sender);
}
async function onAddMissingInclude(): Promise<void> {
telemetry.logLanguageServerEvent('AddMissingInclude');
}
async function selectIntelliSenseConfiguration(sender?: any): Promise<void> {
await clients.ActiveClient.ready;
return clients.ActiveClient.promptSelectIntelliSenseConfiguration(sender);
}
async function installCompiler(sender?: any): Promise<void> {
const telemetryProperties = { sender: util.getSenderType(sender), platform: os.platform(), ranCommand: 'false' };
const ok = localize('ok', 'OK');
switch (os.platform()) {
case "win32":
showInstallCompilerWalkthrough();
break;
case "darwin": {
const title = localize('install.compiler.mac.title', 'The clang compiler will now be installed');
const detail = localize('install.compiler.mac.detail', 'You may be prompted to type your password in the VS Code terminal window to authorize the installation.');
const response = await vscode.window.showInformationMessage(title, { modal: true, detail }, ok);
if (response === ok) {
const terminal = vscode.window.createTerminal('Install C++ Compiler');
terminal.sendText('sudo xcode-select --install');
terminal.show();
telemetryProperties.ranCommand = 'true';
}
break;
}
default: {
const info = await PlatformInformation.GetPlatformInformation();
const installCommand = (() => {
switch (info.distribution?.name) {
case 'ubuntu':
case 'linuxmint':
case 'debian': {
return 'sudo sh -c \'apt update ; apt install -y build-essential\'';
}
case 'centos':
case 'fedora':
case 'rhel': {
return 'sudo sh -c \'yum install -y gcc-c++ gdb\'';
}
case 'opensuse':
case 'opensuse-leap':
case 'opensuse-tumbleweed': {
return 'sudo sh -c \'zypper refresh ; zypper install gcc-c++ gdb\'';
}
}
return undefined;
})();
if (installCommand) {
const title = localize('install.compiler.linux.title', 'The gcc compiler will now be installed');
const detail = localize('install.compiler.linux.detail', 'You may be prompted to type your password in the VS Code terminal window to authorize the installation.');
const response = await vscode.window.showInformationMessage(title, { modal: true, detail }, ok);
if (response === ok) {
const terminal = vscode.window.createTerminal('Install C++ Compiler');
terminal.sendText(installCommand);
terminal.show(true);
telemetryProperties.ranCommand = 'true';
}
}
}
}
telemetry.logLanguageServerEvent('installCompiler', telemetryProperties);
}
async function onSelectConfiguration(): Promise<void> {
if (!isFolderOpen()) {
void vscode.window.showInformationMessage(localize("configuration.select.first", 'Open a folder first to select a configuration.'));
} else {
// This only applies to the active client. You cannot change the configuration for
// a client that is not active since that client's UI will not be visible.
return clients.ActiveClient.handleConfigurationSelectCommand();
}
}
function onSelectConfigurationProvider(): void {
if (!isFolderOpen()) {
void vscode.window.showInformationMessage(localize("configuration.provider.select.first", 'Open a folder first to select a configuration provider.'));
} else {
void selectClient().then(client => client.handleConfigurationProviderSelectCommand(), logAndReturn.undefined);
}
}
function onEditConfigurationJSON(viewColumn: vscode.ViewColumn = vscode.ViewColumn.Active): void {
telemetry.logLanguageServerEvent("SettingsCommand", { "palette": "json" }, undefined);
if (!isFolderOpen()) {
void vscode.window.showInformationMessage(localize('edit.configurations.open.first', 'Open a folder first to edit configurations'));
} else {
void selectClient().then(client => client.handleConfigurationEditJSONCommand(viewColumn), logAndReturn.undefined);
}
}
function onEditConfigurationUI(viewColumn: vscode.ViewColumn = vscode.ViewColumn.Active): void {
telemetry.logLanguageServerEvent("SettingsCommand", { "palette": "ui" }, undefined);
if (!isFolderOpen()) {
void vscode.window.showInformationMessage(localize('edit.configurations.open.first', 'Open a folder first to edit configurations'));
} else {
void selectClient().then(client => client.handleConfigurationEditUICommand(viewColumn), logAndReturn.undefined);
}
}
function onEditConfiguration(viewColumn: vscode.ViewColumn = vscode.ViewColumn.Active): void {
if (!isFolderOpen()) {
void vscode.window.showInformationMessage(localize('edit.configurations.open.first', 'Open a folder first to edit configurations'));
} else {
void selectClient().then(client => client.handleConfigurationEditCommand(viewColumn), logAndReturn.undefined);
}
}
function onGenerateEditorConfig(): void {
if (!isFolderOpen()) {
const settings: CppSettings = new CppSettings();
void settings.generateEditorConfig();
} else {
void selectClient().then(client => {
const settings: CppSettings = new CppSettings(client.RootUri);
void settings.generateEditorConfig();
}).catch(logAndReturn.undefined);
}
}
async function onGoToNextDirectiveInGroup(): Promise<void> {
return getActiveClient().handleGoToDirectiveInGroup(true);
}
async function onGoToPrevDirectiveInGroup(): Promise<void> {
return getActiveClient().handleGoToDirectiveInGroup(false);
}
async function onRunCodeAnalysisOnActiveFile(): Promise<void> {
if (activeDocument) {
await vscode.commands.executeCommand("workbench.action.files.saveAll");
return getActiveClient().handleRunCodeAnalysisOnActiveFile();
}
}
async function onRunCodeAnalysisOnOpenFiles(): Promise<void> {
if (openFileVersions.size > 0) {
await vscode.commands.executeCommand("workbench.action.files.saveAll");
return getActiveClient().handleRunCodeAnalysisOnOpenFiles();
}
}
async function onRunCodeAnalysisOnAllFiles(): Promise<void> {
await vscode.commands.executeCommand("workbench.action.files.saveAll");
return getActiveClient().handleRunCodeAnalysisOnAllFiles();
}
async function onRemoveAllCodeAnalysisProblems(): Promise<void> {
return getActiveClient().handleRemoveAllCodeAnalysisProblems();
}
async function onRemoveCodeAnalysisProblems(refreshSquigglesOnSave: boolean, identifiersAndUris: CodeAnalysisDiagnosticIdentifiersAndUri[]): Promise<void> {
return getActiveClient().handleRemoveCodeAnalysisProblems(refreshSquigglesOnSave, identifiersAndUris);
}
// Needed due to https://github.com/microsoft/vscode/issues/148723 .
const codeActionAbortedString: string = localize('code.action.aborted', "The code analysis fix could not be applied because the document has changed.");
async function onFixThisCodeAnalysisProblem(version: number, workspaceEdit: vscode.WorkspaceEdit, refreshSquigglesOnSave: boolean, identifiersAndUris: CodeAnalysisDiagnosticIdentifiersAndUri[]): Promise<void> {
if (identifiersAndUris.length < 1) {
return;
}
const codeActions: CodeActionDiagnosticInfo[] | undefined = codeAnalysisFileToCodeActions.get(identifiersAndUris[0].uri);
if (codeActions === undefined) {
return;
}
for (const codeAction of codeActions) {
if (codeAction.code === identifiersAndUris[0].identifiers[0].code && rangeEquals(codeAction.range, identifiersAndUris[0].identifiers[0].range)) {
if (version !== codeAction.version) {
void vscode.window.showErrorMessage(codeActionAbortedString);
return;
}
break;
}
}
return getActiveClient().handleFixCodeAnalysisProblems(workspaceEdit, refreshSquigglesOnSave, identifiersAndUris);
}
async function onFixAllTypeCodeAnalysisProblems(type: string, version: number, workspaceEdit: vscode.WorkspaceEdit, refreshSquigglesOnSave: boolean, identifiersAndUris: CodeAnalysisDiagnosticIdentifiersAndUri[]): Promise<void> {
if (version === codeAnalysisCodeToFixes.get(type)?.version) {
return getActiveClient().handleFixCodeAnalysisProblems(workspaceEdit, refreshSquigglesOnSave, identifiersAndUris);
}
void vscode.window.showErrorMessage(codeActionAbortedString);
}
async function onFixAllCodeAnalysisProblems(version: number, workspaceEdit: vscode.WorkspaceEdit, refreshSquigglesOnSave: boolean, identifiersAndUris: CodeAnalysisDiagnosticIdentifiersAndUri[]): Promise<void> {
if (version === codeAnalysisAllFixes.version) {
return getActiveClient().handleFixCodeAnalysisProblems(workspaceEdit, refreshSquigglesOnSave, identifiersAndUris);
}
void vscode.window.showErrorMessage(codeActionAbortedString);
}
async function onDisableAllTypeCodeAnalysisProblems(code: string, identifiersAndUris: CodeAnalysisDiagnosticIdentifiersAndUri[]): Promise<void> {
return getActiveClient().handleDisableAllTypeCodeAnalysisProblems(code, identifiersAndUris);
}
async function onCopyDeclarationOrDefinition(args?: any): Promise<void> {
const sender: any | undefined = util.isString(args?.sender) ? args.sender : args;
const properties: Record<string, string> = {
sender: util.getSenderType(sender)
};
telemetry.logLanguageServerEvent('CopyDeclDefn', properties);
return getActiveClient().handleCreateDeclarationOrDefinition(true, args?.range);
}
async function onCreateDeclarationOrDefinition(args?: any): Promise<void> {
const sender: any | undefined = util.isString(args?.sender) ? args.sender : args;
const properties: Record<string, string> = {
sender: util.getSenderType(sender)
};
telemetry.logLanguageServerEvent('CreateDeclDefn', properties);
return getActiveClient().handleCreateDeclarationOrDefinition(false, args?.range);
}
async function onExtractToFunction(extractAsGlobal: boolean, extractAsMemberFunction: boolean): Promise<void> {
if (extractAsGlobal) {
telemetry.logLanguageServerEvent('ExtractToFreeFunction');
} else if (extractAsMemberFunction) {
telemetry.logLanguageServerEvent('ExtractToMemberFunction');
} else {
telemetry.logLanguageServerEvent('ExtractToFunction');
}
return getActiveClient().handleExtractToFunction(extractAsGlobal);
}
function onExpandSelection(r: Range) {
const activeTextEditor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (activeTextEditor) {
activeTextEditor.selection = new vscode.Selection(new vscode.Position(r.start.line, r.start.character), new vscode.Position(r.end.line, r.end.character));
telemetry.logLanguageServerEvent('ExpandSelection');
}
}
function onAddToIncludePath(path: string): void {
if (isFolderOpen()) {
// This only applies to the active client. It would not make sense to add the include path
// suggestion to a different workspace.
return clients.ActiveClient.handleAddToIncludePathCommand(path);
}
}
function onEnableSquiggles(): void {
// This only applies to the active client.
const settings: CppSettings = new CppSettings(clients.ActiveClient.RootUri);
settings.update<string>("errorSquiggles", "enabled");
}
function onDisableSquiggles(): void {
// This only applies to the active client.
const settings: CppSettings = new CppSettings(clients.ActiveClient.RootUri);
settings.update<string>("errorSquiggles", "disabled");
}
function onToggleDimInactiveRegions(): void {
// This only applies to the active client.
const settings: CppSettings = new CppSettings(clients.ActiveClient.RootUri);
settings.update<boolean>("dimInactiveRegions", !settings.dimInactiveRegions);
}
function onPauseParsing(): void {
clients.ActiveClient.pauseParsing();
}
function onResumeParsing(): void {
clients.ActiveClient.resumeParsing();
}
function onPauseCodeAnalysis(): void {
clients.ActiveClient.PauseCodeAnalysis();
}
function onResumeCodeAnalysis(): void {
clients.ActiveClient.ResumeCodeAnalysis();
}
function onCancelCodeAnalysis(): void {
clients.ActiveClient.CancelCodeAnalysis();
}
function onShowActiveCodeAnalysisCommands(): Promise<void> {
return clients.ActiveClient.handleShowActiveCodeAnalysisCommands();
}
function onShowIdleCodeAnalysisCommands(): Promise<void> {
return clients.ActiveClient.handleShowIdleCodeAnalysisCommands();
}
function onShowReferencesProgress(): void {
clients.ActiveClient.handleReferencesIcon();
}
function onToggleRefGroupView(): void {
// Set context to switch icons
const client: Client = getActiveClient();
client.toggleReferenceResultsView();
}
function onTakeSurvey(): void {
telemetry.logLanguageServerEvent("onTakeSurvey");
const uri: vscode.Uri = vscode.Uri.parse(`https://www.research.net/r/VBVV6C6?o=${os.platform()}&m=${vscode.env.machineId}`);
void vscode.commands.executeCommand('vscode.open', uri);
}
function onVcpkgOnlineHelpSuggested(dummy?: any): void {
telemetry.logLanguageServerEvent('vcpkgAction', { 'source': dummy ? 'CodeAction' : 'CommandPalette', 'action': 'vcpkgOnlineHelpSuggested' });
const uri: vscode.Uri = vscode.Uri.parse(`https://aka.ms/vcpkg`);
void vscode.commands.executeCommand('vscode.open', uri);
}
async function onVcpkgClipboardInstallSuggested(ports?: string[]): Promise<void> {
let source: string;
if (ports && ports.length) {
source = 'CodeAction';
} else {
source = 'CommandPalette';
// Glob up all existing diagnostics for missing includes and look them up in the vcpkg database
const missingIncludeLocations: [vscode.TextDocument, number[]][] = [];
vscode.languages.getDiagnostics().forEach(uriAndDiagnostics => {
// Extract textDocument
const textDocument: vscode.TextDocument | undefined = vscode.workspace.textDocuments.find(doc => doc.uri.fsPath === uriAndDiagnostics[0].fsPath);
if (!textDocument) {
return;
}
// Extract lines numbers for missing include diagnostics
let lines: number[] = uriAndDiagnostics[1].filter(isMissingIncludeDiagnostic).map<number>(d => d.range.start.line);
if (!lines.length) {
return;
}
// Filter duplicate lines
lines = lines.filter((line: number, index: number) => {
const foundIndex: number = lines.indexOf(line);
return foundIndex === index;
});
missingIncludeLocations.push([textDocument, lines]);
});
if (!missingIncludeLocations.length) {
return;
}
// Queue look ups in the vcpkg database for missing ports; filter out duplicate results
const portsPromises: Promise<string[]>[] = [];
missingIncludeLocations.forEach(docAndLineNumbers => {
docAndLineNumbers[1].forEach(line => {
portsPromises.push(lookupIncludeInVcpkg(docAndLineNumbers[0], line));
});
});
ports = ([] as string[]).concat(...await Promise.all(portsPromises));
if (!ports.length) {
return;
}
const ports2: string[] = ports;
ports = ports2.filter((port: string, index: number) => ports2.indexOf(port) === index);
}
let installCommand: string = 'vcpkg install';
ports.forEach(port => installCommand += ` ${port}`);
telemetry.logLanguageServerEvent('vcpkgAction', { 'source': source, 'action': 'vcpkgClipboardInstallSuggested', 'ports': ports.toString() });
await vscode.env.clipboard.writeText(installCommand);
}
function onGenerateDoxygenComment(arg: DoxygenCodeActionCommandArguments): Promise<void> {
return getActiveClient().handleGenerateDoxygenComment(arg);
}
function onSetActiveConfigName(configurationName: string): Thenable<void> {
return clients.ActiveClient.setCurrentConfigName(configurationName);
}
function onGetActiveConfigName(): Thenable<string | undefined> {
return clients.ActiveClient.getCurrentConfigName();
}
function onGetActiveConfigCustomVariable(variableName: string): Thenable<string> {
return clients.ActiveClient.getCurrentConfigCustomVariable(variableName);
}
function onLogDiagnostics(): Promise<void> {
return clients.ActiveClient.logDiagnostics();
}
function onRescanWorkspace(): Promise<void> {
return clients.ActiveClient.rescanFolder();
}
function onShowRefCommand(arg?: TreeNode): void {
if (!arg) {
return;
}
const { node } = arg;
if (node === NodeType.reference) {
const { referenceLocation } = arg;
if (referenceLocation) {
void vscode.window.showTextDocument(referenceLocation.uri, {
selection: referenceLocation.range.with({ start: referenceLocation.range.start, end: referenceLocation.range.end })
}).then(undefined, logAndReturn.undefined);
}
} else if (node === NodeType.fileWithPendingRef) {
const { fileUri } = arg;
if (fileUri) {
void vscode.window.showTextDocument(fileUri).then(undefined, logAndReturn.undefined);
}
}
}
function reportMacCrashes(): void {
if (process.platform === "darwin") {
prevMacCrashFile = "";
const home: string = os.homedir();
const crashFolder: string = path.resolve(home, "Library/Logs/DiagnosticReports");
fs.stat(crashFolder, (err) => {
const crashObject: Record<string, string> = {};
if (err?.code) {
// If the directory isn't there, we have a problem...
crashObject["errCode"] = err.code;
telemetry.logLanguageServerEvent("MacCrash", crashObject);
return;
}
// vscode.workspace.createFileSystemWatcher only works in workspace folders.
try {
fs.watch(crashFolder, (event, filename) => {
if (event !== "rename") {
return;
}
if (!filename || filename === prevMacCrashFile) {
return;
}
prevMacCrashFile = filename;
if (!filename.startsWith("cpptools")) {
return;
}
// Wait 5 seconds to allow time for the crash log to finish being written.
setTimeout(() => {
fs.readFile(path.resolve(crashFolder, filename), 'utf8', (err, data) => {
if (err) {
// Try again?
fs.readFile(path.resolve(crashFolder, filename), 'utf8', handleMacCrashFileRead);
return;
}
handleMacCrashFileRead(err, data);
});
}, 5000);
});
} catch (e) {
// The file watcher limit is hit (may not be possible on Mac, but just in case).
}
});
}
}
export function usesCrashHandler(): boolean {
if (os.platform() === "darwin") {
if (os.arch() === "arm64") {
return true;
} else {
const releaseParts: string[] = os.release().split(".");
if (releaseParts.length >= 1) {
// Avoid potentially intereferring with the older macOS crash handler.
return parseInt(releaseParts[0]) >= 19;
}
return true;
}
}
return os.platform() !== "win32" && os.arch() === "x64";
}
export function watchForCrashes(crashDirectory: string): void {
if (crashDirectory !== "") {
prevCppCrashFile = "";
fs.stat(crashDirectory, (err) => {
const crashObject: Record<string, string> = {};
if (err?.code) {
// If the directory isn't there, we have a problem...
crashObject["errCode"] = err.code;