forked from microsoft/vscode-cpptools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.ts
2603 lines (2371 loc) · 137 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, Position, DocumentFilter
} from 'vscode-languageclient';
import { SourceFileConfigurationItem, WorkspaceBrowseConfiguration, SourceFileConfiguration, Version } from 'vscode-cpptools';
import { Status, IntelliSenseStatus } 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 { SettingsTracker, getTracker } from './settingsTracker';
import { getTestHook, TestHook } from '../testHook';
import { getCustomConfigProviders, CustomConfigurationProvider1, isSameProviderExtensionId } from '../LanguageServer/customProviders';
import { ABTestSettings, getABTestSettings } from '../abTesting';
import * as fs from 'fs';
import * as os from 'os';
import { TokenKind, ColorizationSettings, ColorizationState } from './colorization';
import * as refs from './references';
import * as nls from 'vscode-nls';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
type LocalizeStringParams = util.LocalizeStringParams;
let ui: UI;
let timeStamp: number = 0;
const configProviderTimeout: number = 2000;
// Data shared by all clients.
let languageClient: LanguageClient;
let clientCollection: ClientCollection;
let pendingTask: util.BlockingTask<any> | undefined;
let compilerDefaults: configs.CompilerDefaults;
let diagnosticsChannel: vscode.OutputChannel;
let outputChannel: vscode.OutputChannel;
let debugChannel: vscode.OutputChannel;
let diagnosticsCollection: vscode.DiagnosticCollection;
let workspaceColorizationState: Map<string, ColorizationState> = new Map<string, ColorizationState>();
let workspaceDisposables: vscode.Disposable[] = [];
let workspaceReferences: refs.ReferencesManager;
export function disposeWorkspaceData(): void {
workspaceDisposables.forEach((d) => d.dispose());
workspaceDisposables = [];
workspaceColorizationState.forEach(colorizationState => {
colorizationState.dispose();
});
}
function logTelemetry(notificationBody: TelemetryPayload): void {
telemetry.logLanguageServerEvent(notificationBody.event, notificationBody.properties, notificationBody.metrics);
}
/**
* listen for logging messages from the language server and print them to the Output window
*/
function setupOutputHandlers(): void {
console.assert(languageClient !== undefined, "This method must not be called until this.languageClient is set in \"onReady\"");
languageClient.onNotification(DebugProtocolNotification, (output) => {
if (!debugChannel) {
debugChannel = vscode.window.createOutputChannel(`${localize("c.cpp.debug.protocol", "C/C++ Debug Protocol")}`);
workspaceDisposables.push(debugChannel);
}
debugChannel.appendLine("");
debugChannel.appendLine("************************************************************************************************************************");
debugChannel.append(`${output}`);
});
languageClient.onNotification(DebugLogNotification, logLocalized);
}
function log(output: string): void {
if (!outputChannel) {
outputChannel = logger.getOutputChannel();
workspaceDisposables.push(outputChannel);
}
outputChannel.appendLine(`${output}`);
}
function logLocalized(params: LocalizeStringParams): void {
let output: string = util.getLocalizedString(params);
log(output);
}
function showMessageWindow(params: ShowMessageWindowParams): void {
let message: string = util.getLocalizedString(params.localizeStringParams);
switch (params.type) {
case 1: // Error
vscode.window.showErrorMessage(message);
break;
case 2: // Warning
vscode.window.showWarningMessage(message);
break;
case 3: // Info
vscode.window.showInformationMessage(message);
break;
default:
console.assert("Unrecognized type for showMessageWindow");
break;
}
}
function publishDiagnostics(params: PublishDiagnosticsParams): void {
if (!diagnosticsCollection) {
diagnosticsCollection = vscode.languages.createDiagnosticCollection("C/C++");
}
// Convert from our Diagnostic objects to vscode Diagnostic objects
let diagnostics: vscode.Diagnostic[] = [];
params.diagnostics.forEach((d) => {
let message: string = util.getLocalizedString(d.localizeStringParams);
let r: vscode.Range = new vscode.Range(d.range.start.line, d.range.start.character, d.range.end.line, d.range.end.character);
let diagnostic: vscode.Diagnostic = new vscode.Diagnostic(r, message, d.severity);
diagnostic.code = d.code;
diagnostic.source = d.source;
diagnostics.push(diagnostic);
});
let realUri: vscode.Uri = vscode.Uri.parse(params.uri);
diagnosticsCollection.set(realUri, diagnostics);
}
function updateSemanticColorizationRegions(params: SemanticColorizationRegionsParams): void {
let colorizationState: ColorizationState | undefined = workspaceColorizationState.get(params.uri);
if (colorizationState) {
// Convert the params to vscode.Range's before passing to colorizationState.updateSemantic()
let semanticRanges: vscode.Range[][] = new Array<vscode.Range[]>(TokenKind.Count);
for (let i: number = 0; i < TokenKind.Count; i++) {
semanticRanges[i] = [];
}
params.regions.forEach(element => {
let newRange: vscode.Range = new vscode.Range(element.range.start.line, element.range.start.character, element.range.end.line, element.range.end.character);
semanticRanges[element.kind].push(newRange);
});
let inactiveRanges: vscode.Range[] = [];
params.inactiveRegions.forEach(element => {
let newRange: vscode.Range = new vscode.Range(element.startLine, 0, element.endLine, 0);
inactiveRanges.push(newRange);
});
colorizationState.updateSemantic(params.uri, semanticRanges, inactiveRanges, params.editVersion);
languageClient.sendNotification(SemanticColorizationRegionsReceiptNotification, { uri: params.uri });
}
}
interface WorkspaceFolderParams {
workspaceFolderUri?: string;
}
interface TelemetryPayload {
event: string;
properties?: { [key: string]: string };
metrics?: { [key: string]: number };
}
interface DebugProtocolParams {
jsonrpc: string;
method: string;
params?: any;
}
interface ReportStatusNotificationBody extends WorkspaceFolderParams {
status: string;
}
interface QueryCompilerDefaultsParams {
}
interface CppPropertiesParams extends WorkspaceFolderParams {
currentConfiguration: number;
configurations: any[];
isReady?: boolean;
}
interface FolderSelectedSettingParams extends WorkspaceFolderParams {
currentConfiguration: number;
}
interface SwitchHeaderSourceParams extends WorkspaceFolderParams {
switchHeaderSourceFileName: string;
}
interface FileChangedParams extends WorkspaceFolderParams {
uri: string;
}
interface SemanticColorizationRegionsParams {
uri: string;
regions: InputColorizationRegion[];
inactiveRegions: InputRegion[];
editVersion: number;
}
interface InputRegion {
startLine: number;
endLine: number;
}
interface InputColorizationRegion {
range: Range;
kind: number;
}
// Need to convert vscode.Uri to a string before sending it to the language server.
interface SourceFileConfigurationItemAdapter {
uri: string;
configuration: SourceFileConfiguration;
}
interface CustomConfigurationParams extends WorkspaceFolderParams {
configurationItems: SourceFileConfigurationItemAdapter[];
}
interface CustomBrowseConfigurationParams extends WorkspaceFolderParams {
browseConfiguration: WorkspaceBrowseConfiguration;
}
interface CompileCommandsPaths extends WorkspaceFolderParams {
paths: string[];
}
interface QueryTranslationUnitSourceParams extends WorkspaceFolderParams {
uri: string;
}
interface QueryTranslationUnitSourceResult {
candidates: string[];
}
interface GetDiagnosticsResult {
diagnostics: string;
}
interface DidChangeVisibleRangesParams {
uri: string;
ranges: Range[];
}
interface SemanticColorizationRegionsReceiptParams {
uri: string;
}
interface ColorThemeChangedParams {
name: string;
}
interface Diagnostic {
range: Range;
code?: number | string;
source?: string;
severity: vscode.DiagnosticSeverity;
localizeStringParams: LocalizeStringParams;
}
interface PublishDiagnosticsParams {
uri: string;
diagnostics: Diagnostic[];
}
interface GetCodeActionsRequestParams {
uri: string;
range: Range;
}
interface CodeActionCommand {
localizeStringParams: LocalizeStringParams;
command: string;
arguments?: any[];
}
interface ShowMessageWindowParams {
type: number;
localizeStringParams: LocalizeStringParams;
}
interface GetDocumentSymbolRequestParams {
uri: string;
}
interface WorkspaceSymbolParams extends WorkspaceFolderParams {
query: string;
}
interface LocalizeDocumentSymbol {
name: string;
detail: LocalizeStringParams;
kind: vscode.SymbolKind;
range: Range;
selectionRange: Range;
children: LocalizeDocumentSymbol[];
}
interface Location {
uri: string;
range: Range;
}
interface LocalizeSymbolInformation {
name: string;
kind: vscode.SymbolKind;
location: Location;
containerName: string;
suffix: LocalizeStringParams;
}
export interface RenameParams {
newName: string;
position: Position;
textDocument: TextDocumentIdentifier;
}
export interface FindAllReferencesParams {
position: Position;
textDocument: TextDocumentIdentifier;
}
interface DidChangeConfigurationParams extends WorkspaceFolderParams {
settings: any;
}
// Requests
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');
const GetCodeActionsRequest: RequestType<GetCodeActionsRequestParams, CodeActionCommand[], void, void> = new RequestType<GetCodeActionsRequestParams, CodeActionCommand[], void, void>('cpptools/getCodeActions');
const GetDocumentSymbolRequest: RequestType<GetDocumentSymbolRequestParams, LocalizeDocumentSymbol[], void, void> = new RequestType<GetDocumentSymbolRequestParams, LocalizeDocumentSymbol[], void, void>('cpptools/getDocumentSymbols');
const GetSymbolInfoRequest: RequestType<WorkspaceSymbolParams, LocalizeSymbolInformation[], void, void> = new RequestType<WorkspaceSymbolParams, LocalizeSymbolInformation[], void, void>('cpptools/getWorkspaceSymbols');
// 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 FileChangedNotification: NotificationType<FileChangedParams, void> = new NotificationType<FileChangedParams, void>('cpptools/fileChanged');
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 ChangeCppPropertiesNotification: NotificationType<CppPropertiesParams, void> = new NotificationType<CppPropertiesParams, void>('cpptools/didChangeCppProperties');
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<WorkspaceFolderParams, void> = new NotificationType<WorkspaceFolderParams, void>('cpptools/clearCustomConfigurations');
const ClearCustomBrowseConfigurationNotification: NotificationType<WorkspaceFolderParams, void> = new NotificationType<WorkspaceFolderParams, void>('cpptools/clearCustomBrowseConfiguration');
const RescanFolderNotification: NotificationType<void, void> = new NotificationType<void, void>('cpptools/rescanFolder');
const DidChangeVisibleRangesNotification: NotificationType<DidChangeVisibleRangesParams, void> = new NotificationType<DidChangeVisibleRangesParams, void>('cpptools/didChangeVisibleRanges');
const SemanticColorizationRegionsReceiptNotification: NotificationType<SemanticColorizationRegionsReceiptParams, void> = new NotificationType<SemanticColorizationRegionsReceiptParams, void>('cpptools/semanticColorizationRegionsReceipt');
const ColorThemeChangedNotification: NotificationType<ColorThemeChangedParams, void> = new NotificationType<ColorThemeChangedParams, void>('cpptools/colorThemeChanged');
const RequestReferencesNotification: NotificationType<boolean, void> = new NotificationType<boolean, void>('cpptools/requestReferences');
const CancelReferencesNotification: NotificationType<void, void> = new NotificationType<void, void>('cpptools/cancelReferences');
const FinishedRequestCustomConfig: NotificationType<string, void> = new NotificationType<string, void>('cpptools/finishedRequestCustomConfig');
const FindAllReferencesNotification: NotificationType<FindAllReferencesParams, void> = new NotificationType<FindAllReferencesParams, void>('cpptools/findAllReferences');
const RenameNotification: NotificationType<RenameParams, void> = new NotificationType<RenameParams, void>('cpptools/rename');
const DidChangeSettingsNotification: NotificationType<DidChangeConfigurationParams, void> = new NotificationType<DidChangeConfigurationParams, void>('cpptools/didChangeSettings');
// 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 ReportTagParseStatusNotification: NotificationType<LocalizeStringParams, void> = new NotificationType<LocalizeStringParams, void>('cpptools/reportTagParseStatus');
const ReportStatusNotification: NotificationType<ReportStatusNotificationBody, void> = new NotificationType<ReportStatusNotificationBody, void>('cpptools/reportStatus');
const DebugProtocolNotification: NotificationType<DebugProtocolParams, void> = new NotificationType<DebugProtocolParams, void>('cpptools/debugProtocol');
const DebugLogNotification: NotificationType<LocalizeStringParams, void> = new NotificationType<LocalizeStringParams, void>('cpptools/debugLog');
const SemanticColorizationRegionsNotification: NotificationType<SemanticColorizationRegionsParams, void> = new NotificationType<SemanticColorizationRegionsParams, void>('cpptools/semanticColorizationRegions');
const CompileCommandsPathsNotification: NotificationType<CompileCommandsPaths, void> = new NotificationType<CompileCommandsPaths, void>('cpptools/compileCommandsPaths');
const ReferencesNotification: NotificationType<refs.ReferencesResultMessage, void> = new NotificationType<refs.ReferencesResultMessage, void>('cpptools/references');
const ReportReferencesProgressNotification: NotificationType<refs.ReportReferencesProgressNotification, void> = new NotificationType<refs.ReportReferencesProgressNotification, void>('cpptools/reportReferencesProgress');
const RequestCustomConfig: NotificationType<string, void> = new NotificationType<string, void>('cpptools/requestCustomConfig');
const PublishDiagnosticsNotification: NotificationType<PublishDiagnosticsParams, void> = new NotificationType<PublishDiagnosticsParams, void>('cpptools/publishDiagnostics');
const ShowMessageWindowNotification: NotificationType<ShowMessageWindowParams, void> = new NotificationType<ShowMessageWindowParams, void>('cpptools/showMessageWindow');
const ReportTextDocumentLanguage: NotificationType<string, void> = new NotificationType<string, void>('cpptools/reportTextDocumentLanguage');
let failureMessageShown: boolean = false;
let referencesRequestPending: boolean = false;
let renamePending: boolean = false;
let renameRequestsPending: number = 0;
let referencesParams: RenameParams | FindAllReferencesParams | undefined;
interface ReferencesCancellationState {
reject(): void;
callback(): void;
}
let referencesPendingCancellations: ReferencesCancellationState[] = [];
class ClientModel {
public isTagParsing: DataBinding<boolean>;
public isUpdatingIntelliSense: DataBinding<boolean>;
public referencesCommandMode: DataBinding<refs.ReferencesCommandMode>;
public tagParserStatus: DataBinding<string>;
public activeConfigName: DataBinding<string>;
constructor() {
this.isTagParsing = new DataBinding<boolean>(false);
this.isUpdatingIntelliSense = new DataBinding<boolean>(false);
this.referencesCommandMode = new DataBinding<refs.ReferencesCommandMode>(refs.ReferencesCommandMode.None);
this.tagParserStatus = new DataBinding<string>("");
this.activeConfigName = new DataBinding<string>("");
}
public activate(): void {
this.isTagParsing.activate();
this.isUpdatingIntelliSense.activate();
this.referencesCommandMode.activate();
this.tagParserStatus.activate();
this.activeConfigName.activate();
}
public deactivate(): void {
this.isTagParsing.deactivate();
this.isUpdatingIntelliSense.deactivate();
this.referencesCommandMode.deactivate();
this.tagParserStatus.deactivate();
this.activeConfigName.deactivate();
}
public dispose(): void {
this.isTagParsing.dispose();
this.isUpdatingIntelliSense.dispose();
this.referencesCommandMode.dispose();
this.tagParserStatus.dispose();
this.activeConfigName.dispose();
}
}
export interface Client {
TagParsingChanged: vscode.Event<boolean>;
IntelliSenseParsingChanged: vscode.Event<boolean>;
ReferencesCommandModeChanged: vscode.Event<refs.ReferencesCommandMode>;
TagParserStatusChanged: vscode.Event<string>;
ActiveConfigChanged: vscode.Event<string>;
RootPath: string;
RootUri?: vscode.Uri;
Name: string;
TrackedDocuments: Set<vscode.TextDocument>;
onDidChangeSettings(event: vscode.ConfigurationChangeEvent, isFirstClient: boolean): { [key: string]: string };
onDidOpenTextDocument(document: vscode.TextDocument): void;
onDidCloseTextDocument(document: vscode.TextDocument): void;
onDidChangeVisibleTextEditors(editors: vscode.TextEditor[]): void;
onDidChangeTextDocument(textDocumentChangeEvent: vscode.TextDocumentChangeEvent): void;
onDidChangeTextEditorVisibleRanges(textEditorVisibleRangesChangeEvent: vscode.TextEditorVisibleRangesChangeEvent): void;
onRegisterCustomConfigurationProvider(provider: CustomConfigurationProvider1): Thenable<void>;
updateCustomConfigurations(requestingProvider?: CustomConfigurationProvider1): Thenable<void>;
updateCustomBrowseConfiguration(requestingProvider?: CustomConfigurationProvider1): Thenable<void>;
provideCustomConfiguration(docUri: vscode.Uri, requestFile?: string): Promise<void>;
logDiagnostics(): Promise<void>;
rescanFolder(): Promise<void>;
toggleReferenceResultsView(): void;
setCurrentConfigName(configurationName: string): Thenable<void>;
getCurrentConfigName(): Thenable<string | undefined>;
getVcpkgInstalled(): Thenable<boolean>;
getVcpkgEnabled(): Thenable<boolean>;
getCurrentCompilerPathAndArgs(): Thenable<util.CompilerPathAndArgs | undefined>;
getKnownCompilers(): Thenable<configs.KnownCompiler[] | undefined>;
takeOwnership(document: vscode.TextDocument): void;
queueTask<T>(task: () => Thenable<T>): Thenable<T>;
requestWhenReady<T>(request: () => Thenable<T>): Thenable<T>;
notifyWhenReady(notify: () => void): void;
requestSwitchHeaderSource(rootPath: string, fileName: string): 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;
handleReferencesIcon(): 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();
}
export class DefaultClient implements Client {
private innerLanguageClient?: LanguageClient; // The "client" that launches and communicates with our language "server" process.
private disposables: vscode.Disposable[] = [];
private innerConfiguration?: configs.CppProperties;
private rootPathFileWatcher?: vscode.FileSystemWatcher;
private rootFolder?: vscode.WorkspaceFolder;
private storagePath: string;
private trackedDocuments = new Set<vscode.TextDocument>();
private crashTimes: number[] = [];
private isSupported: boolean = true;
private colorizationSettings: ColorizationSettings;
private openFileVersions = new Map<string, number>();
private visibleRanges = new Map<string, Range[]>();
private settingsTracker: SettingsTracker;
private configurationProvider?: string;
// The "model" that is displayed via the UI (status bar).
private model: ClientModel = new ClientModel();
public get TagParsingChanged(): vscode.Event<boolean> { return this.model.isTagParsing.ValueChanged; }
public get IntelliSenseParsingChanged(): vscode.Event<boolean> { return this.model.isUpdatingIntelliSense.ValueChanged; }
public get ReferencesCommandModeChanged(): vscode.Event<refs.ReferencesCommandMode> { return this.model.referencesCommandMode.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 | undefined {
return (this.rootFolder) ? this.rootFolder.uri : undefined;
}
public get RootFolder(): vscode.WorkspaceFolder | undefined {
return this.rootFolder;
}
public get Name(): string {
return this.getName(this.rootFolder);
}
public get TrackedDocuments(): Set<vscode.TextDocument> {
return this.trackedDocuments;
}
public get IsTagParsing(): boolean {
return this.model.isTagParsing.Value;
}
public get ReferencesCommandMode(): refs.ReferencesCommandMode {
return this.model.referencesCommandMode.Value;
}
private get languageClient(): LanguageClient {
if (!this.innerLanguageClient) {
throw new Error("Attempting to use languageClient before initialized");
}
return this.innerLanguageClient;
}
private get configuration(): configs.CppProperties {
if (!this.innerConfiguration) {
throw new Error("Attempting to use configuration before initialized");
}
return this.innerConfiguration;
}
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)
*/
constructor(allClients: ClientCollection, workspaceFolder?: vscode.WorkspaceFolder) {
this.rootFolder = workspaceFolder;
let storagePath: string | undefined;
if (util.extensionContext) {
let path: string | undefined = util.extensionContext.storagePath;
if (path) {
storagePath = path;
}
}
if (!storagePath) {
storagePath = path.join(this.RootPath, "/.vscode");
}
if (workspaceFolder && vscode.workspace.workspaceFolders && vscode.workspace.workspaceFolders.length > 1) {
storagePath = path.join(storagePath, util.getUniqueWorkspaceStorageName(workspaceFolder));
}
this.storagePath = storagePath;
const rootUri: vscode.Uri | undefined = this.RootUri;
if (!rootUri) {
throw new Error("Empty URI in client constructor");
}
this.settingsTracker = getTracker(rootUri);
this.colorizationSettings = new ColorizationSettings(rootUri);
try {
let firstClient: boolean = false;
if (!languageClient) {
languageClient = this.createLanguageClient(allClients);
clientCollection = 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());
firstClient = true;
}
ui = getUI();
ui.bind(this);
// requests/notifications are deferred until this.languageClient is set.
this.queueBlockingTask(() => languageClient.onReady().then(
() => {
let workspaceFolder: vscode.WorkspaceFolder | undefined = this.rootFolder;
if (!workspaceFolder) {
throw new Error("Empty URI in client constructor");
}
this.innerConfiguration = new configs.CppProperties(rootUri, workspaceFolder);
this.innerConfiguration.ConfigurationsChanged((e) => this.onConfigurationsChanged(e));
this.innerConfiguration.SelectionChanged((e) => this.onSelectedConfigurationChanged(e));
this.innerConfiguration.CompileCommandsChanged((e) => this.onCompileCommandsChanged(e));
this.disposables.push(this.innerConfiguration);
this.innerLanguageClient = languageClient;
telemetry.logLanguageServerEvent("NonDefaultInitialCppSettings", this.settingsTracker.getUserModifiedSettings());
failureMessageShown = false;
let documentSelector: DocumentFilter[] = [
{ scheme: 'file', language: 'cpp' },
{ scheme: 'file', language: 'c' }
];
class CodeActionProvider implements vscode.CodeActionProvider {
private client: DefaultClient;
constructor(client: DefaultClient) {
this.client = client;
}
public async provideCodeActions(document: vscode.TextDocument, range: vscode.Range | vscode.Selection, context: vscode.CodeActionContext, token: vscode.CancellationToken): Promise<(vscode.Command | vscode.CodeAction)[]> {
return this.client.requestWhenReady(() => {
let r: Range;
if (range instanceof vscode.Selection) {
if (range.active.isBefore(range.anchor)) {
r = Range.create(Position.create(range.active.line, range.active.character), Position.create(range.anchor.line, range.anchor.character));
} else {
r = Range.create(Position.create(range.anchor.line, range.anchor.character), Position.create(range.active.line, range.active.character));
}
} else {
r = Range.create(Position.create(range.start.line, range.start.character), Position.create(range.end.line, range.end.character));
}
let params: GetCodeActionsRequestParams = {
range: r,
uri: document.uri.toString()
};
return this.client.languageClient.sendRequest(GetCodeActionsRequest, params)
.then((commands) => {
let resultCodeActions: vscode.CodeAction[] = [];
// Convert to vscode.CodeAction array
commands.forEach((command) => {
let title: string = util.getLocalizedString(command.localizeStringParams);
let vscodeCodeAction: vscode.CodeAction = {
title: title,
command: {
title: title,
command: command.command,
arguments: command.arguments
}
};
resultCodeActions.push(vscodeCodeAction);
});
return resultCodeActions;
});
});
}
}
class DocumentSymbolProvider implements vscode.DocumentSymbolProvider {
private client: DefaultClient;
constructor(client: DefaultClient) {
this.client = client;
}
private getChildrenSymbols(symbols: LocalizeDocumentSymbol[]): vscode.DocumentSymbol[] {
let documentSymbols: vscode.DocumentSymbol[] = [];
if (symbols) {
symbols.forEach((symbol) => {
let detail: string = util.getLocalizedString(symbol.detail);
let r: vscode.Range= new vscode.Range(symbol.range.start.line, symbol.range.start.character, symbol.range.end.line, symbol.range.end.character);
let sr: vscode.Range= new vscode.Range(symbol.selectionRange.start.line, symbol.selectionRange.start.character, symbol.selectionRange.end.line, symbol.selectionRange.end.character);
let vscodeSymbol: vscode.DocumentSymbol = new vscode.DocumentSymbol (symbol.name, detail, symbol.kind, r, sr);
vscodeSymbol.children = this.getChildrenSymbols(symbol.children);
documentSymbols.push(vscodeSymbol);
});
}
return documentSymbols;
}
public async provideDocumentSymbols(document: vscode.TextDocument): Promise<vscode.SymbolInformation[] | vscode.DocumentSymbol[]> {
return this.client.requestWhenReady(() => {
let params: GetDocumentSymbolRequestParams = {
uri: document.uri.toString()
};
return this.client.languageClient.sendRequest(GetDocumentSymbolRequest, params)
.then((symbols) => {
let resultSymbols: vscode.DocumentSymbol[] = this.getChildrenSymbols(symbols);
return resultSymbols;
});
});
}
}
class WorkspaceSymbolProvider implements vscode.WorkspaceSymbolProvider {
private client: DefaultClient;
constructor(client: DefaultClient) {
this.client = client;
}
public async provideWorkspaceSymbols(query: string, token: vscode.CancellationToken): Promise<vscode.SymbolInformation[]> {
let params: WorkspaceSymbolParams = {
query: query,
workspaceFolderUri: this.client.RootPath
};
return this.client.languageClient.sendRequest(GetSymbolInfoRequest, params)
.then((symbols) => {
let resultSymbols: vscode.SymbolInformation[] = [];
// Convert to vscode.Command array
symbols.forEach((symbol) => {
let suffix: string = util.getLocalizedString(symbol.suffix);
let name: string = symbol.name;
let range: vscode.Range = new vscode.Range(symbol.location.range.start.line, symbol.location.range.start.character, symbol.location.range.end.line, symbol.location.range.end.character);
let uri: vscode.Uri = vscode.Uri.parse(symbol.location.uri.toString());
if (suffix.length) {
name = name + ' (' + suffix + ')';
}
let vscodeSymbol: vscode.SymbolInformation = new vscode.SymbolInformation(
name,
symbol.kind,
range,
uri,
symbol.containerName
);
resultSymbols.push(vscodeSymbol);
});
return resultSymbols;
});
}
}
class FindAllReferencesProvider implements vscode.ReferenceProvider {
private client: DefaultClient;
constructor(client: DefaultClient) {
this.client = client;
}
public async provideReferences(document: vscode.TextDocument, position: vscode.Position, context: vscode.ReferenceContext, token: vscode.CancellationToken): Promise<vscode.Location[] | undefined> {
return new Promise<vscode.Location[]>((resolve, reject) => {
let callback: () => void = () => {
let params: FindAllReferencesParams = {
position: Position.create(position.line, position.character),
textDocument: this.client.languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document)
};
referencesParams = params;
this.client.notifyWhenReady(() => {
// The current request is represented by referencesParams. If a request detects
// referencesParams does not match the object used when creating the request, abort it.
if (params !== referencesParams) {
// Complete with nothing instead of rejecting, to avoid an error message from VS Code
let locations: vscode.Location[] = [];
resolve(locations);
return;
}
referencesRequestPending = true;
// Register a single-fire handler for the reply.
let resultCallback: refs.ReferencesResultCallback = (result: refs.ReferencesResult | null, doResolve: boolean) => {
referencesRequestPending = false;
let locations: vscode.Location[] = [];
if (result) {
result.referenceInfos.forEach((referenceInfo: refs.ReferenceInfo) => {
if (referenceInfo.type === refs.ReferenceType.Confirmed) {
let uri: vscode.Uri = vscode.Uri.file(referenceInfo.file);
let range: vscode.Range = new vscode.Range(referenceInfo.position.line, referenceInfo.position.character, referenceInfo.position.line, referenceInfo.position.character + result.text.length);
locations.push(new vscode.Location(uri, range));
}
});
}
// If references were canceled while in a preview state, there is not an outstanding promise.
if (doResolve) {
resolve(locations);
}
if (referencesPendingCancellations.length > 0) {
while (referencesPendingCancellations.length > 1) {
let pendingCancel: ReferencesCancellationState = referencesPendingCancellations[0];
referencesPendingCancellations.pop();
pendingCancel.reject();
}
let pendingCancel: ReferencesCancellationState = referencesPendingCancellations[0];
referencesPendingCancellations.pop();
pendingCancel.callback();
}
};
if (!workspaceReferences.referencesRefreshPending) {
workspaceReferences.setResultsCallback(resultCallback);
workspaceReferences.startFindAllReferences(params);
} else {
// We are responding to a refresh (preview or final result)
workspaceReferences.referencesRefreshPending = false;
if (workspaceReferences.lastResults) {
// This is a final result
let lastResults: refs.ReferencesResult = workspaceReferences.lastResults;
workspaceReferences.lastResults = null;
resultCallback(lastResults, true);
} else {
// This is a preview (2nd or later preview)
workspaceReferences.referencesRequestPending = true;
workspaceReferences.setResultsCallback(resultCallback);
this.client.languageClient.sendNotification(RequestReferencesNotification, false);
}
}
});
token.onCancellationRequested(e => {
if (params === referencesParams) {
this.client.cancelReferences();
}
});
};
if (referencesRequestPending || (workspaceReferences.symbolSearchInProgress && !workspaceReferences.referencesRefreshPending)) {
let cancelling: boolean = referencesPendingCancellations.length > 0;
referencesPendingCancellations.push({ reject: () => {
// Complete with nothing instead of rejecting, to avoid an error message from VS Code
let locations: vscode.Location[] = [];
resolve(locations);
}, callback });
if (!cancelling) {
renamePending = false;
workspaceReferences.referencesCanceled = true;
if (!referencesRequestPending) {
workspaceReferences.referencesCanceledWhilePreviewing = true;
}
this.client.languageClient.sendNotification(CancelReferencesNotification);
workspaceReferences.closeRenameUI();
}
} else {
callback();
}
});
}
}
class RenameProvider implements vscode.RenameProvider {
private client: DefaultClient;
constructor(client: DefaultClient) {
this.client = client;
}
public async provideRenameEdits(document: vscode.TextDocument, position: vscode.Position, newName: string, token: vscode.CancellationToken): Promise<vscode.WorkspaceEdit> {
let settings: CppSettings = new CppSettings();
if (settings.renameRequiresIdentifier && !util.isValidIdentifier(newName)) {
vscode.window.showErrorMessage(localize("invalid.identifier.for.rename", "Invalid identifier provided for the Rename Symbol operation."));
let workspaceEdit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit();
return Promise.resolve(workspaceEdit);
}
// Normally, VS Code considers rename to be an atomic operation.
// If the user clicks anywhere in the document, it attempts to cancel it.
// Because that prevents our rename UI, we ignore cancellation requests.
// VS Code will attempt to issue new rename requests while another is still active.
// When we receive another rename request, cancel the one that is in progress.
renamePending = true;
++renameRequestsPending;
return new Promise<vscode.WorkspaceEdit>((resolve, reject) => {
let callback: () => void = () => {
let params: RenameParams = {
newName: newName,
position: Position.create(position.line, position.character),
textDocument: this.client.languageClient.code2ProtocolConverter.asTextDocumentIdentifier(document)
};
referencesParams = params;
this.client.notifyWhenReady(() => {
// The current request is represented by referencesParams. If a request detects
// referencesParams does not match the object used when creating the request, abort it.
if (params !== referencesParams) {
if (--renameRequestsPending === 0) {
renamePending = false;
}
// Complete with nothing instead of rejecting, to avoid an error message from VS Code
let workspaceEdit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit();
resolve(workspaceEdit);
return;
}
referencesRequestPending = true;
workspaceReferences.setResultsCallback((referencesResult: refs.ReferencesResult | null, doResolve: boolean) => {
if (doResolve && referencesResult === null && referencesPendingCancellations.length === 0) {
// The result callback will be called with doResult of true and a null result when the Find All References
// portion of the rename is complete. We complete the promise with an empty edit at this point,
// to cause the progress indicator to be dismissed.
let workspaceEdit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit();
resolve(workspaceEdit);
} else {
referencesRequestPending = false;
--renameRequestsPending;
let workspaceEdit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit();
let cancelling: boolean = referencesPendingCancellations.length > 0;
if (cancelling) {
while (referencesPendingCancellations.length > 1) {
let pendingCancel: ReferencesCancellationState = referencesPendingCancellations[0];
referencesPendingCancellations.pop();
pendingCancel.reject();
}
let pendingCancel: ReferencesCancellationState = referencesPendingCancellations[0];
referencesPendingCancellations.pop();
pendingCancel.callback();
} else {
if (renameRequestsPending === 0) {
renamePending = false;
}
// If rename UI was canceled, we will get a null result.
// If null, return an empty list to avoid Rename failure dialog.
if (referencesResult) {
for (let reference of referencesResult.referenceInfos) {
let uri: vscode.Uri = vscode.Uri.file(reference.file);
let range: vscode.Range = new vscode.Range(reference.position.line, reference.position.character, reference.position.line, reference.position.character + referencesResult.text.length);
workspaceEdit.replace(uri, range, newName);
}
}
workspaceReferences.closeRenameUI();
}
if (doResolve) {
if (referencesResult && (referencesResult.referenceInfos === null || referencesResult.referenceInfos.length === 0)) {
vscode.window.showErrorMessage(localize("unable.to.locate.selected.symbol", "A definition for the selected symbol could not be located."));
}
resolve(workspaceEdit);
} else if (workspaceEdit.size > 0) {
vscode.workspace.applyEdit(workspaceEdit);
}
}
});
workspaceReferences.startRename(params);
});
};
if (referencesRequestPending || workspaceReferences.symbolSearchInProgress) {
let cancelling: boolean = referencesPendingCancellations.length > 0;
referencesPendingCancellations.push({ reject: () => {
--renameRequestsPending;
// Complete with nothing instead of rejecting, to avoid an error message from VS Code
let workspaceEdit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit();
resolve(workspaceEdit);
}, callback });
if (!cancelling) {
workspaceReferences.referencesCanceled = true;
if (!referencesRequestPending) {
workspaceReferences.referencesCanceledWhilePreviewing = true;
}
this.client.languageClient.sendNotification(CancelReferencesNotification);
workspaceReferences.closeRenameUI();
}
} else {
callback();
}
});
}
}
this.registerFileWatcher();
if (firstClient) {
this.disposables.push(vscode.languages.registerRenameProvider(documentSelector, new RenameProvider(this)));
this.disposables.push(vscode.languages.registerReferenceProvider(documentSelector, new FindAllReferencesProvider(this)));
this.disposables.push(vscode.languages.registerWorkspaceSymbolProvider(new WorkspaceSymbolProvider(this)));
this.disposables.push(vscode.languages.registerDocumentSymbolProvider(documentSelector, new DocumentSymbolProvider(this), undefined));
this.disposables.push(vscode.languages.registerCodeActionsProvider(documentSelector, new CodeActionProvider(this), undefined));
// Listen for messages from the language server.
this.registerNotifications();
workspaceReferences = new refs.ReferencesManager(this);
// 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((inputCompilerDefaults: configs.CompilerDefaults) => {
compilerDefaults = inputCompilerDefaults;
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();