forked from microsoft/vscode-cpptools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
configurations.ts
1979 lines (1806 loc) · 100 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 { CustomConfigurationProviderCollection, 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 { setTimeout } from 'timers';
import * as which from 'which';
import { WorkspaceBrowseConfiguration } from 'vscode-cpptools';
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;
compilerPathIsExplicit?: boolean;
compilerArgs?: string[];
cStandard?: string;
cStandardIsExplicit?: boolean;
cppStandard?: string;
cppStandardIsExplicit?: boolean;
includePath?: string[];
macFrameworkPath?: string[];
windowsSdkVersion?: string;
defines?: string[];
intelliSenseMode?: string;
intelliSenseModeIsExplicit?: boolean;
compileCommands?: string;
forcedInclude?: string[];
configurationProvider?: string;
browse?: Browse;
customConfigurationVariables?: {[key: string]: string};
}
export interface ConfigurationErrors {
name?: string;
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 compileCommandsFile: vscode.Uri | undefined | null = undefined;
private compileCommandsFileWatchers: fs.FSWatcher[] = [];
private compileCommandsFileWatcherFallbackTime: Date = new Date(); // Used when file watching fails.
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 nodeAddonIncludes: string[] = [];
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<CppProperties>();
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;
private lastCustomBrowseConfiguration: PersistentFolderState<WorkspaceBrowseConfiguration | undefined> | undefined;
private lastCustomBrowseConfigurationProviderId: PersistentFolderState<string | undefined> | undefined;
// 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.lastCustomBrowseConfiguration = new PersistentFolderState<WorkspaceBrowseConfiguration | undefined>("CPP.lastCustomBrowseConfiguration", undefined, workspaceFolder);
this.lastCustomBrowseConfigurationProviderId = new PersistentFolderState<string | undefined>("CPP.lastCustomBrowseConfigurationProviderId", undefined, workspaceFolder);
}
this.configFolder = path.join(rootPath, ".vscode");
this.diagnosticCollection = vscode.languages.createDiagnosticCollection(rootPath);
this.buildVcpkgIncludePath();
const userSettings: CppSettings = new CppSettings();
if (userSettings.addNodeAddonIncludePaths) {
this.readNodeAddonIncludeLocations(rootPath);
}
this.disposables.push(vscode.Disposable.from(this.configurationsChanged, this.selectionChanged, this.compileCommandsChanged));
}
public get ConfigurationsChanged(): vscode.Event<CppProperties> { 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 LastCustomBrowseConfiguration(): PersistentFolderState<WorkspaceBrowseConfiguration | undefined> | undefined { return this.lastCustomBrowseConfiguration; }
public get LastCustomBrowseConfigurationProviderId(): PersistentFolderState<string | undefined> | undefined { return this.lastCustomBrowseConfigurationProviderId; }
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();
}
});
vscode.workspace.onDidSaveTextDocument((doc: vscode.TextDocument) => {
// For multi-root, the "onDidSaveTextDocument" will be received once for each project folder.
// To avoid misleading telemetry (for CMake retention) skip if the notifying folder
// is not the same workspace folder of the modified document.
// Exception: if the document does not belong to any of the folders in this workspace,
// getWorkspaceFolder will return undefined and we report this as "outside".
// Even in this case make sure we send the telemetry information only once,
// not for each notifying folder.
const savedDocWorkspaceFolder: vscode.WorkspaceFolder | undefined = vscode.workspace.getWorkspaceFolder(doc.uri);
const notifyingWorkspaceFolder: vscode.WorkspaceFolder | undefined = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(settingsPath));
if ((!savedDocWorkspaceFolder && vscode.workspace.workspaceFolders && notifyingWorkspaceFolder === vscode.workspace.workspaceFolders[0])
|| savedDocWorkspaceFolder === notifyingWorkspaceFolder) {
let fileType: string | undefined;
const documentPath: string = doc.uri.fsPath.toLowerCase();
if (documentPath.endsWith("cmakelists.txt")) {
fileType = "CMakeLists";
} else if (documentPath.endsWith("cmakecache.txt")) {
fileType = "CMakeCache";
} else if (documentPath.endsWith(".cmake")) {
fileType = ".cmake";
}
if (fileType) {
// We consider the changed cmake file as outside if it is not found in any
// of the projects folders.
telemetry.logLanguageServerEvent("cmakeFileWrite",
{
filetype: fileType,
outside: (savedDocWorkspaceFolder === undefined).toString()
});
}
}
});
this.handleConfigurationChange();
}
public get VcpkgInstalled(): boolean {
return this.vcpkgIncludes.length > 0;
}
private onConfigurationsChanged(): void {
if (this.Configurations) {
this.configurationsChanged.fire(this);
}
}
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 rootFolder: string = "${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();
}
}
public nodeAddonIncludesFound(): number {
return this.nodeAddonIncludes.length;
}
private async readNodeAddonIncludeLocations(rootPath: string): Promise<void> {
let error: Error | undefined;
let pdjFound: boolean = false;
let packageJson: any;
try {
packageJson = JSON.parse(await fs.promises.readFile(path.join(rootPath, "package.json"), "utf8"));
pdjFound = true;
} catch (err) {
error = err;
}
if (!error) {
try {
const pathToNode: string = which.sync("node");
const nodeAddonMap: [string, string][] = [
["node-addon-api", `"${pathToNode}" --no-warnings -p "require('node-addon-api').include"`],
["nan", `"${pathToNode}" --no-warnings -e "require('nan')"`]
];
// Yarn (2) PnP support
const pathToYarn: string | null = which.sync("yarn", { nothrow: true });
if (pathToYarn && await util.checkDirectoryExists(path.join(rootPath, ".yarn/cache"))) {
nodeAddonMap.push(
["node-addon-api", `"${pathToYarn}" node --no-warnings -p "require('node-addon-api').include"`],
["nan", `"${pathToYarn}" node --no-warnings -e "require('nan')"`]
);
}
for (const [dep, execCmd] of nodeAddonMap) {
if (dep in packageJson.dependencies) {
try {
let stdout: string | void = await util.execChildProcess(execCmd, rootPath);
if (!stdout) {
continue;
}
// cleanup newlines
if (stdout[stdout.length - 1] === "\n") {
stdout = stdout.slice(0, -1);
}
// node-addon-api returns a quoted string, e.g., '"/home/user/dir/node_modules/node-addon-api"'.
if (stdout[0] === "\"" && stdout[stdout.length - 1] === "\"") {
stdout = stdout.slice(1, -1);
}
// at this time both node-addon-api and nan return their own directory so this test is not really
// needed. but it does future proof the code.
if (!await util.checkDirectoryExists(stdout)) {
// nan returns a path relative to rootPath causing the previous check to fail because this code
// is executing in vscode's working directory.
stdout = path.join(rootPath, stdout);
if (!await util.checkDirectoryExists(stdout)) {
error = new Error(`${dep} directory ${stdout} doesn't exist`);
stdout = '';
}
}
if (stdout) {
this.nodeAddonIncludes.push(stdout);
}
} catch (err) {
console.log('readNodeAddonIncludeLocations', err.message);
}
}
}
} catch (e) {
error = e;
}
}
if (error) {
if (pdjFound) {
// only log an error if package.json exists.
console.log('readNodeAddonIncludeLocations', error.message);
}
} else {
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 "linux-gcc-x64";
} else if (name === "Mac") {
return "macos-clang-x64";
} else if (name === "Win32") {
return "windows-msvc-x64";
} else if (process.platform === 'win32') {
// Custom configs default to the OS's preference.
return "windows-msvc-x64";
} else if (process.platform === 'darwin') {
return "macos-clang-x64";
} else {
return "linux-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);
const isValid: boolean = ((compilerPathAndArgs.compilerName.toLowerCase() === "cl.exe" || compilerPathAndArgs.compilerName.toLowerCase() === "cl") === configuration.intelliSenseMode.includes("msvc")
// We can't necessarily determine what host compiler nvcc will use, without parsing command line args (i.e. for -ccbin)
// to determine if the user has set it to something other than the default. So, we don't squiggle IntelliSenseMode when using nvcc.
|| (compilerPathAndArgs.compilerName.toLowerCase() === "nvcc.exe") || (compilerPathAndArgs.compilerName.toLowerCase() === "nvcc"));
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 userSettings: CppSettings = new CppSettings();
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);
// in case includePath is reset below
const origIncludePath: string[] | undefined = configuration.includePath;
if (userSettings.addNodeAddonIncludePaths) {
const includePath: string[] = origIncludePath || [];
configuration.includePath = includePath.concat(this.nodeAddonIncludes.filter(i => includePath.indexOf(i) < 0));
}
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);
configuration.intelliSenseModeIsExplicit = configuration.intelliSenseModeIsExplicit || settings.defaultIntelliSenseMode !== "";
configuration.cStandardIsExplicit = configuration.cStandardIsExplicit || settings.defaultCStandard !== "";
configuration.cppStandardIsExplicit = configuration.cppStandardIsExplicit || settings.defaultCppStandard !== "";
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);
configuration.compilerPathIsExplicit = configuration.compilerPathIsExplicit || settings.defaultCompilerPath !== undefined;
if (configuration.compilerPath === undefined) {
if (!!this.defaultCompilerPath) {
// If no config value yet set for these, pick up values from the defaults, but don't consider them explicit.
configuration.compilerPath = this.defaultCompilerPath;
if (!configuration.cStandard && !!this.defaultCStandard) {
configuration.cStandard = this.defaultCStandard;
configuration.cStandardIsExplicit = false;
}
if (!configuration.cppStandard && !!this.defaultCppStandard) {
configuration.cppStandard = this.defaultCppStandard;
configuration.cppStandardIsExplicit = false;
}
if (!configuration.intelliSenseMode && !!this.defaultIntelliSenseMode) {
configuration.intelliSenseMode = this.defaultIntelliSenseMode;
configuration.intelliSenseModeIsExplicit = false;
}
if (!configuration.windowsSdkVersion && !!this.defaultWindowsSdkVersion) {
configuration.windowsSdkVersion = this.defaultWindowsSdkVersion;
}
if (!origIncludePath && !!this.defaultIncludes) {
const includePath: string[] = configuration.includePath || [];
configuration.includePath = includePath.concat(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;
configuration.compilerPathIsExplicit = true;
} else if (configuration.compilerPath !== undefined) {
configuration.compilerPath = util.resolveVariables(configuration.compilerPath, env);
configuration.compilerPathIsExplicit = true;
} else {
configuration.compilerPathIsExplicit = false;
}
}
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);
if (i === this.CurrentConfigurationIndex) {
// If there is no c_cpp_properties.json, there are no relevant C_Cpp.default.* settings set,
// and there is only 1 registered custom config provider, default to using that provider.
const providers: CustomConfigurationProviderCollection = getCustomConfigProviders();
const hasEmptyConfiguration: boolean = !this.propertiesFile
&& !settings.defaultCompilerPath
&& settings.defaultCompilerPath !== ""
&& !settings.defaultIncludePath
&& !settings.defaultDefines
&& !settings.defaultMacFrameworkPath
&& settings.defaultWindowsSdkVersion === ""
&& !settings.defaultForcedInclude
&& settings.defaultCompileCommands === ""
&& !settings.defaultCompilerArgs
&& settings.defaultCStandard === ""
&& settings.defaultCppStandard === ""
&& settings.defaultIntelliSenseMode === ""
&& settings.defaultConfigurationProvider === "";
// Only keep a cached custom browse config if there is an empty configuration,
// or if a specified provider ID has not changed.
let keepCachedBrowseConfig: boolean = true;
if (hasEmptyConfiguration) {
if (providers.size === 1) {
providers.forEach(provider => { configuration.configurationProvider = provider.extensionId; });
if (this.lastCustomBrowseConfigurationProviderId !== undefined) {
keepCachedBrowseConfig = configuration.configurationProvider === this.lastCustomBrowseConfigurationProviderId.Value;
}
} else if (this.lastCustomBrowseConfigurationProviderId !== undefined
&& !!this.lastCustomBrowseConfigurationProviderId.Value) {
// Use the last configuration provider we received a browse config from as the provider ID.
configuration.configurationProvider = this.lastCustomBrowseConfigurationProviderId.Value;
}
} else if (this.lastCustomBrowseConfigurationProviderId !== undefined) {
keepCachedBrowseConfig = configuration.configurationProvider === this.lastCustomBrowseConfigurationProviderId.Value;
}
if (!keepCachedBrowseConfig && this.lastCustomBrowseConfiguration !== undefined) {
this.lastCustomBrowseConfiguration.Value = undefined;
}
}
}
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.compileCommandsFileWatchers.forEach((watcher: fs.FSWatcher) => watcher.close());
this.compileCommandsFileWatchers = []; // 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.compileCommandsFileWatchers.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, column?: vscode.ViewColumn) => void, viewColumn?: vscode.ViewColumn): void {
const otherSettings: OtherSettings = new OtherSettings(this.rootUri);
if (otherSettings.settingsEditor === "ui") {
this.handleConfigurationEditUICommand(onBeforeOpen, showDocument, viewColumn);
} else {
this.handleConfigurationEditJSONCommand(onBeforeOpen, showDocument, viewColumn);
}
}
// onBeforeOpen will be called after c_cpp_properties.json have been created (if it did not exist), but before the document is opened.
public async handleConfigurationEditJSONCommand(onBeforeOpen: (() => void) | undefined, showDocument: (document: vscode.TextDocument, column?: vscode.ViewColumn) => void, viewColumn?: vscode.ViewColumn): Promise<void> {
await this.ensurePropertiesFile();
console.assert(this.propertiesFile);
if (onBeforeOpen) {
onBeforeOpen();
}
// Directly open the json file
if (this.propertiesFile) {
const document: vscode.TextDocument = await vscode.workspace.openTextDocument(this.propertiesFile);
if (showDocument) {
showDocument(document, viewColumn);
}
}
}
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(() => {
if (this.settingsPanel?.initialized) {
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 async handleConfigurationEditUICommand(onBeforeOpen: (() => void) | undefined, showDocument: (document: vscode.TextDocument, column?: vscode.ViewColumn) => void, viewColumn?: vscode.ViewColumn): Promise<void> {
await this.ensurePropertiesFile();
if (this.propertiesFile) {
if (onBeforeOpen) {
onBeforeOpen();
}
if (this.parsePropertiesFile()) {
this.ensureSettingsPanelInitlialized();
if (this.settingsPanel) {
const configNames: string[] | undefined = this.ConfigurationNames;
if (configNames && this.configurationJson) {