forked from microsoft/vscode-cpptools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
configurations.ts
1652 lines (1494 loc) · 80.8 KB
/
configurations.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 fs from "fs";
import * as vscode from 'vscode';
import * as util from '../common';
import * as telemetry from '../telemetry';
import { PersistentFolderState } from './persistentState';
import { CppSettings, OtherSettings } from './settings';
import { ABTestSettings, getABTestSettings } from '../abTesting';
import { getCustomConfigProviders } from './customProviders';
import { SettingsPanel } from './settingsPanel';
import * as os from 'os';
import escapeStringRegExp = require('escape-string-regexp');
import * as jsonc from 'comment-json';
import * as nls from 'vscode-nls';
import which = require('which');
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
const configVersion: number = 4;
type Environment = { [key: string]: string | string[] };
// No properties are set in the config since we want to apply vscode settings first (if applicable).
// That code won't trigger if another value is already set.
// The property defaults are moved down to applyDefaultIncludePathsAndFrameworks.
function getDefaultConfig(): Configuration {
if (process.platform === 'darwin') {
return { name: "Mac" };
} else if (process.platform === 'win32') {
return { name: "Win32" };
} else {
return { name: "Linux" };
}
}
function getDefaultCppProperties(): ConfigurationJson {
return {
configurations: [getDefaultConfig()],
version: configVersion
};
}
export interface ConfigurationJson {
configurations: Configuration[];
env?: {[key: string]: string | string[]};
version: number;
enableConfigurationSquiggles?: boolean;
}
export interface Configuration {
name: string;
compilerPath?: string;
compilerArgs?: string[];
cStandard?: string;
cppStandard?: string;
includePath?: string[];
macFrameworkPath?: string[];
windowsSdkVersion?: string;
defines?: string[];
intelliSenseMode?: string;
compileCommands?: string;
forcedInclude?: string[];
configurationProvider?: string;
browse?: Browse;
customConfigurationVariables?: {[key: string]: string};
}
export interface ConfigurationErrors {
compilerPath?: string;
includePath?: string;
intelliSenseMode?: string;
macFrameworkPath?: string;
forcedInclude?: string;
compileCommands?: string;
browsePath?: string;
databaseFilename?: string;
}
export interface Browse {
path?: string[];
limitSymbolsToIncludedHeaders?: boolean | string;
databaseFilename?: string;
}
export interface KnownCompiler {
path: string;
isC: boolean;
}
export interface CompilerDefaults {
compilerPath: string;
compilerArgs: string[];
knownCompilers: KnownCompiler[];
cStandard: string;
cppStandard: string;
includes: string[];
frameworks: string[];
windowsSdkVersion: string;
intelliSenseMode: string;
rootfs: string;
}
export class CppProperties {
private rootUri: vscode.Uri | undefined;
private propertiesFile: vscode.Uri | undefined | null = undefined; // undefined and null values are handled differently
private readonly configFolder: string;
private configurationJson?: ConfigurationJson;
private currentConfigurationIndex: PersistentFolderState<number> | undefined;
private configFileWatcher: vscode.FileSystemWatcher | null = null;
private configFileWatcherFallbackTime: Date = new Date(); // Used when file watching fails.
private compileCommandFileWatchers: fs.FSWatcher[] = [];
private defaultCompilerPath: string | null = null;
private knownCompilers?: KnownCompiler[];
private defaultCStandard: string | null = null;
private defaultCppStandard: string | null = null;
private defaultIncludes: string[] | null = null;
private defaultFrameworks?: string[];
private defaultWindowsSdkVersion: string | null = null;
private vcpkgIncludes: string[] = [];
private vcpkgPathReady: boolean = false;
private defaultIntelliSenseMode?: string;
private defaultCustomConfigurationVariables?: { [key: string]: string };
private readonly configurationGlobPattern: string = "c_cpp_properties.json";
private disposables: vscode.Disposable[] = [];
private configurationsChanged = new vscode.EventEmitter<Configuration[]>();
private selectionChanged = new vscode.EventEmitter<number>();
private compileCommandsChanged = new vscode.EventEmitter<string>();
private diagnosticCollection: vscode.DiagnosticCollection;
private prevSquiggleMetrics: Map<string, { [key: string]: number }> = new Map<string, { [key: string]: number }>();
private rootfs: string | null = null;
private settingsPanel?: SettingsPanel;
// Any time the default settings are parsed and assigned to `this.configurationJson`,
// we want to track when the default includes have been added to it.
private configurationIncomplete: boolean = true;
constructor(rootUri?: vscode.Uri, workspaceFolder?: vscode.WorkspaceFolder) {
this.rootUri = rootUri;
const rootPath: string = rootUri ? rootUri.fsPath : "";
if (workspaceFolder) {
this.currentConfigurationIndex = new PersistentFolderState<number>("CppProperties.currentConfigurationIndex", -1, workspaceFolder);
}
this.configFolder = path.join(rootPath, ".vscode");
this.diagnosticCollection = vscode.languages.createDiagnosticCollection(rootPath);
this.buildVcpkgIncludePath();
this.disposables.push(vscode.Disposable.from(this.configurationsChanged, this.selectionChanged, this.compileCommandsChanged));
}
public get ConfigurationsChanged(): vscode.Event<Configuration[]> { return this.configurationsChanged.event; }
public get SelectionChanged(): vscode.Event<number> { return this.selectionChanged.event; }
public get CompileCommandsChanged(): vscode.Event<string> { return this.compileCommandsChanged.event; }
public get Configurations(): Configuration[] | undefined { return this.configurationJson ? this.configurationJson.configurations : undefined; }
public get CurrentConfigurationIndex(): number { return this.currentConfigurationIndex === undefined ? 0 : this.currentConfigurationIndex.Value; }
public get CurrentConfiguration(): Configuration | undefined { return this.Configurations ? this.Configurations[this.CurrentConfigurationIndex] : undefined; }
public get KnownCompiler(): KnownCompiler[] | undefined { return this.knownCompilers; }
public get CurrentConfigurationProvider(): string | undefined {
if (this.CurrentConfiguration?.configurationProvider) {
return this.CurrentConfiguration.configurationProvider;
}
return new CppSettings(this.rootUri).defaultConfigurationProvider;
}
public get ConfigurationNames(): string[] | undefined {
const result: string[] = [];
if (this.configurationJson) {
this.configurationJson.configurations.forEach((config: Configuration) => {
result.push(config.name);
});
}
return result;
}
public set CompilerDefaults(compilerDefaults: CompilerDefaults) {
this.defaultCompilerPath = compilerDefaults.compilerPath;
this.knownCompilers = compilerDefaults.knownCompilers;
this.defaultCStandard = compilerDefaults.cStandard;
this.defaultCppStandard = compilerDefaults.cppStandard;
this.defaultIncludes = compilerDefaults.includes;
this.defaultFrameworks = compilerDefaults.frameworks;
this.defaultWindowsSdkVersion = compilerDefaults.windowsSdkVersion;
this.defaultIntelliSenseMode = compilerDefaults.intelliSenseMode;
this.rootfs = compilerDefaults.rootfs;
// defaultPaths is only used when there isn't a c_cpp_properties.json, but we don't send the configuration changed event
// to the language server until the default include paths and frameworks have been sent.
const configFilePath: string = path.join(this.configFolder, "c_cpp_properties.json");
if (this.rootUri !== null && fs.existsSync(configFilePath)) {
this.propertiesFile = vscode.Uri.file(configFilePath);
} else {
this.propertiesFile = null;
}
const settingsPath: string = path.join(this.configFolder, this.configurationGlobPattern);
this.configFileWatcher = vscode.workspace.createFileSystemWatcher(settingsPath);
this.disposables.push(this.configFileWatcher);
this.configFileWatcher.onDidCreate((uri) => {
this.propertiesFile = uri;
this.handleConfigurationChange();
});
this.configFileWatcher.onDidDelete(() => {
this.propertiesFile = null;
this.resetToDefaultSettings(true);
this.handleConfigurationChange();
});
this.configFileWatcher.onDidChange(() => {
// If the file is one of the textDocument's vscode is tracking, we need to wait for an
// onDidChangeTextDocument event, or we may get old/cached contents when we open it.
let alreadyTracking: boolean = false;
for (let i: number = 0; i < vscode.workspace.textDocuments.length; i++) {
if (vscode.workspace.textDocuments[i].uri.fsPath === settingsPath) {
alreadyTracking = true;
break;
}
}
if (!alreadyTracking) {
this.handleConfigurationChange();
}
});
vscode.workspace.onDidChangeTextDocument((e: vscode.TextDocumentChangeEvent) => {
if (e.document.uri.fsPath === settingsPath) {
this.handleConfigurationChange();
}
});
this.handleConfigurationChange();
}
public get VcpkgInstalled(): boolean {
return this.vcpkgIncludes.length > 0;
}
private onConfigurationsChanged(): void {
this.configurationsChanged.fire(this.Configurations);
}
private onSelectionChanged(): void {
this.selectionChanged.fire(this.CurrentConfigurationIndex);
this.handleSquiggles();
}
private onCompileCommandsChanged(path: string): void {
this.compileCommandsChanged.fire(path);
}
public onDidChangeSettings(): void {
// Default settings may have changed in a way that affects the configuration.
// Just send another message since the language server will sort out whether anything important changed or not.
if (!this.propertiesFile) {
this.resetToDefaultSettings(true);
this.handleConfigurationChange();
} else if (!this.configurationIncomplete) {
this.handleConfigurationChange();
}
}
private resetToDefaultSettings(resetIndex: boolean): void {
this.configurationJson = getDefaultCppProperties();
if (resetIndex || this.CurrentConfigurationIndex < 0 ||
this.CurrentConfigurationIndex >= this.configurationJson.configurations.length) {
const index: number | undefined = this.getConfigIndexForPlatform(this.configurationJson);
if (this.currentConfigurationIndex !== undefined) {
if (index === undefined) {
this.currentConfigurationIndex.setDefault();
} else {
this.currentConfigurationIndex.Value = index;
}
}
}
this.configurationIncomplete = true;
}
private applyDefaultIncludePathsAndFrameworks(): void {
if (this.configurationIncomplete && this.defaultIncludes && this.defaultFrameworks && this.vcpkgPathReady) {
const configuration: Configuration | undefined = this.CurrentConfiguration;
if (configuration) {
this.applyDefaultConfigurationValues(configuration);
this.configurationIncomplete = false;
}
}
}
private applyDefaultConfigurationValues(configuration: Configuration): void {
const settings: CppSettings = new CppSettings(this.rootUri);
// default values for "default" config settings is null.
const isUnset: (input: any) => boolean = (input: any) => input === null || input === undefined;
// Anything that has a vscode setting for it will be resolved in updateServerOnFolderSettingsChange.
// So if a property is currently unset, but has a vscode setting, don't set it yet, otherwise the linkage
// to the setting will be lost if this configuration is saved into a c_cpp_properties.json file.
// Only add settings from the default compiler if user hasn't explicitly set the corresponding VS Code setting.
const abTestSettings: ABTestSettings = getABTestSettings();
const rootFolder: string = abTestSettings.UseRecursiveIncludes ? "${workspaceFolder}/**" : "${workspaceFolder}";
const defaultFolder: string = "${default}";
// We don't add system includes to the includePath anymore. The language server has this information.
if (isUnset(settings.defaultIncludePath)) {
configuration.includePath = [rootFolder].concat(this.vcpkgIncludes);
} else {
configuration.includePath = [defaultFolder];
}
// browse.path is not set by default anymore. When it is not set, the includePath will be used instead.
if (isUnset(settings.defaultDefines)) {
configuration.defines = (process.platform === 'win32') ? ["_DEBUG", "UNICODE", "_UNICODE"] : [];
}
if (isUnset(settings.defaultMacFrameworkPath) && process.platform === 'darwin') {
configuration.macFrameworkPath = this.defaultFrameworks;
}
if ((isUnset(settings.defaultWindowsSdkVersion) || settings.defaultWindowsSdkVersion === "") && this.defaultWindowsSdkVersion && process.platform === 'win32') {
configuration.windowsSdkVersion = this.defaultWindowsSdkVersion;
}
if (isUnset(settings.defaultCompilerPath) && this.defaultCompilerPath &&
(isUnset(settings.defaultCompileCommands) || settings.defaultCompileCommands === "") && !configuration.compileCommands) {
// compile_commands.json already specifies a compiler. compilerPath overrides the compile_commands.json compiler so
// don't set a default when compileCommands is in use.
configuration.compilerPath = this.defaultCompilerPath;
}
if ((isUnset(settings.defaultCStandard) || settings.defaultCStandard === "") && this.defaultCStandard) {
configuration.cStandard = this.defaultCStandard;
}
if ((isUnset(settings.defaultCppStandard) || settings.defaultCppStandard === "") && this.defaultCppStandard) {
configuration.cppStandard = this.defaultCppStandard;
}
if (isUnset(settings.defaultIntelliSenseMode) || settings.defaultIntelliSenseMode === "") {
configuration.intelliSenseMode = this.defaultIntelliSenseMode;
}
if (isUnset(settings.defaultCustomConfigurationVariables) || settings.defaultCustomConfigurationVariables === {}) {
configuration.customConfigurationVariables = this.defaultCustomConfigurationVariables;
}
}
private get ExtendedEnvironment(): Environment {
const result: Environment = {};
if (this.configurationJson?.env) {
Object.assign(result, this.configurationJson.env);
}
result["workspaceFolderBasename"] = this.rootUri ? path.basename(this.rootUri.fsPath) : "";
return result;
}
private async buildVcpkgIncludePath(): Promise<void> {
try {
// Check for vcpkgRoot and include relevent paths if found.
const vcpkgRoot: string = util.getVcpkgRoot();
if (vcpkgRoot) {
const list: string[] = await util.readDir(vcpkgRoot);
if (list !== undefined) {
// For every *directory* in the list (non-recursive). Each directory is basically a platform.
list.forEach((entry) => {
if (entry !== "vcpkg") {
const pathToCheck: string = path.join(vcpkgRoot, entry);
if (fs.existsSync(pathToCheck)) {
let p: string = path.join(pathToCheck, "include");
if (fs.existsSync(p)) {
p = p.replace(/\\/g, "/");
p = p.replace(vcpkgRoot, "${vcpkgRoot}");
this.vcpkgIncludes.push(p);
}
}
}
});
}
}
} catch (error) {} finally {
this.vcpkgPathReady = true;
this.handleConfigurationChange();
}
}
private getConfigIndexForPlatform(config: any): number | undefined {
if (!this.configurationJson) {
return undefined;
}
let plat: string;
if (process.platform === 'darwin') {
plat = "Mac";
} else if (process.platform === 'win32') {
plat = "Win32";
} else {
plat = "Linux";
}
for (let i: number = 0; i < this.configurationJson.configurations.length; i++) {
if (config.configurations[i].name === plat) {
return i;
}
}
return this.configurationJson.configurations.length - 1;
}
private getIntelliSenseModeForPlatform(name?: string): string {
// Do the built-in configs first.
if (name === "Linux") {
return "gcc-x64";
} else if (name === "Mac") {
return "clang-x64";
} else if (name === "Win32") {
return "msvc-x64";
} else if (process.platform === 'win32') {
// Custom configs default to the OS's preference.
return "msvc-x64";
} else if (process.platform === 'darwin') {
return "clang-x64";
} else {
return "gcc-x64";
}
}
private validateIntelliSenseMode(configuration: Configuration): string {
// Validate whether IntelliSenseMode is compatible with compiler.
// Do not validate if compiler path is not set or intelliSenseMode is not set.
if (configuration.compilerPath === undefined ||
configuration.compilerPath === "" ||
configuration.compilerPath === "${default}" ||
configuration.intelliSenseMode === undefined ||
configuration.intelliSenseMode === "" ||
configuration.intelliSenseMode === "${default}") {
return "";
}
const resolvedCompilerPath: string = this.resolvePath(configuration.compilerPath, true);
const compilerPathAndArgs: util.CompilerPathAndArgs = util.extractCompilerPathAndArgs(resolvedCompilerPath);
// Valid compiler + IntelliSenseMode combinations:
// 1. compiler is cl/clang-cl and IntelliSenseMode is MSVC
// 2. compiler is not cl/clang-cl and IntelliSenseMode is not MSVC
const isValid: boolean = compilerPathAndArgs.compilerName.endsWith("cl.exe") === configuration.intelliSenseMode.startsWith("msvc");
if (isValid) {
return "";
} else {
return localize("incompatible.intellisense.mode", "IntelliSense mode {0} is incompatible with compiler path.", configuration.intelliSenseMode);
}
}
public addToIncludePathCommand(path: string): void {
this.handleConfigurationEditCommand(() => {
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
const config: Configuration | undefined = this.CurrentConfiguration;
if (config) {
telemetry.logLanguageServerEvent("addToIncludePath");
if (config.includePath === undefined) {
config.includePath = ["${default}"];
}
config.includePath.splice(config.includePath.length, 0, path);
this.writeToJson();
this.handleConfigurationChange();
}
}, () => {});
}
public updateCustomConfigurationProvider(providerId: string): Thenable<void> {
return new Promise<void>((resolve) => {
if (this.propertiesFile) {
this.handleConfigurationEditJSONCommand(() => {
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
const config: Configuration | undefined = this.CurrentConfiguration;
if (config) {
if (providerId) {
config.configurationProvider = providerId;
} else {
delete config.configurationProvider;
}
this.writeToJson();
this.handleConfigurationChange();
}
resolve();
}, () => {});
} else {
const settings: CppSettings = new CppSettings(this.rootUri);
if (providerId) {
settings.update("default.configurationProvider", providerId);
} else {
settings.update("default.configurationProvider", undefined); // delete the setting
}
const config: Configuration | undefined = this.CurrentConfiguration;
if (config) {
config.configurationProvider = providerId;
}
resolve();
}
});
}
public setCompileCommands(path: string): void {
this.handleConfigurationEditJSONCommand(() => {
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
const config: Configuration | undefined = this.CurrentConfiguration;
if (config) {
config.compileCommands = path;
this.writeToJson();
this.handleConfigurationChange();
}
}, () => {});
}
public select(index: number): Configuration | undefined {
if (this.configurationJson) {
if (index === this.configurationJson.configurations.length) {
this.handleConfigurationEditUICommand(() => {}, vscode.window.showTextDocument);
return;
}
if (index === this.configurationJson.configurations.length + 1) {
this.handleConfigurationEditJSONCommand(() => {}, vscode.window.showTextDocument);
return;
}
}
if (this.currentConfigurationIndex !== undefined) {
this.currentConfigurationIndex.Value = index;
}
this.onSelectionChanged();
}
private resolveDefaults(entries: string[], defaultValue?: string[]): string[] {
let result: string[] = [];
entries.forEach(entry => {
if (entry === "${default}") {
// package.json default values for string[] properties is null.
// If no default is set, return an empty array instead of an array with `null` in it.
if (defaultValue) {
result = result.concat(defaultValue);
}
} else {
result.push(entry);
}
});
return result;
}
private resolveDefaultsDictionary(entries: { [key: string]: string }, defaultValue: { [key: string]: string } | undefined, env: Environment): { [key: string]: string } {
const result: { [key: string]: string } = {};
for (const property in entries) {
if (property === "${default}") {
if (defaultValue) {
for (const defaultProperty in defaultValue) {
if (!(defaultProperty in entries)) {
result[defaultProperty] = util.resolveVariables(defaultValue[defaultProperty], env);
}
}
}
} else {
result[property] = util.resolveVariables(entries[property], env);
}
}
return result;
}
private resolveAndSplit(paths: string[] | undefined, defaultValue: string[] | undefined, env: Environment): string[] {
let result: string[] = [];
if (paths) {
paths = this.resolveDefaults(paths, defaultValue);
paths.forEach(entry => {
const entries: string[] = util.resolveVariables(entry, env).split(util.envDelimiter).filter(e => e);
result = result.concat(entries);
});
}
return result;
}
private updateConfigurationString(property: string | undefined | null, defaultValue: string | undefined | null, env: Environment, acceptBlank?: boolean): string | undefined {
if (property === null || property === undefined || property === "${default}") {
property = defaultValue;
}
if (property === null || property === undefined || (acceptBlank !== true && property === "")) {
return undefined;
}
return util.resolveVariables(property, env);
}
private updateConfigurationStringArray(property: string[] | undefined, defaultValue: string[] | undefined, env: Environment): string[] | undefined {
if (property) {
return this.resolveAndSplit(property, defaultValue, env);
}
if (!property && defaultValue) {
return this.resolveAndSplit(defaultValue, [], env);
}
return property;
}
private updateConfigurationStringOrBoolean(property: string | boolean | undefined | null, defaultValue: boolean | undefined | null, env: Environment): string | boolean | undefined {
if (!property || property === "${default}") {
property = defaultValue;
}
if (!property || property === "") {
return undefined;
}
if (typeof property === "boolean") {
return property;
}
return util.resolveVariables(property, env);
}
private updateConfigurationStringDictionary(property: { [key: string]: string } | undefined, defaultValue: { [key: string]: string } | undefined, env: Environment): { [key: string]: string } | undefined {
if (!property || property === {}) {
property = defaultValue;
}
if (!property || property === {}) {
return undefined;
}
return this.resolveDefaultsDictionary(property, defaultValue, env);
}
private updateServerOnFolderSettingsChange(): void {
if (!this.configurationJson) {
return;
}
const settings: CppSettings = new CppSettings(this.rootUri);
const env: Environment = this.ExtendedEnvironment;
for (let i: number = 0; i < this.configurationJson.configurations.length; i++) {
const configuration: Configuration = this.configurationJson.configurations[i];
configuration.includePath = this.updateConfigurationStringArray(configuration.includePath, settings.defaultIncludePath, env);
configuration.defines = this.updateConfigurationStringArray(configuration.defines, settings.defaultDefines, env);
configuration.macFrameworkPath = this.updateConfigurationStringArray(configuration.macFrameworkPath, settings.defaultMacFrameworkPath, env);
configuration.windowsSdkVersion = this.updateConfigurationString(configuration.windowsSdkVersion, settings.defaultWindowsSdkVersion, env);
configuration.forcedInclude = this.updateConfigurationStringArray(configuration.forcedInclude, settings.defaultForcedInclude, env);
configuration.compileCommands = this.updateConfigurationString(configuration.compileCommands, settings.defaultCompileCommands, env);
configuration.compilerArgs = this.updateConfigurationStringArray(configuration.compilerArgs, settings.defaultCompilerArgs, env);
configuration.cStandard = this.updateConfigurationString(configuration.cStandard, settings.defaultCStandard, env);
configuration.cppStandard = this.updateConfigurationString(configuration.cppStandard, settings.defaultCppStandard, env);
configuration.intelliSenseMode = this.updateConfigurationString(configuration.intelliSenseMode, settings.defaultIntelliSenseMode, env);
if (!configuration.compileCommands) {
// compile_commands.json already specifies a compiler. compilerPath overrides the compile_commands.json compiler so
// don't set a default when compileCommands is in use.
configuration.compilerPath = this.updateConfigurationString(configuration.compilerPath, settings.defaultCompilerPath, env, true);
if (configuration.compilerPath === undefined && !!this.defaultCompilerPath) {
configuration.compilerPath = this.defaultCompilerPath;
if (!configuration.cStandard && !!this.defaultCStandard) {
configuration.cStandard = this.defaultCStandard;
}
if (!configuration.cppStandard && !!this.defaultCppStandard) {
configuration.cppStandard = this.defaultCppStandard;
}
if (!configuration.intelliSenseMode && !!this.defaultIntelliSenseMode) {
configuration.intelliSenseMode = this.defaultIntelliSenseMode;
}
if (!configuration.windowsSdkVersion && !!this.defaultWindowsSdkVersion) {
configuration.windowsSdkVersion = this.defaultWindowsSdkVersion;
}
if (!configuration.includePath && !!this.defaultIncludes) {
configuration.includePath = this.defaultIncludes;
}
if (!configuration.macFrameworkPath && !!this.defaultFrameworks) {
configuration.macFrameworkPath = this.defaultFrameworks;
}
}
} else {
// However, if compileCommands are used and compilerPath is explicitly set, it's still necessary to resolve variables in it.
if (configuration.compilerPath === "${default}") {
configuration.compilerPath = settings.defaultCompilerPath;
}
if (configuration.compilerPath === null) {
configuration.compilerPath = undefined;
} else if (configuration.compilerPath !== undefined) {
configuration.compilerPath = util.resolveVariables(configuration.compilerPath, env);
}
}
if (configuration.compilerPath
&& configuration.compilerPath.length > 0
&& configuration.compilerPath[0] !== '/'
&& !fs.existsSync(configuration.compilerPath)) {
// If a compiler path is specified, and it doesn't resolve to a file,
// try looking for it in the current path.
try {
configuration.compilerPath = which.sync(configuration.compilerPath);
} catch {
}
}
configuration.customConfigurationVariables = this.updateConfigurationStringDictionary(configuration.customConfigurationVariables, settings.defaultCustomConfigurationVariables, env);
configuration.configurationProvider = this.updateConfigurationString(configuration.configurationProvider, settings.defaultConfigurationProvider, env);
if (!configuration.browse) {
configuration.browse = {};
}
if (!configuration.browse.path) {
if (settings.defaultBrowsePath) {
configuration.browse.path = settings.defaultBrowsePath;
} else if (configuration.includePath) {
// If the user doesn't set browse.path, copy the includePath over. Make sure ${workspaceFolder} is in there though...
configuration.browse.path = configuration.includePath.slice(0);
if (configuration.includePath.findIndex((value: string, index: number) =>
!!value.match(/^\$\{(workspaceRoot|workspaceFolder)\}(\\\*{0,2}|\/\*{0,2})?$/g)) === -1
) {
configuration.browse.path.push("${workspaceFolder}");
}
}
} else {
configuration.browse.path = this.updateConfigurationStringArray(configuration.browse.path, settings.defaultBrowsePath, env);
}
configuration.browse.limitSymbolsToIncludedHeaders = this.updateConfigurationStringOrBoolean(configuration.browse.limitSymbolsToIncludedHeaders, settings.defaultLimitSymbolsToIncludedHeaders, env);
configuration.browse.databaseFilename = this.updateConfigurationString(configuration.browse.databaseFilename, settings.defaultDatabaseFilename, env);
}
this.updateCompileCommandsFileWatchers();
if (!this.configurationIncomplete) {
this.onConfigurationsChanged();
}
}
private compileCommandsFileWatcherTimer?: NodeJS.Timer;
private compileCommandsFileWatcherFiles: Set<string> = new Set<string>();
// Dispose existing and loop through cpp and populate with each file (exists or not) as you go.
// paths are expected to have variables resolved already
public updateCompileCommandsFileWatchers(): void {
if (this.configurationJson) {
this.compileCommandFileWatchers.forEach((watcher: fs.FSWatcher) => watcher.close());
this.compileCommandFileWatchers = []; // reset it
const filePaths: Set<string> = new Set<string>();
this.configurationJson.configurations.forEach(c => {
if (c.compileCommands) {
const fileSystemCompileCommandsPath: string = this.resolvePath(c.compileCommands, os.platform() === "win32");
if (fs.existsSync(fileSystemCompileCommandsPath)) {
filePaths.add(fileSystemCompileCommandsPath);
}
}
});
try {
filePaths.forEach((path: string) => {
this.compileCommandFileWatchers.push(fs.watch(path, (event: string, filename: string) => {
// Wait 1 second after a change to allow time for the write to finish.
if (this.compileCommandsFileWatcherTimer) {
clearInterval(this.compileCommandsFileWatcherTimer);
}
this.compileCommandsFileWatcherFiles.add(path);
this.compileCommandsFileWatcherTimer = setTimeout(() => {
this.compileCommandsFileWatcherFiles.forEach((path: string) => {
this.onCompileCommandsChanged(path);
});
if (this.compileCommandsFileWatcherTimer) {
clearInterval(this.compileCommandsFileWatcherTimer);
}
this.compileCommandsFileWatcherFiles.clear();
this.compileCommandsFileWatcherTimer = undefined;
}, 1000);
}));
});
} catch (e) {
// The file watcher limit is hit.
// TODO: Check if the compile commands file has a higher timestamp during the interval timer.
}
}
}
// onBeforeOpen will be called after c_cpp_properties.json have been created (if it did not exist), but before the document is opened.
public handleConfigurationEditCommand(onBeforeOpen: (() => void) | undefined, showDocument: (document: vscode.TextDocument) => void): void {
const otherSettings: OtherSettings = new OtherSettings(this.rootUri);
if (otherSettings.settingsEditor === "ui") {
this.handleConfigurationEditUICommand(onBeforeOpen, showDocument);
} else {
this.handleConfigurationEditJSONCommand(onBeforeOpen, showDocument);
}
}
// onBeforeOpen will be called after c_cpp_properties.json have been created (if it did not exist), but before the document is opened.
public handleConfigurationEditJSONCommand(onBeforeOpen: (() => void) | undefined, showDocument: (document: vscode.TextDocument) => void): void {
this.ensurePropertiesFile().then(() => {
console.assert(this.propertiesFile);
if (onBeforeOpen) {
onBeforeOpen();
}
// Directly open the json file
if (this.propertiesFile) {
vscode.workspace.openTextDocument(this.propertiesFile).then((document: vscode.TextDocument) => {
if (showDocument) {
showDocument(document);
}
});
}
});
}
private ensureSettingsPanelInitlialized(): void {
if (this.settingsPanel === undefined) {
const settings: CppSettings = new CppSettings(this.rootUri);
this.settingsPanel = new SettingsPanel();
this.settingsPanel.setKnownCompilers(this.knownCompilers, settings.preferredPathSeparator);
this.settingsPanel.SettingsPanelActivated(() => this.onSettingsPanelActivated());
this.settingsPanel.ConfigValuesChanged(() => this.saveConfigurationUI());
this.settingsPanel.ConfigSelectionChanged(() => this.onConfigSelectionChanged());
this.settingsPanel.AddConfigRequested((e) => this.onAddConfigRequested(e));
this.disposables.push(this.settingsPanel);
}
}
// onBeforeOpen will be called after c_cpp_properties.json have been created (if it did not exist), but before the document is opened.
public handleConfigurationEditUICommand(onBeforeOpen: (() => void) | undefined, showDocument: (document: vscode.TextDocument) => void): void {
this.ensurePropertiesFile().then(() => {
if (this.propertiesFile) {
if (onBeforeOpen) {
onBeforeOpen();
}
if (this.parsePropertiesFile()) {
this.ensureSettingsPanelInitlialized();
if (this.settingsPanel) {
const configNames: string[] | undefined = this.ConfigurationNames;
if (configNames && this.configurationJson) {
// Use the active configuration as the default selected configuration to load on UI editor
this.settingsPanel.selectedConfigIndex = this.CurrentConfigurationIndex;
this.settingsPanel.createOrShow(configNames,
this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex],
this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex));
}
}
} else {
// Parse failed, open json file
vscode.workspace.openTextDocument(this.propertiesFile).then((document: vscode.TextDocument) => {
if (showDocument) {
showDocument(document);
}
});
}
}
});
}
private onSettingsPanelActivated(): void {
if (this.configurationJson) {
this.ensurePropertiesFile().then(() => {
if (this.propertiesFile) {
if (this.parsePropertiesFile()) {
const configNames: string[] | undefined = this.ConfigurationNames;
if (configNames && this.settingsPanel && this.configurationJson) {
// The settings UI became visible or active.
// Ensure settingsPanel has copy of latest current configuration
if (this.settingsPanel.selectedConfigIndex >= this.configurationJson.configurations.length) {
this.settingsPanel.selectedConfigIndex = this.CurrentConfigurationIndex;
}
this.settingsPanel.updateConfigUI(configNames,
this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex],
this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex));
} else {
// Parse failed, open json file
vscode.workspace.openTextDocument(this.propertiesFile);
}
}
}
});
}
}
private saveConfigurationUI(): void {
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
if (this.settingsPanel && this.configurationJson) {
const config: Configuration = this.settingsPanel.getLastValuesFromConfigUI();
this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex] = config;
this.settingsPanel.updateErrors(this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex));
this.writeToJson();
}
}
private onConfigSelectionChanged(): void {
const configNames: string[] | undefined = this.ConfigurationNames;
if (configNames && this.settingsPanel && this.configurationJson) {
this.settingsPanel.updateConfigUI(configNames,
this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex],
this.getErrorsForConfigUI(this.settingsPanel.selectedConfigIndex));
}
}
private onAddConfigRequested(configName: string): void {
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
// Create default config and add to list of configurations
const newConfig: Configuration = { name: configName };
this.applyDefaultConfigurationValues(newConfig);
const configNames: string[] | undefined = this.ConfigurationNames;
if (configNames && this.settingsPanel && this.configurationJson) {
this.configurationJson.configurations.push(newConfig);
// Update UI
this.settingsPanel.selectedConfigIndex = this.configurationJson.configurations.length - 1;
this.settingsPanel.updateConfigUI(configNames,
this.configurationJson.configurations[this.settingsPanel.selectedConfigIndex],
null);
// Save new config to file
this.writeToJson();
}
}
private handleConfigurationChange(): void {
if (this.propertiesFile === undefined) {
return; // Occurs when propertiesFile hasn't been checked yet.
}
this.configFileWatcherFallbackTime = new Date();
if (this.propertiesFile) {
this.parsePropertiesFile();
// parsePropertiesFile can fail, but it won't overwrite an existing configurationJson in the event of failure.
// this.configurationJson should only be undefined here if we have never successfully parsed the propertiesFile.
if (this.configurationJson) {
if (this.CurrentConfigurationIndex < 0 ||
this.CurrentConfigurationIndex >= this.configurationJson.configurations.length) {
// If the index is out of bounds (during initialization or due to removal of configs), fix it.
const index: number | undefined = this.getConfigIndexForPlatform(this.configurationJson);
if (this.currentConfigurationIndex !== undefined) {
if (!index) {
this.currentConfigurationIndex.setDefault();
} else {
this.currentConfigurationIndex.Value = index;
}
}
}
}
}
if (!this.configurationJson) {
this.resetToDefaultSettings(true); // I don't think there's a case where this will be hit anymore.
}
this.applyDefaultIncludePathsAndFrameworks();
this.updateServerOnFolderSettingsChange();
}
private async ensurePropertiesFile(): Promise<void> {
if (this.propertiesFile && fs.existsSync(this.propertiesFile.fsPath)) {
return;
} else {
try {
if (!fs.existsSync(this.configFolder)) {
fs.mkdirSync(this.configFolder);
}
const fullPathToFile: string = path.join(this.configFolder, "c_cpp_properties.json");
if (this.configurationJson) {
this.resetToDefaultSettings(true);
}
this.applyDefaultIncludePathsAndFrameworks();
const settings: CppSettings = new CppSettings(this.rootUri);
if (settings.defaultConfigurationProvider) {
if (this.configurationJson) {
this.configurationJson.configurations.forEach(config => {
config.configurationProvider = settings.defaultConfigurationProvider ? settings.defaultConfigurationProvider : undefined;
});
}
settings.update("default.configurationProvider", undefined); // delete the setting
}
await util.writeFileText(fullPathToFile, jsonc.stringify(this.configurationJson, null, 4));
this.propertiesFile = vscode.Uri.file(path.join(this.configFolder, "c_cpp_properties.json"));
} catch (err) {
const failedToCreate: string = localize("failed.to.create.config.folder", 'Failed to create "{0}"', this.configFolder);
vscode.window.showErrorMessage(`${failedToCreate}: ${err.message}`);
}
}
return;
}
private parsePropertiesFile(): boolean {
if (!this.propertiesFile) {
return false;
}
let success: boolean = true;
try {
const readResults: string = fs.readFileSync(this.propertiesFile.fsPath, 'utf8');
if (readResults === "") {
return false; // Repros randomly when the file is initially created. The parse will get called again after the file is written.
}
// Try to use the same configuration as before the change.
const newJson: ConfigurationJson = jsonc.parse(readResults);
if (!newJson || !newJson.configurations || newJson.configurations.length === 0) {
throw { message: localize("invalid.configuration.file", "Invalid configuration file. There must be at least one configuration present in the array.") };
}
if (!this.configurationIncomplete && this.configurationJson && this.configurationJson.configurations &&
this.CurrentConfigurationIndex >= 0 && this.CurrentConfigurationIndex < this.configurationJson.configurations.length) {
for (let i: number = 0; i < newJson.configurations.length; i++) {
if (newJson.configurations[i].name === this.configurationJson.configurations[this.CurrentConfigurationIndex].name) {
if (this.currentConfigurationIndex !== undefined) {
this.currentConfigurationIndex.Value = i;
}
break;
}
}
}
this.configurationJson = newJson;
if (this.CurrentConfigurationIndex < 0 || this.CurrentConfigurationIndex >= newJson.configurations.length) {
const index: number | undefined = this.getConfigIndexForPlatform(newJson);
if (this.currentConfigurationIndex !== undefined) {
if (index === undefined) {
this.currentConfigurationIndex.setDefault();
} else {
this.currentConfigurationIndex.Value = index;
}