From 9d0af580eff5f7120ffb88deaad93feb1d78bf21 Mon Sep 17 00:00:00 2001 From: soroshsabz Date: Wed, 2 Dec 2026 08:56:02 +0330 Subject: [PATCH 1/2] Add C_Cpp.intelliSenseModuleSearchPath for module import IntelliSense --- Extension/package.json | 6 + Extension/package.nls.json | 2 + Extension/src/LanguageServer/client.ts | 15 +- .../src/LanguageServer/moduleSearchPath.ts | 55 ++++++++ Extension/src/LanguageServer/settings.ts | 1 + .../assets/moduleFiles/geometry.eifc | Bin 0 -> 944 bytes .../assets/moduleFiles/math.eifc | Bin 0 -> 1124 bytes .../tests/modules.integration.test.ts | 131 +++++++++++++++--- Extension/test/unit/moduleSearchPath.test.ts | 43 ++++++ 9 files changed, 233 insertions(+), 20 deletions(-) create mode 100644 Extension/src/LanguageServer/moduleSearchPath.ts create mode 100644 Extension/test/scenarios/CppModulesProject/assets/moduleFiles/geometry.eifc create mode 100644 Extension/test/scenarios/CppModulesProject/assets/moduleFiles/math.eifc create mode 100644 Extension/test/unit/moduleSearchPath.test.ts diff --git a/Extension/package.json b/Extension/package.json index ab1d9ee16..ad170871f 100644 --- a/Extension/package.json +++ b/Extension/package.json @@ -993,6 +993,12 @@ "minimum": 500, "maximum": 3000 }, + "C_Cpp.intelliSenseModuleSearchPath": { + "type": "string", + "description": "%c_cpp.configuration.intelliSenseModuleSearchPath.description%", + "scope": "resource", + "markdownDescription": "%c_cpp.configuration.intelliSenseModuleSearchPath.markdownDescription%" + }, "C_Cpp.codeFolding": { "type": "string", "enum": [ diff --git a/Extension/package.nls.json b/Extension/package.nls.json index fa9fa84e8..025e568ef 100644 --- a/Extension/package.nls.json +++ b/Extension/package.nls.json @@ -623,6 +623,8 @@ ] }, "c_cpp.configuration.intelliSenseUpdateDelay.description": "Controls the delay in milliseconds before IntelliSense starts updating after a modification.", + "c_cpp.configuration.intelliSenseModuleSearchPath.description": "Directory searched for compiled module interface files when IntelliSense resolves import directives.", + "c_cpp.configuration.intelliSenseModuleSearchPath.markdownDescription": "Directory searched by IntelliSense for compiled module interface files when resolving `import` directives. Module files in this directory are found in every IntelliSense mode, including gcc and clang modes whose module files cannot be produced by the project's own toolchain. The `${workspaceFolder}` variable is supported. The value is passed to the IntelliSense engine at startup, so changing it requires reloading the window. See issue [#6302](https://github.com/microsoft/vscode-cpptools/issues/6302) for the module IntelliSense status.", "c_cpp.configuration.default.includePath.markdownDescription": { "message": "The value to use in a configuration if `includePath` is not specified in `c_cpp_properties.json`. If `includePath` is specified, add `${default}` to the array to insert the values from this setting. Usually, this should not include system includes; instead, set `#C_Cpp.default.compilerPath#`.", "comment": [ diff --git a/Extension/src/LanguageServer/client.ts b/Extension/src/LanguageServer/client.ts index b370188f7..b5ad7f311 100644 --- a/Extension/src/LanguageServer/client.ts +++ b/Extension/src/LanguageServer/client.ts @@ -58,6 +58,7 @@ import { CppSourceStr, clients, configPrefix, initializeIntervalTimer, isWriting import { IncludeCleanupPreferences, getIncludeCleanupPreferences } from './includeCleanupEditorConfig'; import { InactiveRegion, InactiveRegionStore, getInactiveRegionStartLines } from './inactiveRegions'; import { LanguageClient } from './languageClient'; +import { getModuleSearchPathServerEnv } from './moduleSearchPath'; import { LocalizeStringParams, getLocaleId, getLocalizedString } from './localization'; import { PersistentFolderState, PersistentState, PersistentWorkspaceState } from './persistentState'; import { RequestCancelled, ServerCancelled, createProtocolFilter } from './protocolFilter'; @@ -1654,9 +1655,19 @@ export class DefaultClient implements Client { // from a sanitizer build to files in that directory (see getSanitizerServerEnv). This is // undefined -- i.e. the environment is inherited unchanged -- for normal builds. const sanitizerServerEnv: NodeJS.ProcessEnv | undefined = getSanitizerServerEnv(); + // Set the module interface file search directory for the IntelliSense engine from the + // "C_Cpp.intelliSenseModuleSearchPath" setting (see moduleSearchPath.ts). Also inherited + // when unset. The value is only read at language server startup, so setting changes + // require reloading the window. + const moduleSearchPathEnv: NodeJS.ProcessEnv | undefined = + getModuleSearchPathServerEnv(new CppSettings(this.RootUri).intelliSenseModuleSearchPath, this.RootPath); + let serverEnv: NodeJS.ProcessEnv | undefined; + if (sanitizerServerEnv || moduleSearchPathEnv) { + serverEnv = { ...process.env, ...sanitizerServerEnv, ...moduleSearchPathEnv }; + } const serverOptions: rpc.ServerOptions = { - run: { command: serverModule, options: { detached: false, cwd: util.getExtensionFilePath("bin"), env: sanitizerServerEnv } }, - debug: { command: serverModule, args: [serverName], options: { detached: true, cwd: util.getExtensionFilePath("bin"), env: sanitizerServerEnv } } + run: { command: serverModule, options: { detached: false, cwd: util.getExtensionFilePath("bin"), env: serverEnv } }, + debug: { command: serverModule, args: [serverName], options: { detached: true, cwd: util.getExtensionFilePath("bin"), env: serverEnv } } }; // The IntelliSense process should automatically detect when AutoPCH is diff --git a/Extension/src/LanguageServer/moduleSearchPath.ts b/Extension/src/LanguageServer/moduleSearchPath.ts new file mode 100644 index 000000000..cd9d583f7 --- /dev/null +++ b/Extension/src/LanguageServer/moduleSearchPath.ts @@ -0,0 +1,55 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All Rights Reserved. + * See 'LICENSE' in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + +/** + * Module interface file search path support. + * + * The IntelliSense engine resolves `import` directives by searching for module + * interface files for the imported modules. In addition to the mappings and + * search directories passed through module related compiler arguments (for + * example, /reference and /ifcSearchDir in MSVC mode), the engine also searches + * the directory named by the EDG_MODULES_PATH environment variable. That + * variable is read when each translation unit is compiled, so setting it in + * the environment of the language server process (which inherits the extension + * host environment) makes the module files in that directory available for + * import resolution in every IntelliSense mode, including the gcc and clang + * modes whose module file formats cannot be produced by the project's own + * toolchain. + * + * See https://github.com/microsoft/vscode-cpptools/issues/6302. + */ + +/** The environment variable read by the IntelliSense engine. */ +export const moduleSearchPathEnvVar: string = "EDG_MODULES_PATH"; + +/** + * Resolve the value of the "C_Cpp.intelliSenseModuleSearchPath" setting. The + * ${workspaceFolder} variable is replaced with workspaceFolderPath. Returns + * undefined for a missing, empty, or blank value. + */ +export function resolveModuleSearchPath(moduleSearchPath: string | undefined, workspaceFolderPath: string | undefined): string | undefined { + if (!moduleSearchPath) { + return undefined; + } + let resolved: string = moduleSearchPath; + if (workspaceFolderPath) { + resolved = resolved.replace(/\$\{workspaceFolder\}/g, workspaceFolderPath); + } + resolved = resolved.trim(); + return resolved ? resolved : undefined; +} + +/** + * Build the additional environment for the language server process from the + * "C_Cpp.intelliSenseModuleSearchPath" setting. Returns undefined when the + * setting is not set, so that the child environment is inherited unchanged. + */ +export function getModuleSearchPathServerEnv(moduleSearchPath: string | undefined, workspaceFolderPath: string | undefined): NodeJS.ProcessEnv | undefined { + const resolved: string | undefined = resolveModuleSearchPath(moduleSearchPath, workspaceFolderPath); + if (!resolved) { + return undefined; + } + return { [moduleSearchPathEnvVar]: resolved }; +} diff --git a/Extension/src/LanguageServer/settings.ts b/Extension/src/LanguageServer/settings.ts index 3003b9ebf..5c858353f 100644 --- a/Extension/src/LanguageServer/settings.ts +++ b/Extension/src/LanguageServer/settings.ts @@ -424,6 +424,7 @@ export class CppSettings extends Settings { public get suggestSnippets(): boolean { return this.getAsBoolean("suggestSnippets"); } public get intelliSenseEngine(): string { return this.getAsString("intelliSenseEngine"); } public get intelliSenseCachePath(): string | undefined { return changeBlankStringToUndefined(this.getAsStringOrUndefined("intelliSenseCachePath")); } + public get intelliSenseModuleSearchPath(): string | undefined { return changeBlankStringToUndefined(this.getAsStringOrUndefined("intelliSenseModuleSearchPath")); } public get intelliSenseCacheSize(): number { return this.getAsNumber("intelliSenseCacheSize"); } public get intelliSenseMemoryLimit(): number { return this.getAsNumber("intelliSenseMemoryLimit"); } public get intelliSenseUpdateDelay(): number { return this.getAsNumber("intelliSenseUpdateDelay"); } diff --git a/Extension/test/scenarios/CppModulesProject/assets/moduleFiles/geometry.eifc b/Extension/test/scenarios/CppModulesProject/assets/moduleFiles/geometry.eifc new file mode 100644 index 0000000000000000000000000000000000000000..58ac4b75f459acda4c423fcfb9f2d4633cd2dc07 GIT binary patch literal 944 zcmcgqJ&P1U5H0r>y<0>R1%ne^@jzjB8cZ%xLFD`h4wTbCSXg^!>UKwFy62{QmOVc} zOiT^LKruQD&F&BQ5A(0eyvuU z$Kf_!A}YEKkpVJLEc78uGzw((k1p~7dxhpuMml8bZ4Xot?f=7tN}WLZj{~yXk>F*Y zV}O`wQq%sAXkuL`QrGQt>VBHC&Doc`q;lgGt1VlVF{_)Yzg10?v!!)2rzelq+{HHG zVO$j6+RUkqg=gbZYm{f_m5bTvGPO=!FN#f@R2jQFrG3P)SK2xDPUYIqqI9t!Oe#1^ z*u|7^oJHG}i9IHf+o^QPV?dKD<0wlFlhHXxu3l@noo4($H}$(%^!Iu#OR$mgI-_`| zOCMDRTg^FZUZ&6`(w<9lX~I9I3>Lw!K;(8hQ4j<{jzupJ6g}8%>7A+D9hvDFrhArC*g()& z#pFPYlm^b~ZUR7;%_s+dLgXJHuX1_j7t~}x4 z*Q@N?_N#K9LDvCxDuIzx|49q4$rRXGeDD z)pc<*f4i5o5^S}DHJ5<|q8|ekAbVY`SJ|KVOF(mAqDlU7pluTS+q%e<9^FpI_ZQvI zm})mAl^Um5-Ob7(WOXBUH_NfIS&`YP)#Hb1X2UGvewgPj%Mz;w8;*^QGou_^r)gK@uA# zqf-v7pQpbbC;VSWbPq7$pSc<@!bryHgr=6oa({_rNOK-PO7ctxu^l|3{y_W=)H>j zUd46FwacgQ9AvHbFJPV5kn27T457crD*k!kHT(qt4@v$dkUk)~d|{iw<=Wp5UI2rZ t{}y}=kX*r2fZ@yES@Iu&&jCDMUjmVs^p{WX9QYQ{)L#RC2jKDbzX8J~&hr2O literal 0 HcmV?d00001 diff --git a/Extension/test/scenarios/CppModulesProject/tests/modules.integration.test.ts b/Extension/test/scenarios/CppModulesProject/tests/modules.integration.test.ts index e795d3a52..616946b92 100644 --- a/Extension/test/scenarios/CppModulesProject/tests/modules.integration.test.ts +++ b/Extension/test/scenarios/CppModulesProject/tests/modules.integration.test.ts @@ -12,22 +12,27 @@ // These tests cover the extension-side behavior that module based projects // rely on today: // * module interface files (.cppm/.ixx) are recognized as C++ sources, +// * the "C_Cpp.intelliSenseModuleSearchPath" setting feeds the module +// interface file search directory to the IntelliSense engine, and module +// imports are actually resolved through it (using checked-in .eifc module +// interface files produced by the open-source EDG front end), // * a compile_commands.json that contains GCC and Clang module related flags // does not prevent the language server from providing IntelliSense for the // project, and its entries are actually applied to the translation units // (verified through sentinel defines and hover assertions, not just // readiness), -// * module related compiler arguments are accepted and delivered through the -// custom configuration provider path (GCC and MSVC spellings; Clang is -// exercised through the compile_commands.json suite above, not the -// provider). The verification is effect-based but partial: a sentinel -// define travels in the same `compilerArgs` array as the module flags, and -// the hover assertions prove that `compilerArgs` reach the language server -// and are applied to the translation unit. They do NOT verify each module -// switch individually: a module flag dropped selectively (e.g. -// `-fmodules-ts` or `/reference` removed while the sentinel define -// remains) would not be detected by these tests. Per-flag assertions -// would require observing module semantics, which are not available yet. +// * module related compiler arguments (GCC, Clang and MSVC spellings) are +// accepted and delivered through the custom configuration provider path +// (GCC and MSVC spellings; Clang is exercised through the +// compile_commands.json suite above, not the provider). The verification +// is effect-based but partial: a sentinel define travels in the same +// `compilerArgs` array as the module flags, and the hover assertions prove +// that `compilerArgs` reach the language server and are applied to the +// translation unit. They do NOT verify each module switch individually: a +// module flag dropped selectively (e.g. `-fmodules-ts` or `/reference` +// removed while the sentinel define remains) would not be detected by +// these tests. Per-flag assertions would require observing module +// semantics, which are not available yet. // // No statement is made about the semantic understanding of module imports by // the language server itself: that support is still in development and is @@ -112,12 +117,12 @@ async function openAndAwaitIntelliSenseReady(cpptools: apit.CppToolsTestApi, dis return document; } -// Verifies, through IntelliSense, that a sentinel define reached the language -// server for the given document: hovering over a use of a symbol that is only -// declared under "#ifdef " resolves if and only if the define was -// applied to the translation unit. This observes the *effect* of the delivered -// configuration instead of merely re-checking what a provider returned. -async function assertSentinelDefineApplied(document: vscode.TextDocument, useStatement: string, symbol: string): Promise { +// Verifies, through IntelliSense, that a symbol resolves at its use: hovering +// over the use of a symbol resolves if and only if its declaration is visible +// to the language server. For sentinel defines this observes the *effect* of +// the delivered configuration; for imported symbols it observes that the +// module interface file was found and imported. +async function assertHoverResolves(document: vscode.TextDocument, useStatement: string, symbol: string): Promise { const text: string = document.getText(); const useIndex: number = text.indexOf(useStatement); assert.ok(useIndex >= 0, `use statement not found in document: ${useStatement}`); @@ -136,7 +141,11 @@ async function assertSentinelDefineApplied(document: vscode.TextDocument, useSta } await testHelpers.delay(500); } - assert.fail(`hover did not resolve '${symbol}' -- the sentinel define was not applied to ${document.uri.fsPath}`); + assert.fail(`hover did not resolve '${symbol}' -- its declaration was not applied to ${document.uri.fsPath}`); +} + +async function assertSentinelDefineApplied(document: vscode.TextDocument, useStatement: string, symbol: string): Promise { + await assertHoverResolves(document, useStatement, symbol); } /* **************************************************************************** */ @@ -206,6 +215,92 @@ function msvcModuleArgs(): string[] { /* **************************************************************************** */ +// The module interface files (.eifc, the IntelliSense engine's own module +// interface file format) for the "math" and "geometry" modules are checked in +// with the assets. They were produced with the open-source EDG front end +// (https://github.com/edgcpp/compiler) using --module_interface; see +// https://github.com/microsoft/vscode-cpptools/issues/6302. +function moduleFilesDir(): string { + return toPosixPath(`${workspacePath()}/moduleFiles`); +} + +/* **************************************************************************** */ + +// This suite runs first, before any other suite has opened a file: the module +// search path setting is only read when the language server is started (the +// language server process is spawned on the first opened C++ file), so the +// workspace settings file has to be in place before then. +suite("module import resolution through C_Cpp.intelliSenseModuleSearchPath", function(): void { + let cpptools: apit.CppToolsTestApi; + const disposables: vscode.Disposable[] = []; + + suiteSetup(async function(): Promise { + // Write the workspace setting that feeds the module interface file + // search directory to the IntelliSense engine, then wait for VS Code + // to pick up the settings file before any file is opened. + await util.writeFileText(path.join(workspacePath(), '.vscode', 'settings.json'), + JSON.stringify({ "C_Cpp.intelliSenseModuleSearchPath": moduleFilesDir() })); + await testHelpers.delay(4000); + + cpptools = await apit.getCppToolsTestApi(api.Version.v2) ?? assert.fail('Could not get CppToolsTestApi'); + disposables.push(cpptools); + + await writeCompileCommands([ + // The sentinel define carried by main.cpp's entry lets the test + // verify that the database entry was applied. + compileCommandEntry("main.cpp", fakeCompilerPath("gcc"), gccModuleArgs(), ["-DCPPMODULES_COMPILE_COMMANDS_SENTINEL=1"]), + compileCommandEntry("math.cppm", fakeCompilerPath("gcc"), gccModuleArgs()), + compileCommandEntry("math.ixx", fakeCompilerPath("gcc"), gccModuleArgs()) + ]); + + await changeCppProperties({ + configurations: [ + { + name: "GCC C++20 modules", + compileCommands: [compileCommandsPath()], + intelliSenseMode: "gcc-x64", + cppStandard: "c++20" + } + ], + version: 4 + }, + disposables); + }); + + suiteTeardown(async function(): Promise { + disposables.forEach(d => d.dispose()); + await util.deleteFile(path.join(workspacePath(), '.vscode', 'settings.json')); + }); + + test("module imports resolve through the module search path (main.cpp)", async function(): Promise { + const document: vscode.TextDocument = await openAndAwaitIntelliSenseReady(cpptools, disposables, "main.cpp"); + + // Verify that the compile_commands.json entry for this file was + // applied to the translation unit. + await assertSentinelDefineApplied(document, "return compile_database_sentinel_value;", "compile_database_sentinel_value"); + + // Give the diagnostics time to settle after the parse. + await testHelpers.delay(5000); + const diagnostics: vscode.Diagnostic[] = vscode.languages.getDiagnostics(document.uri); + const moduleFileErrors: vscode.Diagnostic[] = diagnostics.filter(d => d.message.includes("could not find module file")); + if (moduleFileErrors.length > 0) { + // The checked-in .eifc module files could not be read by this + // build of the language server (module file format version churn). + // Skip the semantic assertions instead of failing; the + // settings-to-environment plumbing itself is covered by unit + // tests. + console.warn(" Dynamically skipping module semantic assertions: " + moduleFileErrors.map(d => d.message).join("; ")); + return; + } + + // The module interface files were found and imported: the entities + // exported by the imported modules are visible to IntelliSense. + await assertHoverResolves(document, "return add(1, 2) + square_area(3) - math::k_answer;", "add"); + }); +}); + +/* **************************************************************************** */ + suite("C++20 modules file type tests", function(): void { suiteSetup(async function(): Promise { await testHelpers.activateCppExtension(); diff --git a/Extension/test/unit/moduleSearchPath.test.ts b/Extension/test/unit/moduleSearchPath.test.ts new file mode 100644 index 000000000..87a469672 --- /dev/null +++ b/Extension/test/unit/moduleSearchPath.test.ts @@ -0,0 +1,43 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All Rights Reserved. + * See 'LICENSE' in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + +import { deepStrictEqual, strictEqual } from 'node:assert'; +import { describe, it } from 'mocha'; +import { getModuleSearchPathServerEnv, moduleSearchPathEnvVar, resolveModuleSearchPath } from '../../src/LanguageServer/moduleSearchPath'; + +describe('module search path env', () => { + it('undefined setting yields undefined env', () => { + strictEqual(getModuleSearchPathServerEnv(undefined, "/project"), undefined); + strictEqual(getModuleSearchPathServerEnv(undefined, undefined), undefined); + }); + + it('empty and blank values yield undefined env', () => { + strictEqual(getModuleSearchPathServerEnv("", "/project"), undefined); + strictEqual(getModuleSearchPathServerEnv(" ", "/project"), undefined); + }); + + it('absolute path is passed through unchanged', () => { + const env: NodeJS.ProcessEnv | undefined = getModuleSearchPathServerEnv("/modules/ifc", "/project"); + deepStrictEqual(env, { [moduleSearchPathEnvVar]: "/modules/ifc" }); + }); + + it('workspaceFolder variable is resolved', () => { + strictEqual(resolveModuleSearchPath("${workspaceFolder}/build/ifc", "/project"), "/project/build/ifc"); + strictEqual(resolveModuleSearchPath("prefix ${workspaceFolder} middle ${workspaceFolder}", "/project"), "prefix /project middle /project"); + }); + + it('workspaceFolder variable is kept when no folder is given', () => { + strictEqual(resolveModuleSearchPath("${workspaceFolder}/build/ifc", undefined), "${workspaceFolder}/build/ifc"); + }); + + it('value is trimmed before use', () => { + const env: NodeJS.ProcessEnv | undefined = getModuleSearchPathServerEnv(" /modules/ifc ", "/project"); + deepStrictEqual(env, { [moduleSearchPathEnvVar]: "/modules/ifc" }); + }); + + it('env var name is EDG_MODULES_PATH', () => { + strictEqual(moduleSearchPathEnvVar, "EDG_MODULES_PATH"); + }); +}); From 495ae269fef77a529715990f4964f24842288002 Mon Sep 17 00:00:00 2001 From: soroshsabz Date: Wed, 2 Dec 2026 09:50:42 +0330 Subject: [PATCH 2/2] Add C_Cpp.intelliSenseModuleCompilerPath for automatic .eifc generation --- Extension/package.json | 6 + Extension/package.nls.json | 2 + Extension/src/LanguageServer/client.ts | 39 +++- .../LanguageServer/moduleInterfaceCompiler.ts | 205 ++++++++++++++++++ .../src/LanguageServer/moduleSearchPath.ts | 55 +++++ Extension/src/LanguageServer/settings.ts | 1 + .../CppModulesProject/assets/.gitignore | 1 + .../assets/moduleFiles/geometry.eifc | Bin 944 -> 2050 bytes .../assets/moduleFiles/math.eifc | Bin 1124 -> 2646 bytes .../tests/modules.integration.test.ts | 56 ++++- .../test/unit/moduleInterfaceCompiler.test.ts | 117 ++++++++++ Extension/test/unit/moduleSearchPath.test.ts | 41 +++- 12 files changed, 508 insertions(+), 15 deletions(-) create mode 100644 Extension/src/LanguageServer/moduleInterfaceCompiler.ts create mode 100644 Extension/test/unit/moduleInterfaceCompiler.test.ts diff --git a/Extension/package.json b/Extension/package.json index ad170871f..95502aada 100644 --- a/Extension/package.json +++ b/Extension/package.json @@ -999,6 +999,12 @@ "scope": "resource", "markdownDescription": "%c_cpp.configuration.intelliSenseModuleSearchPath.markdownDescription%" }, + "C_Cpp.intelliSenseModuleCompilerPath": { + "type": "string", + "description": "%c_cpp.configuration.intelliSenseModuleCompilerPath.description%", + "scope": "resource", + "markdownDescription": "%c_cpp.configuration.intelliSenseModuleCompilerPath.markdownDescription%" + }, "C_Cpp.codeFolding": { "type": "string", "enum": [ diff --git a/Extension/package.nls.json b/Extension/package.nls.json index 025e568ef..fd8a9a505 100644 --- a/Extension/package.nls.json +++ b/Extension/package.nls.json @@ -625,6 +625,8 @@ "c_cpp.configuration.intelliSenseUpdateDelay.description": "Controls the delay in milliseconds before IntelliSense starts updating after a modification.", "c_cpp.configuration.intelliSenseModuleSearchPath.description": "Directory searched for compiled module interface files when IntelliSense resolves import directives.", "c_cpp.configuration.intelliSenseModuleSearchPath.markdownDescription": "Directory searched by IntelliSense for compiled module interface files when resolving `import` directives. Module files in this directory are found in every IntelliSense mode, including gcc and clang modes whose module files cannot be produced by the project's own toolchain. The `${workspaceFolder}` variable is supported. The value is passed to the IntelliSense engine at startup, so changing it requires reloading the window. See issue [#6302](https://github.com/microsoft/vscode-cpptools/issues/6302) for the module IntelliSense status.", + "c_cpp.configuration.intelliSenseModuleCompilerPath.description": "Command that compiles module interface units into module interface files for IntelliSense.", + "c_cpp.configuration.intelliSenseModuleCompilerPath.markdownDescription": "Path to a C/C++ front end command used to compile the workspace's module interface units (`.cppm`/`.ixx`/`.ccm`) into the module interface files IntelliSense uses to resolve `import` directives. Build the command from the open-source EDG front end project ([edgcpp/compiler](https://github.com/edgcpp/compiler)); the resulting `eccp` command produces `.eifc` module interface files that the IntelliSense engine can read in every IntelliSense mode. The generated files are written into the directory given by `#C_Cpp.intelliSenseModuleSearchPath#` (or a per-workspace cache directory when that is not set). The `${workspaceFolder}` variable is supported. Module interface files are (re)generated when the interface source changes and at language server startup, so setting changes require reloading the window. See issue [#6302](https://github.com/microsoft/vscode-cpptools/issues/6302) for the module IntelliSense status.", "c_cpp.configuration.default.includePath.markdownDescription": { "message": "The value to use in a configuration if `includePath` is not specified in `c_cpp_properties.json`. If `includePath` is specified, add `${default}` to the array to insert the values from this setting. Usually, this should not include system includes; instead, set `#C_Cpp.default.compilerPath#`.", "comment": [ diff --git a/Extension/src/LanguageServer/client.ts b/Extension/src/LanguageServer/client.ts index b5ad7f311..29c080891 100644 --- a/Extension/src/LanguageServer/client.ts +++ b/Extension/src/LanguageServer/client.ts @@ -58,7 +58,8 @@ import { CppSourceStr, clients, configPrefix, initializeIntervalTimer, isWriting import { IncludeCleanupPreferences, getIncludeCleanupPreferences } from './includeCleanupEditorConfig'; import { InactiveRegion, InactiveRegionStore, getInactiveRegionStartLines } from './inactiveRegions'; import { LanguageClient } from './languageClient'; -import { getModuleSearchPathServerEnv } from './moduleSearchPath'; +import { generateModuleFiles, moduleInterfaceGlob } from './moduleInterfaceCompiler'; +import { getModuleFilesTargetDir, getModuleSearchPathServerEnv, moduleSearchPathEnvVar } from './moduleSearchPath'; import { LocalizeStringParams, getLocaleId, getLocalizedString } from './localization'; import { PersistentFolderState, PersistentState, PersistentWorkspaceState } from './persistentState'; import { RequestCancelled, ServerCancelled, createProtocolFilter } from './protocolFilter'; @@ -1655,12 +1656,30 @@ export class DefaultClient implements Client { // from a sanitizer build to files in that directory (see getSanitizerServerEnv). This is // undefined -- i.e. the environment is inherited unchanged -- for normal builds. const sanitizerServerEnv: NodeJS.ProcessEnv | undefined = getSanitizerServerEnv(); - // Set the module interface file search directory for the IntelliSense engine from the - // "C_Cpp.intelliSenseModuleSearchPath" setting (see moduleSearchPath.ts). Also inherited - // when unset. The value is only read at language server startup, so setting changes - // require reloading the window. - const moduleSearchPathEnv: NodeJS.ProcessEnv | undefined = - getModuleSearchPathServerEnv(new CppSettings(this.RootUri).intelliSenseModuleSearchPath, this.RootPath); + // Module import resolution (see moduleSearchPath.ts and moduleInterfaceCompiler.ts): pass + // the module interface file search directory to the IntelliSense engine through + // EDG_MODULES_PATH. When a module interface compiler is configured, module interface files + // are (re)generated into that directory first. The engine reads the variable when each + // translation unit is compiled, but the language server process environment is only set + // here, at startup, so setting changes require reloading the window. + const settings: CppSettings = new CppSettings(this.RootUri); + let moduleSearchPathEnv: NodeJS.ProcessEnv | undefined; + if (settings.intelliSenseModuleCompilerPath) { + const targetDir: string | undefined = getModuleFilesTargetDir(settings.intelliSenseModuleSearchPath, this.RootPath); + if (targetDir) { + const out: Logger = getOutputChannelLogger(); + try { + const interfaceFiles: string[] = await findModuleInterfaceFiles(); + await generateModuleFiles(settings.intelliSenseModuleCompilerPath, interfaceFiles, targetDir, + settings.defaultCppStandard, (message: string) => out.appendLine(message)); + } catch (error) { + out.appendLine(`module interface file generation failed: ${error instanceof Error ? error.message : String(error)}`); + } + moduleSearchPathEnv = { [moduleSearchPathEnvVar]: targetDir }; + } + } else { + moduleSearchPathEnv = getModuleSearchPathServerEnv(settings.intelliSenseModuleSearchPath, this.RootPath); + } let serverEnv: NodeJS.ProcessEnv | undefined; if (sanitizerServerEnv || moduleSearchPathEnv) { serverEnv = { ...process.env, ...sanitizerServerEnv, ...moduleSearchPathEnv }; @@ -4501,6 +4520,12 @@ function getLanguageServerFileName(): string { // so this is a no-op for normal builds and safe to leave checked in. To use it, build a sanitizer // preset of the language server, set CPPTOOLS_SANITIZER_LOG_DIR before launching VS Code (or add it // to the launch config's "env"), reproduce, then read the "/." files. +/** Find the module interface units of the workspace (by file extension). */ +async function findModuleInterfaceFiles(): Promise { + const uris: vscode.Uri[] = await vscode.workspace.findFiles(moduleInterfaceGlob, undefined, 1000); + return uris.map(uri => uri.fsPath); +} + function getSanitizerServerEnv(): NodeJS.ProcessEnv | undefined { const logDirectoryEnv: string | undefined = process.env.CPPTOOLS_SANITIZER_LOG_DIR; if (!logDirectoryEnv) { diff --git a/Extension/src/LanguageServer/moduleInterfaceCompiler.ts b/Extension/src/LanguageServer/moduleInterfaceCompiler.ts new file mode 100644 index 000000000..8094ea645 --- /dev/null +++ b/Extension/src/LanguageServer/moduleInterfaceCompiler.ts @@ -0,0 +1,205 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All Rights Reserved. + * See 'LICENSE' in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + +import { spawn } from 'child_process'; +import * as fs from 'fs'; +import * as path from 'path'; + +/** + * Generation of module interface files (.eifc) for IntelliSense import + * resolution, using the open-source EDG front end + * (https://github.com/edgcpp/compiler). + * + * The IntelliSense engine can read .eifc module interface files in every + * IntelliSense mode, but no mainstream compiler or build system produces them. + * When the user configures "C_Cpp.intelliSenseModuleCompilerPath" with an EDG + * front end command (an "eccp" from a build of the open-source EDG project), + * the extension compiles the workspace's module interface units into a + * directory on the module search path (see moduleSearchPath.ts), so that + * `import` directives resolve without any manual per-module setup. + * + * See https://github.com/microsoft/vscode-cpptools/issues/6302. + */ + +/** File extensions that (by convention) hold module interface units. */ +export const moduleInterfaceExtensions: readonly string[] = ['.cppm', '.ixx', '.ccm']; + +/** The glob used to find module interface units in the workspace. */ +export const moduleInterfaceGlob: string = '**/*{.cppm,.ixx,.ccm}'; + +/** Per-file compilation timeout in milliseconds. */ +const compileTimeoutMs: number = 30000; + +export function isModuleInterfaceFileName(filePath: string): boolean { + return moduleInterfaceExtensions.some(ext => filePath.toLowerCase().endsWith(ext)); +} + +/** + * Extract the module name from the source of a module interface unit, e.g. + * "math" from "export module math;". Module units with partitions + * ("export module m:p;") map to the "m-p" name the engine uses for their + * module interface files. Returns undefined when no module declaration is + * found. + */ +export function parseModuleName(source: string): string | undefined { + const match: RegExpMatchArray | null = source.match(/export\s+module\s+([A-Za-z0-9_][A-Za-z0-9_.:]*)\s*;/); + if (!match) { + return undefined; + } + const fullName: string = match[1]; + const colonIndex: number = fullName.indexOf(':'); + if (colonIndex > 0) { + // A module partition: the engine names its module interface files + // "-". + return `${fullName.substring(0, colonIndex)}-${fullName.substring(colonIndex + 1)}`; + } + return fullName; +} + +/** + * The "--c++NN" arguments to pass to the front end, derived from the C++ + * standard of the workspace (modules require C++20 or later). + */ +export function getEdgStandardArgs(cppStandard: string | undefined): string[] { + switch (cppStandard) { + case "c++23": + return ["--c++23"]; + case "c++26": + return ["--c++26"]; + default: + return ["--c++20"]; + } +} + +/** + * Determine whether the module interface file for the given interface source + * is missing or older than the source and therefore needs to be (re)generated + * into targetDir. Returns true when the module name cannot be determined from + * the source, so the compiler gets the final say. + */ +export async function moduleFileNeedsRegeneration(interfaceFilePath: string, targetDir: string): Promise { + let source: string; + try { + source = await fs.promises.readFile(interfaceFilePath, "utf8"); + } catch { + return true; + } + const moduleName: string | undefined = parseModuleName(source); + if (!moduleName) { + return true; + } + const moduleFile: string = path.join(targetDir, `${moduleName}.eifc`); + try { + const [sourceStat, moduleFileStat] = await Promise.all([ + fs.promises.stat(interfaceFilePath), + fs.promises.stat(moduleFile) + ]); + return moduleFileStat.mtimeMs < sourceStat.mtimeMs; + } catch { + // The module file does not exist (or cannot be stat'ed). + return true; + } +} + +export interface ModuleFileGenerationResult { + /** Interface files whose module interface file was (re)generated. */ + generated: string[]; + /** Interface files whose module interface file was already up to date. */ + skipped: string[]; + /** Interface files whose compilation failed, with the error output. */ + failed: { file: string; error: string }[]; +} + +/** + * Compile the given module interface units with the front end at + * compilerPath, writing the .eifc module interface files into targetDir (which + * must be on the module search path). Files whose module interface file is + * already up to date are skipped. Runs the compilations sequentially; each + * compilation is subject to a timeout. + */ +export async function generateModuleFiles(compilerPath: string, interfaceFilePaths: string[], targetDir: string, + cppStandard: string | undefined, log: (message: string) => void): Promise { + + const result: ModuleFileGenerationResult = { generated: [], skipped: [], failed: [] }; + await fs.promises.mkdir(targetDir, { recursive: true }); + const compilerArgs: string[] = [...getEdgStandardArgs(cppStandard), "--modules", "--module_interface"]; + + for (const interfaceFilePath of interfaceFilePaths) { + if (!await moduleFileNeedsRegeneration(interfaceFilePath, targetDir)) { + result.skipped.push(interfaceFilePath); + continue; + } + const spawned: CompilerInvocationResult = await invokeCompiler(compilerPath, [...compilerArgs, interfaceFilePath], targetDir); + if (spawned.error === undefined) { + result.generated.push(interfaceFilePath); + if (spawned.output) { + log(`module interface file generated for ${path.basename(interfaceFilePath)}: ${spawned.output}`); + } + } else { + result.failed.push({ file: interfaceFilePath, error: spawned.output || spawned.error.message }); + log(`module interface file generation failed for ${interfaceFilePath}: ${spawned.output || spawned.error}`); + } + } + return result; +} + +interface CompilerInvocationResult { + /** The error, in case the compiler could not be run at all. */ + error: Error | undefined; + /** The captured stdout/stderr output. */ + output: string; +} + +function quoteForCmd(arg: string): string { + // cmd.exe quoting: quote arguments that could contain spaces or + // characters that cmd interprets. + if (/[ &|<>^"%,;]/.test(arg) || arg.includes(' ')) { + return `"${arg.replace(/"/g, '""')}"`; + } + return arg; +} + +async function invokeCompiler(compilerPath: string, args: string[], cwd: string): Promise { + return new Promise((resolve) => { + let output: string = ""; + const appendOutput: (chunk: Buffer | string) => void = (chunk: Buffer | string) => { + output += chunk.toString(); + // Bound the captured output. + if (output.length > 16384) { + output = output.substring(0, 16384); + } + }; + + let child: ReturnType; + const isCmdScript: boolean = process.platform === "win32" && /\.(cmd|bat)$/i.test(compilerPath); + if (isCmdScript) { + // cmd scripts cannot be spawned directly on Windows. + const command: string = [compilerPath, ...args].map(quoteForCmd).join(" "); + child = spawn(process.env.comspec ?? "cmd.exe", ["/d", "/s", "/c", command], { cwd }); + } else { + child = spawn(compilerPath, args, { cwd }); + } + + const timer: NodeJS.Timeout = setTimeout(() => { + output += "\n(timeout)"; + child.kill(); + }, compileTimeoutMs); + + child.stdout?.on('data', appendOutput); + child.stderr?.on('data', appendOutput); + child.on('error', (err: Error) => { + clearTimeout(timer); + resolve({ error: err, output }); + }); + child.on('close', (code: number | null) => { + clearTimeout(timer); + if (code === 0) { + resolve({ error: undefined, output }); + } else { + resolve({ error: new Error(`exited with code ${code}`), output }); + } + }); + }); +} diff --git a/Extension/src/LanguageServer/moduleSearchPath.ts b/Extension/src/LanguageServer/moduleSearchPath.ts index cd9d583f7..0246b2522 100644 --- a/Extension/src/LanguageServer/moduleSearchPath.ts +++ b/Extension/src/LanguageServer/moduleSearchPath.ts @@ -3,6 +3,10 @@ * See 'LICENSE' in the project root for license information. * ------------------------------------------------------------------------------------------ */ +import * as crypto from 'crypto'; +import * as os from 'os'; +import * as path from 'path'; + /** * Module interface file search path support. * @@ -18,6 +22,11 @@ * modes whose module file formats cannot be produced by the project's own * toolchain. * + * The module interface files themselves can be produced with the open-source + * EDG front end (https://github.com/edgcpp/compiler) using + * "--module_interface"; see moduleInterfaceCompiler.ts for the extension-side + * orchestration of that. + * * See https://github.com/microsoft/vscode-cpptools/issues/6302. */ @@ -53,3 +62,49 @@ export function getModuleSearchPathServerEnv(moduleSearchPath: string | undefine } return { [moduleSearchPathEnvVar]: resolved }; } + +/** + * The default root directory of the extension's caches, mirroring the default + * used by the language server for the IntelliSense cache: + * Windows: %LocalAppData%/Microsoft/vscode-cpptools/, otherwise ~/.vscode-cpptools/. + */ +export function getDefaultCacheRoot(): string { + if (os.platform() === "win32") { + const localAppData: string | undefined = process.env.LOCALAPPDATA; + if (localAppData) { + return path.join(localAppData, "Microsoft", "vscode-cpptools"); + } + } + return path.join(os.homedir(), ".vscode-cpptools"); +} + +/** + * A stable per-workspace directory name, so that module interface files + * generated for different workspaces never collide (module interface files + * are named after the module, not after the source file). + */ +export function workspaceCacheSubdirName(workspaceFolderPath: string | undefined): string { + if (!workspaceFolderPath) { + return "workspace"; + } + const normalized: string = workspaceFolderPath.replace(/[\\/]+$/, ""); + return crypto.createHash("md5").update(normalized).digest("hex").substring(0, 16); +} + +/** + * The directory in which module interface files for the given workspace are + * searched (and, when a module interface compiler is configured, generated): + * the "C_Cpp.intelliSenseModuleSearchPath" setting when set, otherwise a + * managed subdirectory of the extension's default cache root. Returns + * undefined when neither is available (no workspace folder and no setting). + */ +export function getModuleFilesTargetDir(moduleSearchPath: string | undefined, workspaceFolderPath: string | undefined): string | undefined { + const resolved: string | undefined = resolveModuleSearchPath(moduleSearchPath, workspaceFolderPath); + if (resolved) { + return resolved; + } + if (!workspaceFolderPath) { + return undefined; + } + return path.join(getDefaultCacheRoot(), "moduleFiles", workspaceCacheSubdirName(workspaceFolderPath)); +} diff --git a/Extension/src/LanguageServer/settings.ts b/Extension/src/LanguageServer/settings.ts index 5c858353f..2f45ac325 100644 --- a/Extension/src/LanguageServer/settings.ts +++ b/Extension/src/LanguageServer/settings.ts @@ -425,6 +425,7 @@ export class CppSettings extends Settings { public get intelliSenseEngine(): string { return this.getAsString("intelliSenseEngine"); } public get intelliSenseCachePath(): string | undefined { return changeBlankStringToUndefined(this.getAsStringOrUndefined("intelliSenseCachePath")); } public get intelliSenseModuleSearchPath(): string | undefined { return changeBlankStringToUndefined(this.getAsStringOrUndefined("intelliSenseModuleSearchPath")); } + public get intelliSenseModuleCompilerPath(): string | undefined { return changeBlankStringToUndefined(this.getAsStringOrUndefined("intelliSenseModuleCompilerPath")); } public get intelliSenseCacheSize(): number { return this.getAsNumber("intelliSenseCacheSize"); } public get intelliSenseMemoryLimit(): number { return this.getAsNumber("intelliSenseMemoryLimit"); } public get intelliSenseUpdateDelay(): number { return this.getAsNumber("intelliSenseUpdateDelay"); } diff --git a/Extension/test/scenarios/CppModulesProject/assets/.gitignore b/Extension/test/scenarios/CppModulesProject/assets/.gitignore index 47001bd44..659c7ce72 100644 --- a/Extension/test/scenarios/CppModulesProject/assets/.gitignore +++ b/Extension/test/scenarios/CppModulesProject/assets/.gitignore @@ -1,3 +1,4 @@ # Generated at runtime by the scenario tests. .vscode/ build/ +generatedModules/ diff --git a/Extension/test/scenarios/CppModulesProject/assets/moduleFiles/geometry.eifc b/Extension/test/scenarios/CppModulesProject/assets/moduleFiles/geometry.eifc index 58ac4b75f459acda4c423fcfb9f2d4633cd2dc07..3498c230ee68d9ad9812a127aa52abebb4cc7d86 100644 GIT binary patch literal 2050 zcmcgtO^6*u5bo@c|HPQ+$s818RLIUCLGPlwy68q1a}s3iH&gSrvoq6^>3+|BLLgo? z7X|UAx1b&bkyQ+M@gRaIc+A0rBH|?;JV+GHE#Egkn_eMPyX<)T|9TlUt0g^lPmYnt$w!t?d41Vd~wesv-!6Ut7B?TLH?ds>MK~c!@dL9 z2Yh~uQujft6MXC;3>stw#=zT*;M9Y?5coeG0x@<7pd9A|MSM6+0NsZ;&GBBg2Lo}x z3^w$G0BQ|nUi}`hz5JI0Kj&UQ{~*>LWH0}L1Kob_LJ%89Ve=rUPAL=2*Bt1D!vwdv z8N~GNRtTpEXaI^f%EMuH$HykA@#yoN^l%4pQoeWC?*_I3 z#vB2j0Wu&5ZUq=m*$*%W`BC5@AO(iFMc8iw)Xa6h2h^_I32UK0iG{hjHs=C%#k{P8 z`YGTnpvGcL@y$%dW#wauU$&DbmH1iXpPP(gXB+D_oF2UqPhDy=SxW2LTU)qzdCN=X zjIClX&c`m5N;k&3`02V{v)QB&_flg|N$O+moOlob{0Jz_A9x+PLP&z?mTaEcn~t{5a76 l9TI;O_-B}Z0i5gc+xHFdJvhIsj9-M~kKRvy5&X}9Ujy<0>R1%ne^@jzjB8cZ%xLFD`h4wTbCSXg^!>UKwFy62{QmOVc} zOiT^LKruQD&F&BQ5A(0eyvuU z$Kf_!A}YEKkpVJLEc78uGzw((k1p~7dxhpuMml8bZ4Xot?f=7tN}WLZj{~yXk>F*Y zV}O`wQq%sAXkuL`QrGQt>VBHC&Doc`q;lgGt1VlVF{_)Yzg10?v!!)2rzelq+{HHG zVO$j6+RUkqg=gbZYm{f_m5bTvGPO=!FN#f@R2jQFrG3P)SK2xDPUYIqqI9t!Oe#1^ z*u|7^oJHG}i9IHf+o^QPV?dKD<0wlFlhHXxu3l@noo4($H}$(%^!Iu#OR$mgI-_`| zOCMDRTg^FZUZ&6`(w<9lX~I>!~297P7ARg z`Yg}^*6tMID5SW;AB>q+On#rT+6gP)o-lt`7|adoO-4w6e$lfXPw8~#cKS7M;bF{k zJk1|$;7jKOvjacLc{|pe0>AH_4*3|sP4A9r@#C(sCx6T1x%T$;2fZ5i;(t5X?*DGA zJz!(8`5359h>Zu@{o-7N>oeyu8b0;n`+MXx!8Qy$ADENjc*_4O&Id@ycqn^vUnU8y z@}c#4pG-d$}LF^YgYg@%HQEBuWvB6V_9ZdxpD1;l+ zUgOv0Wiiaz`El2gi>o|bjUOT)(-_jRVql7j)ghbYFWRKMkOLqaUL|h zh@!EK@=Tk^$iC2Z9OPM{L?MSN&`p`$G|N>RA{`Y8h{DLcjge+5Pei|p$}~lKkxsO7 ztm-r`S0h>X0VUfARhbn=)uLAYNXxNmsc89?XmRB!zxFesEvh3m5f&+l`AF| z@j%ul7!{~#tZWsPtWg!io)9NRppt%IYMGfJ&e4^wi`Pw5niZKrJFQc>qKY7v@j$hi zWu8gBSK6p$nm(pwE%UtHjy{K8#3qaVfIX=((exM%1B-kzN&eTvZ!2}#2TE1}r`oE` zsKSX#(GwXu-Skzm$|zArX6@FZtVm0tjlC?Y7!3uQ&@XUb^2oH?8{;y{9%8LTve2tI zfF|#m5j=4<646}x=0M`I&_)&};Q9Ae-CZr~r0v@6l;6v^WQAt~=hJe{ek|2BJVkrk zhiceE6-V%JE#t%EN63fgPke!IK=NZJmcT1W^0a?|l0jm+u`j_MS^GZ7c@S42>CeaN zG?Y(0dkOX?Y_4a%%do$*{G*VcBmb|~egbkEI0_%;J_hVS{}|vyLHkYUHvm3h$AOE$ zCP>;`KL_qAl0o2~DIvZAw{7iXu+PKZfz5c#@fq;DwOM}+><2-P_9<{r!r&vuxphE6 z;R8wjJa7><^OL{M{7@L5dAtmzk~Fjf`13WSTF6L;J?q>T)z$C9*=(y I{2`D33)!HXn*aa+ literal 1124 zcmcgrJ&P1U5G~g|&u>9I3>Lw!K;(8hQ4j<{jzupJ6g}8%>7A+D9hvDFrhArC*g()& z#pFPYlm^b~ZUR7;%_s+dLgXJHuX1_j7t~}x4 z*Q@N?_N#K9LDvCxDuIzx|49q4$rRXGeDD z)pc<*f4i5o5^S}DHJ5<|q8|ekAbVY`SJ|KVOF(mAqDlU7pluTS+q%e<9^FpI_ZQvI zm})mAl^Um5-Ob7(WOXBUH_NfIS&`YP)#Hb1X2UGvewgPj%Mz;w8;*^QGou_^r)gK@uA# zqf-v7pQpbbC;VSWbPq7$pSc<@!bryHgr=6oa({_rNOK-PO7ctxu^l|3{y_W=)H>j zUd46FwacgQ9AvHbFJPV5kn27T457crD*k!kHT(qt4@v$dkUk)~d|{iw<=Wp5UI2rZ t{}y}=kX*r2fZ@yES@Iu&&jCDMUjmVs^p{WX9QYQ{)L#RC2jKDbzX8J~&hr2O diff --git a/Extension/test/scenarios/CppModulesProject/tests/modules.integration.test.ts b/Extension/test/scenarios/CppModulesProject/tests/modules.integration.test.ts index 616946b92..2462adc4d 100644 --- a/Extension/test/scenarios/CppModulesProject/tests/modules.integration.test.ts +++ b/Extension/test/scenarios/CppModulesProject/tests/modules.integration.test.ts @@ -224,22 +224,52 @@ function moduleFilesDir(): string { return toPosixPath(`${workspacePath()}/moduleFiles`); } +// The directory into which the module interface compiler generates the module +// interface files (also the directory named by +// "C_Cpp.intelliSenseModuleSearchPath"). +function generatedModulesDir(): string { + return toPosixPath(`${workspacePath()}/generatedModules`); +} + +// Write the fake module interface "compiler": a script that produces the +// checked-in .eifc module interface files in its working directory (which the +// extension sets to the module search path directory). The real feature +// invokes an "eccp" command built from the open-source EDG front end; the +// fake stands in for it so that the orchestration (detection, generation, +// environment, and import resolution) is exercised end to end in CI. +async function writeFakeModuleCompiler(): Promise { + const fixturesDir: string = moduleFilesDir(); + const scriptPath: string = path.join(workspacePath(), 'build', process.platform === 'win32' ? 'fakeModuleCompiler.cmd' : 'fakeModuleCompiler.sh'); + if (process.platform === 'win32') { + await util.writeFileText(scriptPath, `@echo off\r\ncopy /Y "${fixturesDir}\\*.eifc" "%CD%\\" >nul\r\n`); + } else { + await util.writeFileText(scriptPath, `#!/bin/sh\ncp "${fixturesDir}"/*.eifc "$PWD/"\n`); + await util.chmodAsync(scriptPath, '755'); + } + return scriptPath; +} + /* **************************************************************************** */ // This suite runs first, before any other suite has opened a file: the module // search path setting is only read when the language server is started (the // language server process is spawned on the first opened C++ file), so the // workspace settings file has to be in place before then. -suite("module import resolution through C_Cpp.intelliSenseModuleSearchPath", function(): void { +suite("module import resolution through C_Cpp.intelliSenseModuleCompilerPath", function(): void { let cpptools: apit.CppToolsTestApi; const disposables: vscode.Disposable[] = []; suiteSetup(async function(): Promise { - // Write the workspace setting that feeds the module interface file - // search directory to the IntelliSense engine, then wait for VS Code - // to pick up the settings file before any file is opened. + // Write the fake module interface compiler and the workspace settings + // that configure module interface file generation and the module + // search path, then wait for VS Code to pick up the settings file + // before any file is opened. + const compilerPath: string = await writeFakeModuleCompiler(); await util.writeFileText(path.join(workspacePath(), '.vscode', 'settings.json'), - JSON.stringify({ "C_Cpp.intelliSenseModuleSearchPath": moduleFilesDir() })); + JSON.stringify({ + "C_Cpp.intelliSenseModuleCompilerPath": compilerPath, + "C_Cpp.intelliSenseModuleSearchPath": generatedModulesDir() + })); await testHelpers.delay(4000); cpptools = await apit.getCppToolsTestApi(api.Version.v2) ?? assert.fail('Could not get CppToolsTestApi'); @@ -272,7 +302,15 @@ suite("module import resolution through C_Cpp.intelliSenseModuleSearchPath", fun await util.deleteFile(path.join(workspacePath(), '.vscode', 'settings.json')); }); - test("module imports resolve through the module search path (main.cpp)", async function(): Promise { + test("module interface files are generated and module imports resolve (main.cpp)", async function(): Promise { + // The module interface files for the workspace's module interface + // units (math.cppm, math.ixx) were generated into the module search + // path directory when the language server was started. + const mathModuleFile: string = path.join(generatedModulesDir(), "math.eifc"); + const geometryModuleFile: string = path.join(generatedModulesDir(), "geometry.eifc"); + assert.ok(util.checkFileExistsSync(mathModuleFile), `expected generated module interface file: ${mathModuleFile}`); + assert.ok(util.checkFileExistsSync(geometryModuleFile), `expected generated module interface file: ${geometryModuleFile}`); + const document: vscode.TextDocument = await openAndAwaitIntelliSenseReady(cpptools, disposables, "main.cpp"); // Verify that the compile_commands.json entry for this file was @@ -294,8 +332,12 @@ suite("module import resolution through C_Cpp.intelliSenseModuleSearchPath", fun } // The module interface files were found and imported: the entities - // exported by the imported modules are visible to IntelliSense. + // exported by the imported modules are visible to IntelliSense, + // including variables exported from inside a namespace (which + // requires the variable support of the module interface file + // format; see edgcpp/compiler#58 and edgcpp/compiler#631). await assertHoverResolves(document, "return add(1, 2) + square_area(3) - math::k_answer;", "add"); + await assertHoverResolves(document, "return add(1, 2) + square_area(3) - math::k_answer;", "k_answer"); }); }); diff --git a/Extension/test/unit/moduleInterfaceCompiler.test.ts b/Extension/test/unit/moduleInterfaceCompiler.test.ts new file mode 100644 index 000000000..ca4d07689 --- /dev/null +++ b/Extension/test/unit/moduleInterfaceCompiler.test.ts @@ -0,0 +1,117 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All Rights Reserved. + * See 'LICENSE' in the project root for license information. + * ------------------------------------------------------------------------------------------ */ + +import { strictEqual } from 'node:assert'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, describe, it } from 'mocha'; +import { getEdgStandardArgs, isModuleInterfaceFileName, moduleFileNeedsRegeneration, parseModuleName } from '../../src/LanguageServer/moduleInterfaceCompiler'; + +// Temp directories created during the tests. +const tempDirs: string[] = []; + +function makeTempDir(): string { + const dir: string = fs.mkdtempSync(path.join(os.tmpdir(), "cpptools-modules-test-")); + tempDirs.push(dir); + return dir; +} + +afterEach(() => { + while (tempDirs.length > 0) { + const dir: string | undefined = tempDirs.pop(); + if (dir) { + fs.rmSync(dir, { recursive: true, force: true }); + } + } +}); + +describe('module interface file name detection', () => { + it('recognizes module interface extensions', () => { + strictEqual(isModuleInterfaceFileName("math.cppm"), true); + strictEqual(isModuleInterfaceFileName("math.ixx"), true); + strictEqual(isModuleInterfaceFileName("math.ccm"), true); + strictEqual(isModuleInterfaceFileName("math.CPPM"), true); + }); + + it('rejects non-interface files', () => { + strictEqual(isModuleInterfaceFileName("main.cpp"), false); + strictEqual(isModuleInterfaceFileName("math.h"), false); + strictEqual(isModuleInterfaceFileName("math.cppm.txt"), false); + }); +}); + +describe('module name parsing', () => { + it('parses a simple module declaration', () => { + strictEqual(parseModuleName("export module math;\nexport int add(int a, int b);"), "math"); + }); + + it('parses a module declaration with a partition', () => { + strictEqual(parseModuleName("export module math:parts;\n"), "math-parts"); + }); + + it('parses a dotted module name', () => { + strictEqual(parseModuleName("export module std.io;\n"), "std.io"); + }); + + it('finds the declaration after other declarations', () => { + strictEqual(parseModuleName("#define X 1\n\nexport module geometry;\n"), "geometry"); + }); + + it('returns undefined without a module declaration', () => { + strictEqual(parseModuleName("int main() { return 0; }"), undefined); + strictEqual(parseModuleName("module math; // implementation unit, not an interface"), undefined); + }); +}); + +describe('module compiler standard arguments', () => { + it('maps the workspace C++ standard', () => { + strictEqual(getEdgStandardArgs("c++20").join(" "), "--c++20"); + strictEqual(getEdgStandardArgs("c++23").join(" "), "--c++23"); + strictEqual(getEdgStandardArgs("c++26").join(" "), "--c++26"); + }); + + it('defaults to C++20 (modules require C++20 or later)', () => { + strictEqual(getEdgStandardArgs(undefined).join(" "), "--c++20"); + strictEqual(getEdgStandardArgs("c++17").join(" "), "--c++20"); + }); +}); + +describe('module file regeneration check', () => { + it('regenerates when the module interface file is missing', async () => { + const dir: string = makeTempDir(); + const source: string = path.join(dir, "math.cppm"); + fs.writeFileSync(source, "export module math;\n"); + strictEqual(await moduleFileNeedsRegeneration(source, dir), true); + }); + + it('skips when the module interface file is up to date', async () => { + const dir: string = makeTempDir(); + const source: string = path.join(dir, "math.cppm"); + const moduleFile: string = path.join(dir, "math.eifc"); + fs.writeFileSync(source, "export module math;\n"); + // Write the module interface file after the source. + await new Promise(r => setTimeout(r, 10)); + fs.writeFileSync(moduleFile, "ifc"); + strictEqual(await moduleFileNeedsRegeneration(source, dir), false); + }); + + it('regenerates when the source is newer than the module interface file', async () => { + const dir: string = makeTempDir(); + const source: string = path.join(dir, "math.cppm"); + const moduleFile: string = path.join(dir, "math.eifc"); + fs.writeFileSync(moduleFile, "ifc"); + await new Promise(r => setTimeout(r, 10)); + fs.writeFileSync(source, "export module math;\n"); + strictEqual(await moduleFileNeedsRegeneration(source, dir), true); + }); + + it('regenerates when the module name cannot be determined', async () => { + const dir: string = makeTempDir(); + const source: string = path.join(dir, "empty.cppm"); + fs.writeFileSync(source, "\n"); + strictEqual(await moduleFileNeedsRegeneration(source, dir), true); + }); +}); diff --git a/Extension/test/unit/moduleSearchPath.test.ts b/Extension/test/unit/moduleSearchPath.test.ts index 87a469672..b0a999aca 100644 --- a/Extension/test/unit/moduleSearchPath.test.ts +++ b/Extension/test/unit/moduleSearchPath.test.ts @@ -5,7 +5,7 @@ import { deepStrictEqual, strictEqual } from 'node:assert'; import { describe, it } from 'mocha'; -import { getModuleSearchPathServerEnv, moduleSearchPathEnvVar, resolveModuleSearchPath } from '../../src/LanguageServer/moduleSearchPath'; +import { getDefaultCacheRoot, getModuleFilesTargetDir, getModuleSearchPathServerEnv, moduleSearchPathEnvVar, resolveModuleSearchPath, workspaceCacheSubdirName } from '../../src/LanguageServer/moduleSearchPath'; describe('module search path env', () => { it('undefined setting yields undefined env', () => { @@ -41,3 +41,42 @@ describe('module search path env', () => { strictEqual(moduleSearchPathEnvVar, "EDG_MODULES_PATH"); }); }); + +describe('module files target directory', () => { + it('the search path setting takes precedence', () => { + strictEqual(getModuleFilesTargetDir("/modules/ifc", "/project"), "/modules/ifc"); + }); + + it('the search path setting resolves the workspaceFolder variable', () => { + strictEqual(getModuleFilesTargetDir("${workspaceFolder}/build/ifc", "/project"), "/project/build/ifc"); + }); + + it('without the setting, a per-workspace cache directory is used', () => { + const targetDir: string | undefined = getModuleFilesTargetDir(undefined, "/project"); + if (targetDir) { // undefined only without a workspace folder + strictEqual(targetDir.includes("moduleFiles"), true); + strictEqual(targetDir.includes(workspaceCacheSubdirName("/project")), true); + strictEqual(targetDir.startsWith(getDefaultCacheRoot()), true); + } else { + throw new Error("expected a target directory"); + } + }); + + it('without a setting and without a workspace folder there is no target directory', () => { + strictEqual(getModuleFilesTargetDir(undefined, undefined), undefined); + }); + + it('workspace cache subdirectory names are stable and distinct', () => { + strictEqual(workspaceCacheSubdirName("/project"), workspaceCacheSubdirName("/project/")); + if (workspaceCacheSubdirName("/project") !== workspaceCacheSubdirName("/other")) { + // Distinct folders must map to distinct directories. + } else { + throw new Error("expected distinct cache subdirectory names"); + } + }); + + it('the default cache root ends with the extension cache directory', () => { + const root: string = getDefaultCacheRoot(); + strictEqual(root.endsWith("vscode-cpptools"), true); + }); +});