Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions Extension/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down
4 changes: 4 additions & 0 deletions Extension/package.nls.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": [
Expand Down
40 changes: 38 additions & 2 deletions Extension/src/LanguageServer/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 "<dir>/<sanitizer>.<pid>" files.
/** Find the module interface units of the workspace (by file extension). */
async function findModuleInterfaceFiles(): Promise<string[]> {
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) {
Expand Down
205 changes: 205 additions & 0 deletions Extension/src/LanguageServer/moduleInterfaceCompiler.ts
Original file line number Diff line number Diff line change
@@ -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
// "<module>-<partition>".
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<boolean> {
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<ModuleFileGenerationResult> {

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<CompilerInvocationResult> {
return new Promise<CompilerInvocationResult>((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<typeof spawn>;
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 });
}
});
});
}
Loading