diff --git a/Extension/package.json b/Extension/package.json
index ab1d9ee16..95502aada 100644
--- a/Extension/package.json
+++ b/Extension/package.json
@@ -993,6 +993,18 @@
"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.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 fa9fa84e8..fd8a9a505 100644
--- a/Extension/package.nls.json
+++ b/Extension/package.nls.json
@@ -623,6 +623,10 @@
]
},
"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 b370188f7..29c080891 100644
--- a/Extension/src/LanguageServer/client.ts
+++ b/Extension/src/LanguageServer/client.ts
@@ -58,6 +58,8 @@ import { CppSourceStr, clients, configPrefix, initializeIntervalTimer, isWriting
import { IncludeCleanupPreferences, getIncludeCleanupPreferences } from './includeCleanupEditorConfig';
import { InactiveRegion, InactiveRegionStore, getInactiveRegionStartLines } from './inactiveRegions';
import { LanguageClient } from './languageClient';
+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';
@@ -1654,9 +1656,37 @@ 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();
+ // 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 };
+ }
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
@@ -4490,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
new file mode 100644
index 000000000..0246b2522
--- /dev/null
+++ b/Extension/src/LanguageServer/moduleSearchPath.ts
@@ -0,0 +1,110 @@
+/* --------------------------------------------------------------------------------------------
+ * Copyright (c) Microsoft Corporation. All Rights Reserved.
+ * 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.
+ *
+ * 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.
+ *
+ * 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.
+ */
+
+/** 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 };
+}
+
+/**
+ * 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 3003b9ebf..2f45ac325 100644
--- a/Extension/src/LanguageServer/settings.ts
+++ b/Extension/src/LanguageServer/settings.ts
@@ -424,6 +424,8 @@ 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 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
new file mode 100644
index 000000000..3498c230e
Binary files /dev/null and b/Extension/test/scenarios/CppModulesProject/assets/moduleFiles/geometry.eifc differ
diff --git a/Extension/test/scenarios/CppModulesProject/assets/moduleFiles/math.eifc b/Extension/test/scenarios/CppModulesProject/assets/moduleFiles/math.eifc
new file mode 100644
index 000000000..5fc1d9fc1
Binary files /dev/null and b/Extension/test/scenarios/CppModulesProject/assets/moduleFiles/math.eifc differ
diff --git a/Extension/test/scenarios/CppModulesProject/tests/modules.integration.test.ts b/Extension/test/scenarios/CppModulesProject/tests/modules.integration.test.ts
index e795d3a52..2462adc4d 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,134 @@ 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`);
+}
+
+// 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.intelliSenseModuleCompilerPath", function(): void {
+ let cpptools: apit.CppToolsTestApi;
+ const disposables: vscode.Disposable[] = [];
+
+ suiteSetup(async function(): Promise {
+ // 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.intelliSenseModuleCompilerPath": compilerPath,
+ "C_Cpp.intelliSenseModuleSearchPath": generatedModulesDir()
+ }));
+ 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 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
+ // 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,
+ // 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");
+ });
+});
+
+/* **************************************************************************** */
+
suite("C++20 modules file type tests", function(): void {
suiteSetup(async function(): Promise {
await testHelpers.activateCppExtension();
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
new file mode 100644
index 000000000..b0a999aca
--- /dev/null
+++ b/Extension/test/unit/moduleSearchPath.test.ts
@@ -0,0 +1,82 @@
+/* --------------------------------------------------------------------------------------------
+ * 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 { getDefaultCacheRoot, getModuleFilesTargetDir, getModuleSearchPathServerEnv, moduleSearchPathEnvVar, resolveModuleSearchPath, workspaceCacheSubdirName } 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");
+ });
+});
+
+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);
+ });
+});