diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index a3fb97da5a..e84b54369e 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -115,6 +115,31 @@ pub struct Project { pub light: bool, } +/// clangd reads the active CMake profile's `compile_commands.json`, as CLion's code insight follows +/// its profile switcher, instead of one it would find by itself in a parent folder or its `build/` +/// (another profile's, or a stale one). Left alone: an explicit `--compile-commands-dir`, a +/// `compile_commands.json` at the project root or a `.clangd` naming a `CompilationDatabase` (the +/// user chose), and a build directory not configured yet (clangd searches as usual meanwhile; the +/// window restarts it once the profile is configured). +fn configure_clangd_database( + cfg: &mut ide_language::LanguageServerConfig, + root: &Path, + settings: &ide_core::settings::Settings, +) { + if cfg.name != "clangd" || cfg.args.iter().any(|a| a.starts_with("--compile-commands-dir")) { + return; + } + let chosen = root.join("compile_commands.json").is_file() + || std::fs::read_to_string(root.join(".clangd")).is_ok_and(|t| t.contains("CompilationDatabase")); + if chosen { + return; + } + let Some(dir) = ide_run::cmake_active_build_dir(root, &settings.cmake, &settings.toolchains) else { return }; + if dir.join("compile_commands.json").is_file() { + cfg.args.push(format!("--compile-commands-dir={}", dir.display())); + } +} + /// Selects the same managed Vue executable for Volar and the vtsls companion plugin. fn configure_vue_release(settings: &mut ide_core::settings::Settings, project_root: &Path, app_data: &Path) { let name = ide_tools::vue::SERVER; @@ -269,6 +294,7 @@ impl Host { } ide_sdk::apply::server_launch_overrides(cfg, &effective); ide_sdk::apply::configure_server(cfg, root, server_root, &effective); + configure_clangd_database(cfg, root, &effective); ide_sdk::json_schemas::configure(cfg, root, &effective.json_schemas); crate::ts_code_style::configure(cfg, server_root, &effective); crate::ts_code_style::configure_inlay_hints(cfg, &effective); @@ -3309,6 +3335,56 @@ mod workspace_edit_tests { } } +#[cfg(test)] +mod clangd_database_tests { + use super::configure_clangd_database; + use ide_core::settings::{CMakeProfile, Settings}; + + fn clangd(args: &[&str]) -> ide_language::LanguageServerConfig { + let mut cfg: ide_language::LanguageServerConfig = + toml::from_str("name = 'clangd'\ncommand = 'clangd'").unwrap(); + cfg.args = args.iter().map(|a| (*a).to_owned()).collect(); + cfg + } + + #[test] + fn clangd_reads_the_active_profiles_compilation_database() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let mut settings = Settings::default(); + settings.cmake.profiles = + Some(vec![CMakeProfile { name: "Debug".into(), build_type: "Debug".into(), ..Default::default() }]); + let args = |settings: &Settings, cfg: ide_language::LanguageServerConfig| { + let mut cfg = cfg; + configure_clangd_database(&mut cfg, root, settings); + cfg.args + }; + // Not configured yet: clangd searches by itself. + assert_eq!(args(&settings, clangd(&["--background-index"])), ["--background-index"]); + let build = root.join("cmake-build-debug"); + std::fs::create_dir_all(&build).unwrap(); + std::fs::write(build.join("compile_commands.json"), "[]").unwrap(); + assert_eq!( + args(&settings, clangd(&["--background-index"])), + ["--background-index".to_owned(), format!("--compile-commands-dir={}", build.display())] + ); + // What the user chose stays: an explicit flag, a .clangd naming a database, a root database. + assert_eq!(args(&settings, clangd(&["--compile-commands-dir=x"])), ["--compile-commands-dir=x"]); + std::fs::write(root.join(".clangd"), "CompileFlags:\n CompilationDatabase: out\n").unwrap(); + assert!(args(&settings, clangd(&[])).is_empty()); + std::fs::remove_file(root.join(".clangd")).unwrap(); + std::fs::write(root.join("compile_commands.json"), "[]").unwrap(); + assert!(args(&settings, clangd(&[])).is_empty()); + std::fs::remove_file(root.join("compile_commands.json")).unwrap(); + // Other servers, and projects without profiles, are not touched. + let mut other = clangd(&[]); + other.name = "ccls".into(); + configure_clangd_database(&mut other, root, &settings); + assert!(other.args.is_empty()); + assert!(args(&Settings::default(), clangd(&[])).is_empty()); + } +} + #[cfg(test)] mod agent_worktree_tests { use super::agent_worktrees_dir; diff --git a/crates/ide-run/src/detect/cmake/mod.rs b/crates/ide-run/src/detect/cmake/mod.rs index 00f3cf5835..c889f4f44e 100644 --- a/crates/ide-run/src/detect/cmake/mod.rs +++ b/crates/ide-run/src/detect/cmake/mod.rs @@ -273,6 +273,23 @@ pub(crate) fn refresh_saved(saved: &mut RunConfig, detected: &RunConfig) { /// A profile's build directory when it names none, as CLion: `cmake-build-debug`, or /// `cmake-build-default` for the "Default" (empty) build type. +/// The build directory of the active CMake profile (or enabled preset), absolute: where its +/// `compile_commands.json` is. `None` without saved profiles or enabled presets (the automatic +/// discovery of configured build directories has no active one). +pub fn active_build_dir( + root: &Path, + settings: &ide_core::settings::CMakeSettings, + toolchains: &[ide_core::settings::Toolchain], +) -> Option { + let profile = presets::profiles(root, settings, toolchains)?.into_iter().next()?; + let dir = if profile.build_dir.trim().is_empty() { + default_build_dir(&profile.build_type) + } else { + profile.build_dir.clone() + }; + Some(root.join(dir)) +} + pub fn default_build_dir(build_type: &str) -> String { let build_type = if build_type.is_empty() { "default".to_owned() } else { build_type.to_lowercase() }; format!("cmake-build-{build_type}") @@ -430,6 +447,34 @@ mod tests { use super::*; use serde_json::Value; + #[test] + fn the_active_profile_names_the_build_directory_clangd_reads() { + let root = tempfile::tempdir().unwrap(); + let root = root.path(); + let profile = |name: &str, build_type: &str, build_dir: &str| CMakeProfile { + name: name.into(), + build_type: build_type.into(), + build_dir: build_dir.into(), + ..Default::default() + }; + // Automatic discovery: no active profile. + let mut settings = ide_core::settings::CMakeSettings::default(); + assert_eq!(active_build_dir(root, &settings, &[]), None); + settings.profiles = Some(vec![profile("Debug", "Debug", ""), profile("Release", "Release", "out/release")]); + assert_eq!(active_build_dir(root, &settings, &[]), Some(root.join("cmake-build-debug"))); + settings.active_profile = "Release".into(); + assert_eq!(active_build_dir(root, &settings, &[]), Some(root.join("out/release"))); + // An enabled preset: its binaryDir. + fs::write( + root.join("CMakePresets.json"), + r#"{"version": 3, "configurePresets": [{"name": "dev", "binaryDir": "${sourceDir}/build/${presetName}"}]}"#, + ) + .unwrap(); + let presets = ide_core::settings::CMakeSettings { enabled_presets: vec!["dev".into()], ..Default::default() }; + let dir = active_build_dir(root, &presets, &[]).unwrap(); + assert!(dir.ends_with("build/dev"), "{}", dir.display()); + } + #[test] fn profiles_select_file_api_configuration_and_apply_target_options() { let root = tempfile::tempdir().unwrap(); diff --git a/crates/ide-run/src/lib.rs b/crates/ide-run/src/lib.rs index 4ee3fa0bba..b03d4b5e2f 100644 --- a/crates/ide-run/src/lib.rs +++ b/crates/ide-run/src/lib.rs @@ -26,6 +26,7 @@ pub mod xcode; pub mod xcode_clean; pub mod xcode_index; +pub use detect::cmake::active_build_dir as cmake_active_build_dir; pub use detect::cmake::cache as cmake_cache; pub use detect::cmake::presets::{listed as cmake_listed_profiles, load as cmake_presets, profiles as cmake_profiles}; pub use detect::cmake::toolchain as cmake_toolchain; diff --git a/docs/en/languages/cpp.mdx b/docs/en/languages/cpp.mdx index fe5ca48c2f..087275ea5d 100644 --- a/docs/en/languages/cpp.mdx +++ b/docs/en/languages/cpp.mdx @@ -31,7 +31,7 @@ clangd needs the flags each file is compiled with. Without them it guesses, and - **`.clangd`**: clangd's own configuration file, for example to point `CompilationDatabase` at a build directory. -clangd looks for `compile_commands.json` in the file's parent directories and in a `build/` subdirectory of each. If your build directory has another name (for example `cmake-build-debug` from a CMake profile), add a `.clangd` file with `CompileFlags: { CompilationDatabase: cmake-build-debug }` or copy or link the file to the project root. +With CMake profiles or enabled presets, clangd reads the **active profile's** `compile_commands.json`: OpenIDEA starts it with `--compile-commands-dir` set to that profile's build directory, and restarts it when you choose another profile in the title bar, or once the active profile's directory is configured for the first time. A `compile_commands.json` at the project root, a `.clangd` file naming a `CompilationDatabase`, or a `--compile-commands-dir` in the server's arguments take precedence. Otherwise clangd looks for `compile_commands.json` in the file's parent directories and in a `build/` subdirectory of each; for another directory, add a `.clangd` file with `CompileFlags: { CompilationDatabase: }`. ### Xcode projects diff --git a/docs/zh/languages/cpp.mdx b/docs/zh/languages/cpp.mdx index 713158d65e..404004c2b8 100644 --- a/docs/zh/languages/cpp.mdx +++ b/docs/zh/languages/cpp.mdx @@ -31,7 +31,7 @@ clangd 需要知道每个文件的编译参数,否则只能猜测,常见的 - **`.clangd`**:clangd 自己的配置文件,例如用 `CompilationDatabase` 指向某个构建目录。 -clangd 会在文件的各级父目录以及这些目录下的 `build/` 子目录里查找 `compile_commands.json`。如果构建目录叫别的名字(例如 CMake 配置生成的 `cmake-build-debug`),在项目根目录添加一个 `.clangd`,写上 `CompileFlags: { CompilationDatabase: cmake-build-debug }`,或者把该文件复制或链接到项目根目录。 +使用 CMake 配置或启用的预设时,clangd 读取**当前配置**的 `compile_commands.json`:OpenIDEA 启动 clangd 时把 `--compile-commands-dir` 设为该配置的构建目录,并在标题栏切换配置或当前配置的目录首次完成配置后重启 clangd。项目根目录下的 `compile_commands.json`、指定了 `CompilationDatabase` 的 `.clangd` 文件或服务器参数中的 `--compile-commands-dir` 优先。其他情况下,clangd 会在文件的各级父目录以及这些目录下的 `build/` 子目录里查找 `compile_commands.json`;如需使用其他目录,添加一个 `.clangd` 文件,写上 `CompileFlags: { CompilationDatabase: <目录> }`。 ### Xcode 项目 diff --git a/src/features/run/clangdDatabase.test.ts b/src/features/run/clangdDatabase.test.ts new file mode 100644 index 0000000000..4108f87d65 --- /dev/null +++ b/src/features/run/clangdDatabase.test.ts @@ -0,0 +1,60 @@ +import { afterEach, expect, it, vi } from "vitest"; +import type { RunConfig } from "@/platform/ipc"; +import { activeCMakeBuildDir, syncClangdDatabase } from "./clangdDatabase"; +import { resetRuns, useRun } from "./store"; + +const configure = (buildDir: string, params: Record = {}): RunConfig => ({ + id: "cmake:profile:configure", + name: "CMake Configure", + kind: "cmake", + command: "cmake", + args: ["--preset", "dev"], + cwd: null, + env: {}, + detected: true, + isTest: false, + debugAdapter: null, + params: { buildDir, cmakeProfile: "dev", ...params }, +}); + +afterEach(() => resetRuns()); + +it("names the active profile's build directory, not an automatically discovered one's", () => { + expect(activeCMakeBuildDir([configure("build/dev")])).toBe("build/dev"); + const discovered = { ...configure("build"), params: { buildDir: "build" } }; + expect(activeCMakeBuildDir([discovered])).toBeNull(); + expect(activeCMakeBuildDir([])).toBeNull(); +}); + +it("restarts clangd when another profile becomes active, or once the active one is first configured", () => { + const restart = vi.fn(async () => {}); + const stop = syncClangdDatabase(restart); + // The first load: clangd started with this directory already. + useRun.setState({ configs: [configure("build/dev")] }); + expect(restart).not.toHaveBeenCalled(); + useRun.setState({ configs: [configure("build/dev")] }); + expect(restart).not.toHaveBeenCalled(); + // Another profile. + useRun.setState({ configs: [configure("build/release")] }); + expect(restart).toHaveBeenCalledTimes(1); + + // The active profile's directory is configured for the first time (by the build task that + // reloads the CMake project): the configurations come back without the mark. + useRun.setState({ configs: [configure("build/release", { cmakeNeedsConfigure: "true" })] }); + expect(restart).toHaveBeenCalledTimes(1); + useRun.setState({ configs: [configure("build/release", { cmakeNeedsConfigure: "true" })] }); + expect(restart).toHaveBeenCalledTimes(1); + useRun.setState({ configs: [configure("build/release")] }); + expect(restart).toHaveBeenCalledTimes(2); + useRun.setState({ configs: [configure("build/release")] }); + expect(restart).toHaveBeenCalledTimes(2); + // A first profile, configured by the IDE once it appears. + useRun.setState({ configs: [] }); + useRun.setState({ configs: [configure("build/debug", { cmakeNeedsConfigure: "true" })] }); + useRun.setState({ configs: [configure("build/debug")] }); + expect(restart).toHaveBeenCalledTimes(3); + + stop(); + useRun.setState({ configs: [configure("build/dev")] }); + expect(restart).toHaveBeenCalledTimes(3); +}); diff --git a/src/features/run/clangdDatabase.ts b/src/features/run/clangdDatabase.ts new file mode 100644 index 0000000000..3ce2945b06 --- /dev/null +++ b/src/features/run/clangdDatabase.ts @@ -0,0 +1,47 @@ +/** + * clangd reads the active CMake profile's `compile_commands.json`: the backend passes its build + * directory when clangd starts (`--compile-commands-dir`, once that directory is configured). + * Choosing another profile, or a first successful configure of the active one, restarts this + * project's clangd so that it reads the right database. + */ +import { call, commands, type RunConfig } from "@/platform/ipc"; +import { NEEDS_CONFIGURE } from "./cmake"; +import { useRun } from "./store"; + +const isConfigure = (c: RunConfig) => c.kind === "cmake" && ["-S", "--preset"].includes(c.args[0] ?? ""); + +/** The active profile's configure configuration (`cmakeProfile` marks a profile's). */ +const activeConfigure = (configs: readonly RunConfig[]) => configs.find((c) => isConfigure(c) && c.params?.cmakeProfile); + +/** The active profile's build directory: its configure configuration's. */ +export function activeCMakeBuildDir(configs: readonly RunConfig[]): string | null { + return activeConfigure(configs)?.params?.buildDir ?? null; +} + +const needsConfigure = (configs: readonly RunConfig[]) => + activeConfigure(configs)?.params?.[NEEDS_CONFIGURE] === "true"; + +async function restartClangd() { + const servers = await call(commands.lspServers()).catch(() => []); + await Promise.all( + servers.filter((s) => s.name === "clangd").map((s) => call(commands.lspRestart(s.id)).catch(() => {})), + ); +} + +export function syncClangdDatabase(restart: () => Promise = restartClangd): () => void { + let active = activeCMakeBuildDir(useRun.getState().configs); + let unconfigured = needsConfigure(useRun.getState().configs); + return useRun.subscribe((s, prev) => { + if (s.configs === prev.configs) return; + const now = activeCMakeBuildDir(s.configs); + const needs = needsConfigure(s.configs); + // The first load names the directory clangd already started with: only a switch restarts it. + const switched = active !== null && now !== null && now !== active; + // The directory had never been configured, so clangd started without its database. The + // configure runs as a build task, not a run session: the configurations reload without the mark. + const configured = now !== null && now === active && unconfigured && !needs; + active = now; + unconfigured = needs; + if (switched || configured) void restart(); + }); +} diff --git a/src/features/run/index.ts b/src/features/run/index.ts index 174295947f..415206997e 100644 --- a/src/features/run/index.ts +++ b/src/features/run/index.ts @@ -95,6 +95,7 @@ import { selectCMakeProfile, toggleCMakeProfiles } from "./CMakeProfileChooser"; import { cmakeConfigureConfigs, reloadCMakeProject, reloadCMakeProjects } from "./cmake"; import { registerXcodeCleanActions } from "./xcodeClean"; import { npmGutter } from "./npmGutter"; +import { syncClangdDatabase } from "./clangdDatabase"; import { launchSettingsGutter } from "./launchSettingsGutter"; import { runGutter } from "./runGutter"; import { markdownCommandGutter } from "./markdownCommands"; @@ -562,6 +563,7 @@ export function activate(): () => void { registerRunTabActions(), registerComposerInstall(), registerNpmInstall(), + syncClangdDatabase(), registerXcodeFiles(), registerPubspecCommands(), registerOverlay({ id: "run.chooser", component: ConfigChooserOverlay }),