forked from microsoft/vscode-cpptools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.ts
1513 lines (1358 loc) · 72.1 KB
/
client.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 path from 'path';
import * as vscode from 'vscode';
import {
LanguageClient, LanguageClientOptions, ServerOptions, NotificationType, TextDocumentIdentifier,
RequestType, ErrorAction, CloseAction, DidOpenTextDocumentParams, Range
} from 'vscode-languageclient';
import { SourceFileConfigurationItem, WorkspaceBrowseConfiguration, SourceFileConfiguration, Version } from 'vscode-cpptools';
import { Status } from 'vscode-cpptools/out/testApi';
import * as util from '../common';
import * as configs from './configurations';
import { CppSettings, OtherSettings } from './settings';
import * as telemetry from '../telemetry';
import { PersistentState, PersistentFolderState } from './persistentState';
import { UI, getUI } from './ui';
import { ClientCollection } from './clientCollection';
import { createProtocolFilter } from './protocolFilter';
import { DataBinding } from './dataBinding';
import minimatch = require("minimatch");
import * as logger from '../logger';
import { updateLanguageConfigurations, registerCommands } from './extension';
import { CancellationTokenSource } from 'vscode';
import { SettingsTracker, getTracker } from './settingsTracker';
import { getTestHook, TestHook } from '../testHook';
import { getCustomConfigProviders, CustomConfigurationProviderCollection, CustomConfigurationProvider1 } from '../LanguageServer/customProviders';
import { ABTestSettings, getABTestSettings } from '../abTesting';
import * as fs from 'fs';
import * as os from 'os';
let ui: UI;
let timeStamp: number = 0;
const configProviderTimeout: number = 2000;
interface NavigationPayload {
navigation: string;
}
interface TelemetryPayload {
event: string;
properties?: { [key: string]: string };
metrics?: { [key: string]: number };
}
interface OutputNotificationBody {
category: string;
output: string;
}
interface ReportStatusNotificationBody {
status: string;
}
interface QueryCompilerDefaultsParams {
}
interface FolderSettingsParams {
currentConfiguration: number;
configurations: any[];
}
interface FolderSelectedSettingParams {
currentConfiguration: number;
}
interface SwitchHeaderSourceParams {
rootPath: string;
switchHeaderSourceFileName: string;
}
interface FileChangedParams {
uri: string;
}
interface OutputNotificationBody {
category: string;
output: string;
}
interface InactiveRegionParams {
uri: string;
regions: InputRegion[];
}
interface InputRegion {
startLine: number;
endLine: number;
}
interface DecorationRangesPair {
decoration: vscode.TextEditorDecorationType;
ranges: vscode.Range[];
}
// Need to convert vscode.Uri to a string before sending it to the language server.
interface SourceFileConfigurationItemAdapter {
uri: string;
configuration: SourceFileConfiguration;
}
interface CustomConfigurationParams {
configurationItems: SourceFileConfigurationItemAdapter[];
}
interface CustomBrowseConfigurationParams {
browseConfiguration: WorkspaceBrowseConfiguration;
}
interface CompileCommandsPaths {
paths: string[];
}
interface QueryTranslationUnitSourceParams {
uri: string;
}
export enum QueryTranslationUnitSourceConfigDisposition {
/**
* No custom config needed for this file
*/
ConfigNotNeeded = 0,
/**
* Custom config is needed for this file
*/
ConfigNeeded = 1,
/**
* Custom config is needed for the ancestor file returned in uri
*/
AncestorConfigNeeded = 2
}
interface QueryTranslationUnitSourceResult {
uri: string;
configDisposition: QueryTranslationUnitSourceConfigDisposition;
}
interface GetDiagnosticsResult {
diagnostics: string;
}
// Requests
const NavigationListRequest: RequestType<TextDocumentIdentifier, string, void, void> = new RequestType<TextDocumentIdentifier, string, void, void>('cpptools/requestNavigationList');
const GoToDeclarationRequest: RequestType<void, void, void, void> = new RequestType<void, void, void, void>('cpptools/goToDeclaration');
const QueryCompilerDefaultsRequest: RequestType<QueryCompilerDefaultsParams, configs.CompilerDefaults, void, void> = new RequestType<QueryCompilerDefaultsParams, configs.CompilerDefaults, void, void>('cpptools/queryCompilerDefaults');
const QueryTranslationUnitSourceRequest: RequestType<QueryTranslationUnitSourceParams, QueryTranslationUnitSourceResult, void, void> = new RequestType<QueryTranslationUnitSourceParams, QueryTranslationUnitSourceResult, void, void>('cpptools/queryTranslationUnitSource');
const SwitchHeaderSourceRequest: RequestType<SwitchHeaderSourceParams, string, void, void> = new RequestType<SwitchHeaderSourceParams, string, void, void>('cpptools/didSwitchHeaderSource');
const GetDiagnosticsRequest: RequestType<void, GetDiagnosticsResult, void, void> = new RequestType<void, GetDiagnosticsResult, void, void>('cpptools/getDiagnostics');
// Notifications to the server
const DidOpenNotification: NotificationType<DidOpenTextDocumentParams, void> = new NotificationType<DidOpenTextDocumentParams, void>('textDocument/didOpen');
const FileCreatedNotification: NotificationType<FileChangedParams, void> = new NotificationType<FileChangedParams, void>('cpptools/fileCreated');
const FileDeletedNotification: NotificationType<FileChangedParams, void> = new NotificationType<FileChangedParams, void>('cpptools/fileDeleted');
const ResetDatabaseNotification: NotificationType<void, void> = new NotificationType<void, void>('cpptools/resetDatabase');
const PauseParsingNotification: NotificationType<void, void> = new NotificationType<void, void>('cpptools/pauseParsing');
const ResumeParsingNotification: NotificationType<void, void> = new NotificationType<void, void>('cpptools/resumeParsing');
const ActiveDocumentChangeNotification: NotificationType<TextDocumentIdentifier, void> = new NotificationType<TextDocumentIdentifier, void>('cpptools/activeDocumentChange');
const TextEditorSelectionChangeNotification: NotificationType<Range, void> = new NotificationType<Range, void>('cpptools/textEditorSelectionChange');
const ChangeFolderSettingsNotification: NotificationType<FolderSettingsParams, void> = new NotificationType<FolderSettingsParams, void>('cpptools/didChangeFolderSettings');
const ChangeCompileCommandsNotification: NotificationType<FileChangedParams, void> = new NotificationType<FileChangedParams, void>('cpptools/didChangeCompileCommands');
const ChangeSelectedSettingNotification: NotificationType<FolderSelectedSettingParams, void> = new NotificationType<FolderSelectedSettingParams, void>('cpptools/didChangeSelectedSetting');
const IntervalTimerNotification: NotificationType<void, void> = new NotificationType<void, void>('cpptools/onIntervalTimer');
const CustomConfigurationNotification: NotificationType<CustomConfigurationParams, void> = new NotificationType<CustomConfigurationParams, void>('cpptools/didChangeCustomConfiguration');
const CustomBrowseConfigurationNotification: NotificationType<CustomBrowseConfigurationParams, void> = new NotificationType<CustomBrowseConfigurationParams, void>('cpptools/didChangeCustomBrowseConfiguration');
const ClearCustomConfigurationsNotification: NotificationType<void, void> = new NotificationType<void, void>('cpptools/clearCustomConfigurations');
// Notifications from the server
const ReloadWindowNotification: NotificationType<void, void> = new NotificationType<void, void>('cpptools/reloadWindow');
const LogTelemetryNotification: NotificationType<TelemetryPayload, void> = new NotificationType<TelemetryPayload, void>('cpptools/logTelemetry');
const ReportNavigationNotification: NotificationType<NavigationPayload, void> = new NotificationType<NavigationPayload, void>('cpptools/reportNavigation');
const ReportTagParseStatusNotification: NotificationType<ReportStatusNotificationBody, void> = new NotificationType<ReportStatusNotificationBody, void>('cpptools/reportTagParseStatus');
const ReportStatusNotification: NotificationType<ReportStatusNotificationBody, void> = new NotificationType<ReportStatusNotificationBody, void>('cpptools/reportStatus');
const DebugProtocolNotification: NotificationType<OutputNotificationBody, void> = new NotificationType<OutputNotificationBody, void>('cpptools/debugProtocol');
const DebugLogNotification: NotificationType<OutputNotificationBody, void> = new NotificationType<OutputNotificationBody, void>('cpptools/debugLog');
const InactiveRegionNotification: NotificationType<InactiveRegionParams, void> = new NotificationType<InactiveRegionParams, void>('cpptools/inactiveRegions');
const CompileCommandsPathsNotification: NotificationType<CompileCommandsPaths, void> = new NotificationType<CompileCommandsPaths, void>('cpptools/compileCommandsPaths');
const UpdateClangFormatPathNotification: NotificationType<string, void> = new NotificationType<string, void>('cpptools/updateClangFormatPath');
const UpdateIntelliSenseCachePathNotification: NotificationType<string, void> = new NotificationType<string, void>('cpptools/updateIntelliSenseCachePath');
class BlockingTask<T> {
private dependency: BlockingTask<any>;
private done: boolean = false;
private promise: Promise<T>;
constructor(task: () => T, dependency?: BlockingTask<any>) {
this.promise = new Promise<T>(async (resolve, reject) => {
try {
let result: T = await task();
resolve(result);
this.done = true;
} catch (err) {
reject(err);
this.done = true;
}
});
this.dependency = dependency;
}
public get Done(): boolean {
return this.done && (!this.dependency || this.dependency.Done);
}
public then(onSucceeded: (value: T) => any, onRejected: (err) => any): Promise<any> {
return this.promise.then(onSucceeded, onRejected);
}
}
let failureMessageShown: boolean = false;
interface ClientModel {
isTagParsing: DataBinding<boolean>;
isUpdatingIntelliSense: DataBinding<boolean>;
navigationLocation: DataBinding<string>;
tagParserStatus: DataBinding<string>;
activeConfigName: DataBinding<string>;
}
export interface Client {
TagParsingChanged: vscode.Event<boolean>;
IntelliSenseParsingChanged: vscode.Event<boolean>;
NavigationLocationChanged: vscode.Event<string>;
TagParserStatusChanged: vscode.Event<string>;
ActiveConfigChanged: vscode.Event<string>;
RootPath: string;
RootUri: vscode.Uri;
Name: string;
TrackedDocuments: Set<vscode.TextDocument>;
onDidChangeSettings(): { [key: string] : string };
onDidChangeVisibleTextEditors(editors: vscode.TextEditor[]): void;
onRegisterCustomConfigurationProvider(provider: CustomConfigurationProvider1): Thenable<void>;
updateCustomConfigurations(requestingProvider?: CustomConfigurationProvider1): Thenable<void>;
updateCustomBrowseConfiguration(requestingProvider?: CustomConfigurationProvider1): Thenable<void>;
provideCustomConfiguration(document: vscode.TextDocument): Promise<void>;
logDiagnostics(): Promise<void>;
getCurrentConfigName(): Thenable<string>;
getCompilerPath(): Thenable<string>;
getKnownCompilers(): Thenable<configs.KnownCompiler[]>;
takeOwnership(document: vscode.TextDocument): void;
queueTask<T>(task: () => Thenable<T>): Thenable<T>;
requestWhenReady(request: () => Thenable<any>): Thenable<any>;
notifyWhenReady(notify: () => void): void;
requestGoToDeclaration(): Thenable<void>;
requestSwitchHeaderSource(rootPath: string, fileName: string): Thenable<string>;
requestNavigationList(document: vscode.TextDocument): Thenable<string>;
activeDocumentChanged(document: vscode.TextDocument): void;
activate(): void;
selectionChanged(selection: Range): void;
resetDatabase(): void;
deactivate(): void;
pauseParsing(): void;
resumeParsing(): void;
handleConfigurationSelectCommand(): void;
handleConfigurationProviderSelectCommand(): void;
handleShowParsingCommands(): void;
handleConfigurationEditCommand(): void;
handleConfigurationEditJSONCommand(): void;
handleConfigurationEditUICommand(): void;
handleAddToIncludePathCommand(path: string): void;
onInterval(): void;
dispose(): Thenable<void>;
addFileAssociations(fileAssociations: string, is_c: boolean): void;
}
export function createClient(allClients: ClientCollection, workspaceFolder?: vscode.WorkspaceFolder): Client {
return new DefaultClient(allClients, workspaceFolder);
}
export function createNullClient(): Client {
return new NullClient();
}
class DefaultClient implements Client {
private languageClient: LanguageClient; // The "client" that launches and communicates with our language "server" process.
private disposables: vscode.Disposable[] = [];
private configuration: configs.CppProperties;
private rootPathFileWatcher: vscode.FileSystemWatcher;
private rootFolder: vscode.WorkspaceFolder | undefined;
private storagePath: string;
private trackedDocuments = new Set<vscode.TextDocument>();
private outputChannel: vscode.OutputChannel;
private debugChannel: vscode.OutputChannel;
private diagnosticsChannel: vscode.OutputChannel;
private crashTimes: number[] = [];
private isSupported: boolean = true;
private inactiveRegionsDecorations = new Map<string, DecorationRangesPair>();
private settingsTracker: SettingsTracker;
private configurationProvider: string;
// The "model" that is displayed via the UI (status bar).
private model: ClientModel = {
isTagParsing: new DataBinding<boolean>(false),
isUpdatingIntelliSense: new DataBinding<boolean>(false),
navigationLocation: new DataBinding<string>(""),
tagParserStatus: new DataBinding<string>(""),
activeConfigName: new DataBinding<string>("")
};
public get TagParsingChanged(): vscode.Event<boolean> { return this.model.isTagParsing.ValueChanged; }
public get IntelliSenseParsingChanged(): vscode.Event<boolean> { return this.model.isUpdatingIntelliSense.ValueChanged; }
public get NavigationLocationChanged(): vscode.Event<string> { return this.model.navigationLocation.ValueChanged; }
public get TagParserStatusChanged(): vscode.Event<string> { return this.model.tagParserStatus.ValueChanged; }
public get ActiveConfigChanged(): vscode.Event<string> { return this.model.activeConfigName.ValueChanged; }
/**
* don't use this.rootFolder directly since it can be undefined
*/
public get RootPath(): string {
return (this.rootFolder) ? this.rootFolder.uri.fsPath : "";
}
public get RootUri(): vscode.Uri {
return (this.rootFolder) ? this.rootFolder.uri : null;
}
public get Name(): string {
return this.getName(this.rootFolder);
}
public get TrackedDocuments(): Set<vscode.TextDocument> {
return this.trackedDocuments;
}
private get AdditionalEnvironment(): { [key: string]: string | string[] } {
return { workspaceFolderBasename: this.Name, workspaceStorage: this.storagePath };
}
private getName(workspaceFolder?: vscode.WorkspaceFolder): string {
return workspaceFolder ? workspaceFolder.name : "untitled";
}
/**
* All public methods on this class must be guarded by the "pendingTask" promise. Requests and notifications received before the task is
* complete are executed after this promise is resolved.
* @see requestWhenReady<T>(request)
* @see notifyWhenReady(notify)
*/
private pendingTask: BlockingTask<void>;
constructor(allClients: ClientCollection, workspaceFolder?: vscode.WorkspaceFolder) {
this.rootFolder = workspaceFolder;
this.storagePath = util.extensionContext ? util.extensionContext.storagePath :
path.join((this.rootFolder ? this.rootFolder.uri.fsPath : ""), "/.vscode");
if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) {
this.storagePath = path.join(this.storagePath, this.getName(this.rootFolder));
}
try {
let languageClient: LanguageClient = this.createLanguageClient(allClients);
languageClient.registerProposedFeatures();
languageClient.start(); // This returns Disposable, but doesn't need to be tracked because we call .stop() explicitly in our dispose()
util.setProgress(util.getProgressExecutableStarted());
ui = getUI();
ui.bind(this);
// requests/notifications are deferred until this.languageClient is set.
this.queueBlockingTask(() => languageClient.onReady().then(
() => {
this.configuration = new configs.CppProperties(this.RootUri);
this.configuration.ConfigurationsChanged((e) => this.onConfigurationsChanged(e));
this.configuration.SelectionChanged((e) => this.onSelectedConfigurationChanged(e));
this.configuration.CompileCommandsChanged((e) => this.onCompileCommandsChanged(e));
this.disposables.push(this.configuration);
this.languageClient = languageClient;
this.settingsTracker = getTracker(this.RootUri);
telemetry.logLanguageServerEvent("NonDefaultInitialCppSettings", this.settingsTracker.getUserModifiedSettings());
failureMessageShown = false;
// Listen for messages from the language server.
this.registerNotifications();
this.registerFileWatcher();
// The configurations will not be sent to the language server until the default include paths and frameworks have been set.
// The event handlers must be set before this happens.
return languageClient.sendRequest(QueryCompilerDefaultsRequest, {}).then((compilerDefaults: configs.CompilerDefaults) => {
this.configuration.CompilerDefaults = compilerDefaults;
// Only register the real commands after the extension has finished initializing,
// e.g. prevents empty c_cpp_properties.json from generation.
registerCommands();
});
},
(err) => {
this.isSupported = false; // Running on an OS we don't support yet.
if (!failureMessageShown) {
failureMessageShown = true;
vscode.window.showErrorMessage("Unable to start the C/C++ language server. IntelliSense features will be disabled. Error: " + String(err));
}
}));
} catch (err) {
this.isSupported = false; // Running on an OS we don't support yet.
if (!failureMessageShown) {
failureMessageShown = true;
let additionalInfo: string;
if (err.code === "EPERM") {
additionalInfo = `EPERM: Check permissions for '${getLanguageServerFileName()}'`;
} else {
additionalInfo = String(err);
}
vscode.window.showErrorMessage("Unable to start the C/C++ language server. IntelliSense features will be disabled. Error: " + additionalInfo);
}
}
}
private createLanguageClient(allClients: ClientCollection): LanguageClient {
let serverModule: string = getLanguageServerFileName();
let exeExists: boolean = fs.existsSync(serverModule);
if (!exeExists) {
telemetry.logLanguageServerEvent("missingLanguageServerBinary");
throw String('Missing binary at ' + serverModule);
}
let serverName: string = this.getName(this.rootFolder);
let serverOptions: ServerOptions = {
run: { command: serverModule },
debug: { command: serverModule, args: [ serverName ] }
};
let settings: CppSettings = new CppSettings(this.rootFolder ? this.rootFolder.uri : null);
let other: OtherSettings = new OtherSettings(this.rootFolder ? this.rootFolder.uri : null);
let abTestSettings: ABTestSettings = getABTestSettings();
let intelliSenseCacheDisabled: boolean = false;
if (os.platform() === "darwin") {
const releaseParts: string[] = os.release().split(".");
if (releaseParts.length >= 1) {
// AutoPCH doesn't work for older Mac OS's.
intelliSenseCacheDisabled = parseInt(releaseParts[0]) < 17;
}
}
let clientOptions: LanguageClientOptions = {
documentSelector: [
{ scheme: 'file', language: 'cpp' },
{ scheme: 'file', language: 'c' }
],
synchronize: {
// Synchronize the setting section to the server
configurationSection: ['C_Cpp', 'files', 'search']
},
workspaceFolder: this.rootFolder,
initializationOptions: {
clang_format_path: util.resolveVariables(settings.clangFormatPath, this.AdditionalEnvironment),
clang_format_style: settings.clangFormatStyle,
clang_format_fallbackStyle: settings.clangFormatFallbackStyle,
clang_format_sortIncludes: settings.clangFormatSortIncludes,
formatting: settings.formatting,
extension_path: util.extensionPath,
exclude_files: other.filesExclude,
exclude_search: other.searchExclude,
storage_path: this.storagePath,
tab_size: other.editorTabSize,
intelliSenseEngine: settings.intelliSenseEngine,
intelliSenseEngineFallback: settings.intelliSenseEngineFallback,
intelliSenseCacheDisabled: intelliSenseCacheDisabled,
intelliSenseCachePath : util.resolveVariables(settings.intelliSenseCachePath, this.AdditionalEnvironment),
intelliSenseCacheSize : settings.intelliSenseCacheSize,
autocomplete: settings.autoComplete,
errorSquiggles: settings.errorSquiggles,
dimInactiveRegions: settings.dimInactiveRegions,
suggestSnippets: settings.suggestSnippets,
loggingLevel: settings.loggingLevel,
workspaceParsingPriority: settings.workspaceParsingPriority,
workspaceSymbols: settings.workspaceSymbols,
exclusionPolicy: settings.exclusionPolicy,
preferredPathSeparator: settings.preferredPathSeparator,
default: {
systemIncludePath: settings.defaultSystemIncludePath
},
vcpkg_root: util.getVcpkgRoot(),
gotoDefIntelliSense: abTestSettings.UseGoToDefIntelliSense
},
middleware: createProtocolFilter(this, allClients), // Only send messages directed at this client.
errorHandler: {
error: () => ErrorAction.Continue,
closed: () => {
this.crashTimes.push(Date.now());
if (this.crashTimes.length < 5) {
let newClient: DefaultClient = <DefaultClient>allClients.replace(this, true);
newClient.crashTimes = this.crashTimes;
} else {
let elapsed: number = this.crashTimes[this.crashTimes.length - 1] - this.crashTimes[0];
if (elapsed <= 3 * 60 * 1000) {
if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) {
vscode.window.showErrorMessage(`The language server for '${serverName}' crashed 5 times in the last 3 minutes. It will not be restarted.`);
} else {
vscode.window.showErrorMessage(`The language server crashed 5 times in the last 3 minutes. It will not be restarted.`);
}
allClients.replace(this, false);
} else {
this.crashTimes.shift();
let newClient: DefaultClient = <DefaultClient>allClients.replace(this, true);
newClient.crashTimes = this.crashTimes;
}
}
return CloseAction.DoNotRestart;
}
}
// TODO: should I set the output channel? Does this sort output between servers?
};
// Create the language client
return new LanguageClient(`cpptools: ${serverName}`, serverOptions, clientOptions);
}
public onDidChangeSettings(): { [key: string] : string } {
let changedSettings: { [key: string] : string } = this.settingsTracker.getChangedSettings();
if (Object.keys(changedSettings).length > 0) {
if (changedSettings["commentContinuationPatterns"]) {
updateLanguageConfigurations();
}
if (changedSettings["clang_format_path"]) {
let settings: CppSettings = new CppSettings(this.RootUri);
this.languageClient.sendNotification(UpdateClangFormatPathNotification, util.resolveVariables(settings.clangFormatPath, this.AdditionalEnvironment));
}
if (changedSettings["intelliSenseCachePath"]) {
let settings: CppSettings = new CppSettings(this.RootUri);
this.languageClient.sendNotification(UpdateIntelliSenseCachePathNotification, util.resolveVariables(settings.intelliSenseCachePath, this.AdditionalEnvironment));
}
this.configuration.onDidChangeSettings();
telemetry.logLanguageServerEvent("CppSettingsChange", changedSettings, null);
}
return changedSettings;
}
public onDidChangeVisibleTextEditors(editors: vscode.TextEditor[]): void {
let settings: CppSettings = new CppSettings(this.RootUri);
if (settings.dimInactiveRegions) {
//Apply text decorations to inactive regions
for (let e of editors) {
let valuePair: DecorationRangesPair = this.inactiveRegionsDecorations.get(e.document.uri.toString());
if (valuePair) {
e.setDecorations(valuePair.decoration, valuePair.ranges); // VSCode clears the decorations when the text editor becomes invisible
}
}
}
}
public onRegisterCustomConfigurationProvider(provider: CustomConfigurationProvider1): Thenable<void> {
let onRegistered: () => void = () => {
// version 2 providers control the browse.path. Avoid thrashing the tag parser database by pausing parsing until
// the provider has sent the correct browse.path value.
if (provider.version >= Version.v2) {
this.pauseParsing();
}
};
return this.notifyWhenReady(() => {
if (!this.RootPath) {
return; // There is no c_cpp_properties.json to edit because there is no folder open.
}
let selectedProvider: string = this.configuration.CurrentConfigurationProvider;
if (!selectedProvider) {
let ask: PersistentFolderState<boolean> = new PersistentFolderState<boolean>("Client.registerProvider", true, this.RootPath);
if (ask.Value) {
ui.showConfigureCustomProviderMessage(() => {
let folderStr: string = (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) ? "the '" + this.Name + "'" : "this";
const message: string = `${provider.name} would like to configure IntelliSense for ${folderStr} folder.`;
const allow: string = "Allow";
const dontAllow: string = "Don't Allow";
const askLater: string = "Ask Me Later";
return vscode.window.showInformationMessage(message, allow, dontAllow, askLater).then(result => {
switch (result) {
case allow: {
this.configuration.updateCustomConfigurationProvider(provider.extensionId).then(() => {
onRegistered();
telemetry.logLanguageServerEvent("customConfigurationProvider", { "providerId": provider.extensionId });
});
ask.Value = false;
return true;
}
case dontAllow: {
ask.Value = false;
break;
}
default: {
break;
}
}
return false;
});
},
() => ask.Value = false);
}
} else if (selectedProvider === provider.extensionId) {
onRegistered();
telemetry.logLanguageServerEvent("customConfigurationProvider", { "providerId": provider.extensionId });
} else if (selectedProvider === provider.name) {
onRegistered();
this.configuration.updateCustomConfigurationProvider(provider.extensionId); // v0 -> v1 upgrade. Update the configurationProvider in c_cpp_properties.json
}
});
}
public updateCustomConfigurations(requestingProvider?: CustomConfigurationProvider1): Thenable<void> {
return this.notifyWhenReady(() => {
if (!this.configurationProvider) {
return;
}
let currentProvider: CustomConfigurationProvider1 = getCustomConfigProviders().get(this.configurationProvider);
if (!currentProvider || (requestingProvider && requestingProvider.extensionId !== currentProvider.extensionId) || this.trackedDocuments.size === 0) {
return;
}
let tokenSource: CancellationTokenSource = new CancellationTokenSource();
let documentUris: vscode.Uri[] = [];
this.trackedDocuments.forEach(document => documentUris.push(document.uri));
let task: () => Thenable<SourceFileConfigurationItem[]> = () => {
return currentProvider.provideConfigurations(documentUris, tokenSource.token);
};
this.queueTaskWithTimeout(task, configProviderTimeout, tokenSource).then(configs => this.sendCustomConfigurations(configs), () => {});
});
}
public updateCustomBrowseConfiguration(requestingProvider?: CustomConfigurationProvider1): Thenable<void> {
return this.notifyWhenReady(() => {
if (!this.configurationProvider) {
return;
}
console.log("updateCustomBrowseConfiguration");
let currentProvider: CustomConfigurationProvider1 = getCustomConfigProviders().get(this.configurationProvider);
if (!currentProvider || (requestingProvider && requestingProvider.extensionId !== currentProvider.extensionId)) {
return;
}
let tokenSource: CancellationTokenSource = new CancellationTokenSource();
let task: () => Thenable<WorkspaceBrowseConfiguration> = async () => {
if (await currentProvider.canProvideBrowseConfiguration(tokenSource.token)) {
return currentProvider.provideBrowseConfiguration(tokenSource.token);
}
if (currentProvider.version >= Version.v2) {
console.warn("failed to provide browse configuration");
}
return Promise.reject("");
};
this.queueTaskWithTimeout(task, configProviderTimeout, tokenSource).then(
async config => {
await this.sendCustomBrowseConfiguration(config);
this.resumeParsing();
},
() => {});
});
}
public async logDiagnostics(): Promise<void> {
let response: GetDiagnosticsResult = await this.requestWhenReady(() => this.languageClient.sendRequest(GetDiagnosticsRequest, null));
if (!this.diagnosticsChannel) {
this.diagnosticsChannel = vscode.window.createOutputChannel("C/C++ Diagnostics");
this.disposables.push(this.diagnosticsChannel);
}
let header: string = `-------- Diagnostics - ${new Date().toLocaleString()}\n`;
let version: string = `Version: ${util.packageJson.version}\n`;
this.diagnosticsChannel.appendLine(`${header}${version}${response.diagnostics}`);
this.diagnosticsChannel.show(false);
}
public async provideCustomConfiguration(document: vscode.TextDocument): Promise<void> {
let tokenSource: CancellationTokenSource = new CancellationTokenSource();
let providers: CustomConfigurationProviderCollection = getCustomConfigProviders();
if (providers.size === 0) {
return Promise.resolve();
}
console.log("provideCustomConfiguration");
let providerId: string|undefined = await this.getCustomConfigurationProviderId();
if (!providerId) {
return Promise.resolve();
}
let providerName: string = providerId;
let params: QueryTranslationUnitSourceParams = {
uri: document.uri.toString()
};
let response: QueryTranslationUnitSourceResult = await this.requestWhenReady(() => this.languageClient.sendRequest(QueryTranslationUnitSourceRequest, params));
if (response.configDisposition === QueryTranslationUnitSourceConfigDisposition.ConfigNotNeeded) {
return Promise.resolve();
}
let tuUri: vscode.Uri = vscode.Uri.parse(response.uri);
let configName: string = await this.getCurrentConfigName();
const notReadyMessage: string = `${providerName} is not ready`;
let provideConfigurationAsync: () => Thenable<SourceFileConfigurationItem[]> = async () => {
// The config requests that we use a provider, try to get IntelliSense configuration info from that provider.
try {
let provider: CustomConfigurationProvider1|null = providers.get(providerId);
if (provider) {
if (!provider.isReady) {
return Promise.reject(notReadyMessage);
}
providerName = provider.name;
if (await provider.canProvideConfiguration(tuUri, tokenSource.token)) {
return provider.provideConfigurations([tuUri], tokenSource.token);
}
}
} catch (err) {
}
console.warn("failed to provide configuration");
return Promise.reject("");
};
return this.queueTaskWithTimeout(provideConfigurationAsync, configProviderTimeout, tokenSource).then(
(configs: SourceFileConfigurationItem[]) => {
if (configs && configs.length > 0) {
this.sendCustomConfigurations(configs, true);
if (response.configDisposition === QueryTranslationUnitSourceConfigDisposition.AncestorConfigNeeded) {
// replacing uri with original uri
let newConfig: SourceFileConfigurationItem = { uri: document.uri, configuration: configs[0].configuration };
this.sendCustomConfigurations([newConfig], true);
}
}
},
(err) => {
if (err === notReadyMessage) {
return;
}
let settings: CppSettings = new CppSettings(this.RootUri);
if (settings.configurationWarnings === "Enabled" && !this.isExternalHeader(document.uri) && !vscode.debug.activeDebugSession) {
const dismiss: string = "Dismiss";
const disable: string = "Disable Warnings";
let message: string = `'${providerName}' is unable to provide IntelliSense configuration information for '${document.uri.fsPath}'. ` +
`Settings from the '${configName}' configuration will be used instead.`;
if (err) {
message += ` (${err})`;
}
vscode.window.showInformationMessage(message, dismiss, disable).then(response => {
switch (response) {
case disable: {
settings.toggleSetting("configurationWarnings", "Enabled", "Disabled");
break;
}
}
});
}
});
}
private isExternalHeader(uri: vscode.Uri): boolean {
return util.isHeader(uri) && !uri.toString().startsWith(this.RootUri.toString());
}
private getCustomConfigurationProviderId(): Thenable<string|undefined> {
return this.queueTask(() => Promise.resolve(this.configuration.CurrentConfigurationProvider));
}
public getCurrentConfigName(): Thenable<string> {
return this.queueTask(() => Promise.resolve(this.configuration.CurrentConfiguration.name));
}
public getCompilerPath(): Thenable<string> {
return this.queueTask(() => Promise.resolve(this.configuration.CompilerPath));
}
public getKnownCompilers(): Thenable<configs.KnownCompiler[]> {
return this.queueTask(() => Promise.resolve(this.configuration.KnownCompiler));
}
/**
* Take ownership of a document that was previously serviced by another client.
* This process involves sending a textDocument/didOpen message to the server so
* that it knows about the file, as well as adding it to this client's set of
* tracked documents.
*/
public takeOwnership(document: vscode.TextDocument): void {
let params: DidOpenTextDocumentParams = {
textDocument: {
uri: document.uri.toString(),
languageId: document.languageId,
version: document.version,
text: document.getText()
}
};
this.notifyWhenReady(() => this.languageClient.sendNotification(DidOpenNotification, params));
this.trackedDocuments.add(document);
}
/*************************************************************************************
* wait until the all pendingTasks are complete (e.g. language client is ready for use)
* before attempting to send messages or operate on the client.
*************************************************************************************/
public queueTask(task: () => Thenable<any>): Thenable<any> {
if (this.isSupported) {
let nextTask: () => Thenable<any> = async () => {
try {
return await task();
} catch (err) {
console.error(err);
throw err;
}
};
if (this.pendingTask && !this.pendingTask.Done) {
// We don't want the queue to stall because of a rejected promise.
return this.pendingTask.then(nextTask, nextTask);
} else {
this.pendingTask = undefined;
return nextTask();
}
} else {
return Promise.reject("Unsupported client");
}
}
/**
* Queue a task that blocks all future tasks until it completes. This is currently only intended to be used
* during language client startup and for custom configuration providers.
* @param task The task that blocks all future tasks
*/
private queueBlockingTask(task: () => Thenable<void>): Thenable<void> {
if (this.isSupported) {
this.pendingTask = new BlockingTask<void>(task, this.pendingTask);
} else {
return Promise.reject("Unsupported client");
}
}
private queueTaskWithTimeout(task: () => Thenable<any>, ms: number, cancelToken?: CancellationTokenSource): Thenable<any> {
let timer: NodeJS.Timer;
// Create a promise that rejects in <ms> milliseconds
let timeout: () => Promise<any> = () => new Promise((resolve, reject) => {
timer = setTimeout(() => {
clearTimeout(timer);
if (cancelToken) {
cancelToken.cancel();
}
reject("Timed out in " + ms + "ms.");
}, ms);
});
// Returns a race between our timeout and the passed in promise
return this.queueTask(() => {
return Promise.race([task(), timeout()]).then(
(result: any) => {
clearTimeout(timer);
return result;
},
(error: any) => {
clearTimeout(timer);
throw error;
});
});
}
public requestWhenReady(request: () => Thenable<any>): Thenable<any> {
return this.queueTask(request);
}
public notifyWhenReady(notify: () => void, blockingTask?: boolean): Thenable<void> {
let task: () => Thenable<void> = () => new Promise(resolve => {
notify();
resolve();
});
if (blockingTask) {
return this.queueBlockingTask(task);
} else {
return this.queueTask(task);
}
}
/**
* listen for notifications from the language server.
*/
private registerNotifications(): void {
console.assert(this.languageClient !== undefined, "This method must not be called until this.languageClient is set in \"onReady\"");
this.languageClient.onNotification(ReloadWindowNotification, () => util.promptForReloadWindowDueToSettingsChange());
this.languageClient.onNotification(LogTelemetryNotification, (e) => this.logTelemetry(e));
this.languageClient.onNotification(ReportNavigationNotification, (e) => this.navigate(e));
this.languageClient.onNotification(ReportStatusNotification, (e) => this.updateStatus(e));
this.languageClient.onNotification(ReportTagParseStatusNotification, (e) => this.updateTagParseStatus(e));
this.languageClient.onNotification(InactiveRegionNotification, (e) => this.updateInactiveRegions(e));
this.languageClient.onNotification(CompileCommandsPathsNotification, (e) => this.promptCompileCommands(e));
this.setupOutputHandlers();
}
/**
* listen for file created/deleted events under the ${workspaceFolder} folder
*/
private registerFileWatcher(): void {
console.assert(this.languageClient !== undefined, "This method must not be called until this.languageClient is set in \"onReady\"");
if (this.rootFolder) {
// WARNING: The default limit on Linux is 8k, so for big directories, this can cause file watching to fail.
this.rootPathFileWatcher = vscode.workspace.createFileSystemWatcher(
"**/*",
false /*ignoreCreateEvents*/,
true /*ignoreChangeEvents*/,
false /*ignoreDeleteEvents*/);
this.rootPathFileWatcher.onDidCreate((uri) => {
this.languageClient.sendNotification(FileCreatedNotification, { uri: uri.toString() });
});
this.rootPathFileWatcher.onDidDelete((uri) => {
this.languageClient.sendNotification(FileDeletedNotification, { uri: uri.toString() });
});
this.disposables.push(this.rootPathFileWatcher);
} else {
this.rootPathFileWatcher = undefined;
}
}
/**
* listen for logging messages from the language server and print them to the Output window
*/
private setupOutputHandlers(): void {
console.assert(this.languageClient !== undefined, "This method must not be called until this.languageClient is set in \"onReady\"");
this.languageClient.onNotification(DebugProtocolNotification, (output) => {
if (!this.debugChannel) {
this.debugChannel = vscode.window.createOutputChannel(`C/C++ Debug Protocol: ${this.Name}`);
this.disposables.push(this.debugChannel);
}
this.debugChannel.appendLine("");
this.debugChannel.appendLine("************************************************************************************************************************");
this.debugChannel.append(`${output}`);
});
this.languageClient.onNotification(DebugLogNotification, (output) => {
if (!this.outputChannel) {
if (vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) {
this.outputChannel = vscode.window.createOutputChannel(`C/C++: ${this.Name}`);
} else {
this.outputChannel = logger.getOutputChannel();
}
this.disposables.push(this.outputChannel);
}
this.outputChannel.appendLine(`${output}`);
});
}
/*******************************************************
* handle notifications coming from the language server
*******************************************************/
private logTelemetry(notificationBody: TelemetryPayload): void {
telemetry.logLanguageServerEvent(notificationBody.event, notificationBody.properties, notificationBody.metrics);
}
private navigate(payload: NavigationPayload): void {
let cppSettings: CppSettings = new CppSettings(this.RootUri);
// TODO: Move this code to a different place?
if (cppSettings.autoAddFileAssociations && payload.navigation.startsWith("<def")) {
let fileAssociations: string = payload.navigation.substr(4);
let is_c: boolean = fileAssociations.startsWith("c");
// Skip over rest of header: c>; or >;
fileAssociations = fileAssociations.substr(is_c ? 3 : 2);
this.addFileAssociations(fileAssociations, is_c);
return;
}
// If it's too big, it doesn't appear.
// The space available depends on the user's resolution and space taken up by other UI.
let currentNavigation: string = payload.navigation;
let maxLength: number = cppSettings.navigationLength;
if (currentNavigation.length > maxLength) {
currentNavigation = currentNavigation.substring(0, maxLength - 3).concat("...");
}
this.model.navigationLocation.Value = currentNavigation;
}
public addFileAssociations(fileAssociations: string, is_c: boolean): void {
let settings: OtherSettings = new OtherSettings(this.RootUri);
let assocs: any = settings.filesAssociations;
let filesAndPaths: string[] = fileAssociations.split(";");
let foundNewAssociation: boolean = false;
for (let i: number = 0; i < filesAndPaths.length; ++i) {
let fileAndPath: string[] = filesAndPaths[i].split("@");
// Skip empty or malformed
if (fileAndPath.length === 2) {
let file: string = fileAndPath[0];
let filePath: string = fileAndPath[1];
if ((file in assocs) || (("**/" + file) in assocs)) {
continue; // File already has an association.
}
let j: number = file.lastIndexOf('.');
if (j !== -1) {
let ext: string = file.substr(j);
if ((("*" + ext) in assocs) || (("**/*" + ext) in assocs)) {
continue; // Extension already has an association.
}
}
let foundGlobMatch: boolean = false;
for (let assoc in assocs) {
if (minimatch(filePath, assoc)) {
foundGlobMatch = true;
break; // Assoc matched a glob pattern.
}
}
if (foundGlobMatch) {
continue;