-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
configurations.ts
2361 lines (2151 loc) · 118 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 jsonc from 'comment-json';
import * as fastGlob from 'fast-glob';
import * as fs from "fs";
import * as os from 'os';
import * as path from 'path';
import { setTimeout } from 'timers';
import * as vscode from 'vscode';
import * as nls from 'vscode-nls';
import * as which from 'which';
import { logAndReturn, returns } from '../Utility/Async/returns';
import * as util from '../common';
import { isWindows } from '../constants';
import { getOutputChannelLogger } from '../logger';
import * as telemetry from '../telemetry';
import { DefaultClient } from './client';
import { CustomConfigurationProviderCollection, getCustomConfigProviders } from './customProviders';
import { PersistentFolderState } from './persistentState';
import { CppSettings, OtherSettings } from './settings';
import { SettingsPanel } from './settingsPanel';
import { ConfigurationType, getUI } from './ui';
import escapeStringRegExp = require('escape-string-regexp');
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;
compilerPathInCppPropertiesJson?: string | null;
compilerPath?: string | null;
compilerPathIsExplicit?: boolean;
compilerArgs?: string[];
compilerArgsLegacy?: string[];
cStandard?: string;
cStandardIsExplicit?: boolean;
cppStandard?: string;
cppStandardIsExplicit?: boolean;
includePath?: string[];
macFrameworkPath?: string[];
windowsSdkVersion?: string;
dotConfig?: string;
defines?: string[];
intelliSenseMode?: string;
intelliSenseModeIsExplicit?: boolean;
compileCommandsInCppPropertiesJson?: string;
compileCommands?: string;
forcedInclude?: string[];
configurationProviderInCppPropertiesJson?: string;
configurationProvider?: string;
mergeConfigurations?: boolean;
browse?: Browse;
customConfigurationVariables?: { [key: string]: string };
}
export interface ConfigurationErrors {
name?: string;
compilerPath?: string;
includePath?: string;
intelliSenseMode?: string;
macFrameworkPath?: string;
forcedInclude?: string;
compileCommands?: string;
dotConfig?: string;
browsePath?: string;
databaseFilename?: string;
}
export interface Browse {
path?: string[];
limitSymbolsToIncludedHeaders?: boolean | string;
databaseFilename?: string;
}
export interface KnownCompiler {
path: string;
isC: boolean;
isTrusted: boolean; // May be used in the future for build tasks.
isCL: boolean;
}
export interface CompilerDefaults {
compilerPath: string;
compilerArgs: string[];
knownCompilers: KnownCompiler[];
cStandard: string;
cppStandard: string;
includes: string[];
frameworks: string[];
windowsSdkVersion: string;
intelliSenseMode: string;
trustedCompilerFound: boolean;
}
export class CppProperties {
private client: DefaultClient;
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: Map<string, Date> = new Map<string, 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 isCppPropertiesJsonVisible: boolean = false;
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 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;
trustedCompilerFound: boolean = false;
constructor(client: DefaultClient, rootUri?: vscode.Uri, workspaceFolder?: vscode.WorkspaceFolder) {
this.client = client;
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);
void this.buildVcpkgIncludePath();
const userSettings: CppSettings = new CppSettings();
if (userSettings.addNodeAddonIncludePaths) {
void 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 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 setupConfigurations(): void {
// 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(() => {
this.handleConfigurationChange();
});
vscode.workspace.onDidChangeTextDocument((e) => {
if (e.document.uri.fsPath === settingsPath && this.isCppPropertiesJsonVisible) {
void this.handleSquiggles().catch(logAndReturn.undefined);
}
});
vscode.window.onDidChangeVisibleTextEditors((editors) => {
const wasVisible: boolean = this.isCppPropertiesJsonVisible;
editors.forEach(editor => {
if (editor.document.uri.fsPath === settingsPath) {
this.isCppPropertiesJsonVisible = true;
if (!wasVisible) {
void this.handleSquiggles().catch(logAndReturn.undefined);
}
}
});
});
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 && vscode.workspace.workspaceFolders.length > 0 && 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()
});
}
}
});
}
public set CompilerDefaults(compilerDefaults: CompilerDefaults) {
this.defaultCompilerPath = compilerDefaults.trustedCompilerFound ? compilerDefaults.compilerPath : null;
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 !== "" ? compilerDefaults.intelliSenseMode : undefined;
this.trustedCompilerFound = compilerDefaults.trustedCompilerFound;
}
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);
void this.handleSquiggles().catch(logAndReturn.undefined);
}
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 async applyDefaultIncludePathsAndFrameworks() {
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.
// if the compiler is a cl.exe compiler, replace the full path with the "cl.exe" string.
const compiler: string = path.basename(this.defaultCompilerPath).toLowerCase();
if (compiler === "cl.exe") {
configuration.compilerPath = "cl.exe";
} else {
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 (!settings.defaultCustomConfigurationVariables || Object.keys(settings.defaultCustomConfigurationVariables).length === 0) {
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) : "";
result["execPath"] = process.execPath;
result["pathSeparator"] = (os.platform() === 'win32') ? "\\" : "/";
result["/"] = (os.platform() === 'win32') ? "\\" : "/";
result["userHome"] = os.homedir();
if (util.getVcpkgRoot()) {
result["vcpkgRoot"] = util.getVcpkgRoot();
}
return result;
}
private async buildVcpkgIncludePath(): Promise<void> {
try {
// Check for vcpkgRoot and include relevant 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) { /*ignore*/ } 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 (errJS) {
const err: Error = errJS as Error;
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 = 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 (errJS) {
const err: Error = errJS as Error;
console.log('readNodeAddonIncludeLocations', err.message);
}
}
}
} catch (errJS) {
const e: Error = errJS as Error;
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, false, false);
const settings: CppSettings = new CppSettings(this.rootUri);
const compilerPathAndArgs: util.CompilerPathAndArgs = util.extractCompilerPathAndArgs(!!settings.legacyCompilerArgsBehavior, 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 {
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();
}
// Any time parsePropertiesFile is called, configurationJson gets
// reverted to an unprocessed state and needs to be reprocessed.
this.handleConfigurationChange();
}, () => { }).catch(logAndReturn.undefined);
}
public async updateCompilerPathIfSet(path: string): Promise<void> {
if (!this.propertiesFile) {
// Properties file does not exist.
return;
}
return this.handleConfigurationEditJSONCommand(() => {
this.parsePropertiesFile(); // Clear out any modifications we may have made internally.
const config: Configuration | undefined = this.CurrentConfiguration;
// Update compiler path if it's already set.
if (config && config.compilerPath !== undefined) {
config.compilerPath = path;
this.writeToJson();
}
// Any time parsePropertiesFile is called, configurationJson gets
// reverted to an unprocessed state and needs to be reprocessed.
this.handleConfigurationChange();
}, returns.undefined);
}
public async updateCustomConfigurationProvider(providerId: string): Promise<void> {
if (!this.propertiesFile) {
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;
}
return;
}
return 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();
}
// Any time parsePropertiesFile is called, configurationJson gets
// reverted to an unprocessed state and needs to be reprocessed.
this.handleConfigurationChange();
}, returns.undefined);
}
public setCompileCommands(path: string): Promise<void> {
return 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();
}
// Any time parsePropertiesFile is called, configurationJson gets
// reverted to an unprocessed state and needs to be reprocessed.
this.handleConfigurationChange();
}, returns.undefined);
}
public select(index: number): Configuration | undefined {
if (this.configurationJson) {
if (index === this.configurationJson.configurations.length) {
void this.handleConfigurationEditUICommand(() => { }, vscode.window.showTextDocument).catch(logAndReturn.undefined);
return;
}
if (index === this.configurationJson.configurations.length + 1) {
void this.handleConfigurationEditJSONCommand(() => { }, vscode.window.showTextDocument).catch(logAndReturn.undefined);
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 resolve(entries: string[] | undefined, defaultValue: string[] | undefined, env: Environment): string[] {
let result: string[] = [];
if (entries) {
entries = this.resolveDefaults(entries, defaultValue);
entries.forEach(entry => {
const entriesResolved: string[] = [];
const entryResolved: string = util.resolveVariables(entry, env, entriesResolved);
result = result.concat(entriesResolved.length === 0 ? entryResolved : entriesResolved);
});
}
return result;
}
private resolveAndSplit(paths: string[] | undefined, defaultValue: string[] | undefined, env: Environment, assumeRelative: boolean = true, glob: boolean = false): string[] {
const resolvedVariables: string[] = [];
if (paths === undefined) {
return resolvedVariables;
}
paths = this.resolveDefaults(paths, defaultValue);
paths.forEach(entry => {
const resolvedVariable: string = util.resolveVariables(entry, env);
if (resolvedVariable.includes("env:")) {
// Do not futher try to resolve a "${env:VAR}"
resolvedVariables.push(resolvedVariable);
} else {
const entries: string[] = resolvedVariable.split(path.delimiter).map(e => glob ? this.resolvePath(e, false, assumeRelative) : e).filter(e => e);
resolvedVariables.push(...entries);
}
});
if (!glob) {
return resolvedVariables;
}
const resolvedGlob: string[] = [];
for (let res of resolvedVariables) {
let counter: number = 0;
let slashFound: boolean = false;
const lastIndex: number = res.length - 1;
// Detect all wildcard variations by looking at last character in the path first.
for (let i: number = lastIndex; i >= 0; i--) {
if (res[i] === '*') {
counter++;
} else if (res[i] === '/' || (isWindows && res[i] === '\\')) {
counter++;
slashFound = true;
break;
} else {
break;
}
}
let suffix: string = '';
if (slashFound) {
suffix = res.slice(res.length - counter);
res = res.slice(0, res.length - counter);
}
let normalized = res;
let cwd: string = this.rootUri?.fsPath ?? '';
if (isWindows) {
normalized = res.replace(/\\/g, '/');
cwd = cwd.replace(/\\/g, '/');
}
const isGlobPattern: boolean = normalized.includes('*');
if (isGlobPattern) {
// fastGlob silently strips non-found paths. Limit that behavior to dynamic paths only.
const matches: string[] = fastGlob.isDynamicPattern(normalized) ?
fastGlob.sync(normalized, { onlyDirectories: true, cwd, suppressErrors: true, deep: 15 }) : [res];
resolvedGlob.push(...matches.map(s => s + suffix));
if (resolvedGlob.length === 0) {
resolvedGlob.push(normalized);
}
} else {
resolvedGlob.push(normalized + suffix);
}
}
return resolvedGlob;
}
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.resolve(property, defaultValue, env);
}
if (!property && defaultValue) {
return this.resolve(defaultValue, [], env);
}
return property;
}
private updateConfigurationPathsArray(paths: string[] | undefined, defaultValue: string[] | undefined, env: Environment, assumeRelative: boolean = true): string[] | undefined {
if (paths) {
return this.resolveAndSplit(paths, defaultValue, env, assumeRelative, true);
}
if (!paths && defaultValue) {
return this.resolveAndSplit(defaultValue, [], env, assumeRelative, true);
}
return paths;
}
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 updateConfigurationBoolean(property: boolean | undefined | null, defaultValue: boolean | undefined | null): boolean | undefined {
if (property === null || property === undefined) {
property = defaultValue;
}
if (property === null) {
return undefined;
}
return property;
}
private updateConfigurationStringDictionary(property: { [key: string]: string } | undefined, defaultValue: { [key: string]: string } | undefined, env: Environment): { [key: string]: string } | undefined {
if (!property || Object.keys(property).length === 0) {
property = defaultValue;
}
if (!property || Object.keys(property).length === 0) {
return undefined;
}
return this.resolveDefaultsDictionary(property, defaultValue, env);
}
private getDotconfigDefines(dotConfigPath: string): string[] {
if (dotConfigPath !== undefined) {
const path: string = this.resolvePath(dotConfigPath);
try {
const configContent: string[] = fs.readFileSync(path, "utf-8").split("\n");
return configContent.filter(i => !i.startsWith("#") && i !== "");
} catch (errJS) {
const err: Error = errJS as Error;
getOutputChannelLogger().appendLine(`Invalid input, cannot resolve .config path: ${err.message}`);
}
}
return [];
}
private configProviderAutoSelected: boolean = false;
public get ConfigProviderAutoSelected(): boolean {
return this.configProviderAutoSelected;
}
private updateServerOnFolderSettingsChange(): void {
this.configProviderAutoSelected = false;
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.compilerPathInCppPropertiesJson = configuration.compilerPath;
configuration.compileCommandsInCppPropertiesJson = configuration.compileCommands;
configuration.configurationProviderInCppPropertiesJson = configuration.configurationProvider;
configuration.includePath = this.updateConfigurationPathsArray(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);
// in case we have dotConfig
configuration.dotConfig = this.updateConfigurationString(configuration.dotConfig, settings.defaultDotconfig, env);
if (configuration.dotConfig !== undefined) {
configuration.defines = configuration.defines || [];
configuration.defines = configuration.defines.concat(this.getDotconfigDefines(configuration.dotConfig));
}
configuration.macFrameworkPath = this.updateConfigurationStringArray(configuration.macFrameworkPath, settings.defaultMacFrameworkPath, env);
configuration.windowsSdkVersion = this.updateConfigurationString(configuration.windowsSdkVersion, settings.defaultWindowsSdkVersion, env);
configuration.forcedInclude = this.updateConfigurationPathsArray(configuration.forcedInclude, settings.defaultForcedInclude, env, false);
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 !== "";
configuration.mergeConfigurations = this.updateConfigurationBoolean(configuration.mergeConfigurations, settings.defaultMergeConfigurations);
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 !== null;
if (configuration.compilerPath === undefined) {
if (!!this.defaultCompilerPath && this.trustedCompilerFound) {
// 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 {
// add compiler to list of trusted compilers
if (i === this.CurrentConfigurationIndex) {
void this.client.addTrustedCompiler(configuration.compilerPath).catch(logAndReturn.undefined);
}
}
} 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.compilerPathIsExplicit = true;
} else if (configuration.compilerPath !== undefined) {
configuration.compilerPath = util.resolveVariables(configuration.compilerPath, env);
configuration.compilerPathIsExplicit = true;
} else {
configuration.compilerPathIsExplicit = false;
}