Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

fix(cpp): run CMake targets and rename through file aliases once (#539)

l0ng-ai1e8551ad0bb4
diff --git a/Cargo.lock b/Cargo.lock
index 94b708920..004622c25 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4366,6 +4366,7 @@ dependencies = [
name = "ide-lsp"
version = "0.1.29"
dependencies = [
+ "dunce",
"futures",
"globset",
"ide-core",
@@ -4460,6 +4461,7 @@ dependencies = [
name = "ide-run"
version = "0.1.29"
dependencies = [
+ "dunce",
"encoding_rs",
"ide-build",
"ide-core",
diff --git a/crates/ide-core/src/text.rs b/crates/ide-core/src/text.rs
index 9f96ff766..456481283 100644
--- a/crates/ide-core/src/text.rs
+++ b/crates/ide-core/src/text.rs
@@ -99,6 +99,44 @@ pub struct WorkspaceEdit {
pub files: Vec<FileEdit>,
}
+impl WorkspaceEdit {
+ /// Coalesces aliases of the same file before applying edits against its original text.
+ /// Resource operations separate batches because later edits may use the new contents.
+ pub fn deduplicate(&mut self) {
+ let mut files = Vec::new();
+ let mut batch = std::collections::HashMap::<std::path::PathBuf, usize>::new();
+ let mut resolve_aliases = true;
+ for file in std::mem::take(&mut self.files) {
+ match file {
+ FileEdit::Edit { path, edits } => {
+ let path = if resolve_aliases {
+ dunce::canonicalize(&path).unwrap_or_else(|_| path.to_path_buf())
+ } else {
+ path.to_path_buf()
+ };
+ let index = *batch.entry(path.clone()).or_insert_with(|| {
+ files.push(FileEdit::Edit { path: path.into(), edits: Vec::new() });
+ files.len() - 1
+ });
+ let FileEdit::Edit { edits: own, .. } = &mut files[index] else { unreachable!() };
+ for edit in edits {
+ if !own.contains(&edit) {
+ own.push(edit);
+ }
+ }
+ }
+ op => {
+ batch.clear();
+ // Later paths refer to a filesystem state the resource operation has yet to create.
+ resolve_aliases = false;
+ files.push(op);
+ }
+ }
+ }
+ self.files = files;
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum FileEdit {
@@ -203,3 +241,34 @@ pub struct OutlineItem {
/// Fuzzy-match highlight: indices (in chars of the displayed string) that matched.
pub type MatchIndices = Vec<u32>;
+
+#[cfg(all(test, unix))]
+mod workspace_edit_tests {
+ use super::*;
+
+ #[test]
+ fn aliases_are_one_edit_but_resource_operations_preserve_order() {
+ let dir = tempfile::tempdir().unwrap();
+ let real = dir.path().join("main.cpp");
+ let alias = dir.path().join("alias.cpp");
+ std::fs::write(&real, "add()").unwrap();
+ std::os::unix::fs::symlink(&real, &alias).unwrap();
+ let change = TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "sum_values".into() };
+ let edit = |path: PathBuf| FileEdit::Edit { path: path.into(), edits: vec![change.clone()] };
+ let mut workspace = WorkspaceEdit {
+ files: vec![
+ edit(real.clone()),
+ edit(alias),
+ FileEdit::Create { path: dir.path().join("other").into(), overwrite: false },
+ edit(real),
+ ],
+ };
+ workspace.deduplicate();
+ assert_eq!(workspace.files.len(), 3);
+ let FileEdit::Edit { edits, .. } = &workspace.files[0] else { panic!() };
+ assert_eq!(edits, &[change]);
+ let once = workspace.clone();
+ workspace.deduplicate();
+ assert_eq!(workspace, once);
+ }
+}
diff --git a/crates/ide-host/src/ops/run.rs b/crates/ide-host/src/ops/run.rs
index 9f1f4d5f5..7160c3117 100644
--- a/crates/ide-host/src/ops/run.rs
+++ b/crates/ide-host/src/ops/run.rs
@@ -21,6 +21,11 @@ pub fn configs(host: &Host, window: &str) -> IdeResult<Vec<RunConfig>> {
let key = crate::project::project_key(&member);
let name = member.file_name().unwrap_or_default().to_string_lossy();
for mut config in configs {
+ for task in &mut config.extras.before_launch {
+ if task.kind == "run" {
+ task.target = format!("workspace:{}:{}", key, task.target);
+ }
+ }
config.id = format!("workspace:{}:{}", key, config.id);
config.name = format!("{name} / {}", config.name);
config.cwd = Some(config.cwd.map(|p| member.join(&*p)).unwrap_or_else(|| member.clone()).into());
diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs
index 9683307eb..1630411f5 100644
--- a/crates/ide-host/src/project.rs
+++ b/crates/ide-host/src/project.rs
@@ -786,6 +786,8 @@ impl Project {
/// Applies a multi-file edit through the document layer so open editors update live.
pub fn apply_workspace_edit(documents: &Documents, edit: &ide_core::WorkspaceEdit) -> IdeResult<()> {
use ide_core::FileEdit;
+ let mut edit = edit.clone();
+ edit.deduplicate();
for file in &edit.files {
match file {
FileEdit::Edit { path, edits } => {
@@ -1129,3 +1131,28 @@ mod index_event_tests {
assert!(vcs_path_changed(&index));
}
}
+
+#[cfg(all(test, unix))]
+mod workspace_edit_tests {
+ use super::*;
+ use ide_core::{FileEdit, LanguageId, Pos, Range, TextEdit, WorkspaceEdit};
+
+ #[test]
+ fn rename_via_symlink_updates_the_open_document_once() {
+ let dir = tempfile::tempdir().unwrap();
+ let real = dir.path().join("main.cpp");
+ let alias = dir.path().join("alias.cpp");
+ std::fs::write(&real, "add();\n").unwrap();
+ std::os::unix::fs::symlink(&real, &alias).unwrap();
+ let documents = Documents::new(Arc::new(|_: IdeEvent| {}), Box::new(|_, _| LanguageId::new("cpp")));
+ let doc = documents.open(&alias).unwrap();
+ let changes = |path: PathBuf| FileEdit::Edit {
+ path: path.into(),
+ edits: vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), new_text: "sum_values".into() }],
+ };
+ apply_workspace_edit(&documents, &WorkspaceEdit { files: vec![changes(real.clone()), changes(alias)] })
+ .unwrap();
+ assert_eq!(std::fs::read_to_string(real).unwrap(), "sum_values();\n");
+ assert_eq!(documents.snapshot(doc.id).unwrap().text, "sum_values();\n");
+ }
+}
diff --git a/crates/ide-host/tests/run_configs.rs b/crates/ide-host/tests/run_configs.rs
index 4008b0e33..93d3ca5c4 100644
--- a/crates/ide-host/tests/run_configs.rs
+++ b/crates/ide-host/tests/run_configs.rs
@@ -77,3 +77,22 @@ async fn gradle_defaults_are_not_saved_as_explicit_run_choices() {
assert_eq!(saved.env["JAVA_HOME"], "/explicit-jdk");
assert_eq!(saved.command, gradle.command);
}
+
+#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+async fn workspace_cmake_before_launch_tasks_resolve_in_the_member() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = dunce::canonicalize(tmp.path()).unwrap();
+ let member = root.join("native");
+ std::fs::create_dir(&member).unwrap();
+ std::fs::write(member.join("CMakeLists.txt"), "project(demo)").unwrap();
+ let workspace = root.join("workspace");
+ ide_workspace::workspace::Workspace::save(&workspace, "Native", vec![member.clone()], true).unwrap();
+ let host = host(&root.join("app"));
+ host.open_project("main", &workspace).unwrap();
+ let configs = ops::run::configs(&host, "main").unwrap();
+ let build = configs.iter().find(|c| c.kind == "cmake" && c.args.first().is_some_and(|a| a == "--build")).unwrap();
+ assert_eq!(build.cwd.as_deref(), Some(member.as_path()));
+ for task in &build.extras.before_launch {
+ assert!(configs.iter().any(|c| c.id == task.target && c.cwd == build.cwd));
+ }
+}
diff --git a/crates/ide-lsp/Cargo.toml b/crates/ide-lsp/Cargo.toml
index a8d2605fc..8b011c795 100644
--- a/crates/ide-lsp/Cargo.toml
+++ b/crates/ide-lsp/Cargo.toml
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
ide-core.workspace = true
+dunce.workspace = true
ide-text.workspace = true
ide-language.workspace = true
ide-jsonrpc.workspace = true
diff --git a/crates/ide-lsp/src/convert.rs b/crates/ide-lsp/src/convert.rs
index 08032f6ac..2e29724c1 100644
--- a/crates/ide-lsp/src/convert.rs
+++ b/crates/ide-lsp/src/convert.rs
@@ -661,7 +661,9 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
}
}
}
- WorkspaceEdit { files }
+ let mut edit = WorkspaceEdit { files };
+ edit.deduplicate();
+ edit
}
/// Adds the changes of `extra`, another server's edit for the same request, to
@@ -710,6 +712,14 @@ pub fn goto_response(conv: &Conv, r: lsp::GotoDefinitionResponse) -> Vec<Locatio
}
pub fn dedup_locations(v: &mut Vec<Location>) {
+ let mut canonical = std::collections::HashMap::new();
+ for location in v.iter_mut().filter(|l| l.uri.is_none()) {
+ let path =
+ canonical.entry(location.path.clone()).or_insert_with(|| dunce::canonicalize(&location.path).ok()).clone();
+ if let Some(path) = path {
+ location.path = path.into();
+ }
+ }
let mut seen = std::collections::HashSet::new();
v.retain(|l| seen.insert(l.clone()));
}
@@ -1405,3 +1415,24 @@ mod tests {
assert!(document_link(&conv, here, link(None)).is_none());
}
}
+
+#[cfg(all(test, unix))]
+mod alias_tests {
+ use super::*;
+
+ #[test]
+ fn references_to_a_file_and_its_symlink_are_one_location() {
+ let dir = tempfile::tempdir().unwrap();
+ let real = dir.path().join("main.cpp");
+ let alias = dir.path().join("alias.cpp");
+ std::fs::write(&real, "add()").unwrap();
+ std::os::unix::fs::symlink(&real, &alias).unwrap();
+ let mut locations: Vec<Location> = [real.clone(), alias]
+ .into_iter()
+ .map(|p| Location { path: p.into(), range: Range::new(Pos::new(0, 0), Pos::new(0, 3)), uri: None })
+ .collect();
+ dedup_locations(&mut locations);
+ assert_eq!(locations.len(), 1);
+ assert_eq!(locations[0].path.as_ref(), dunce::canonicalize(real).unwrap());
+ }
+}
diff --git a/crates/ide-lsp/src/lib.rs b/crates/ide-lsp/src/lib.rs
index 784675a34..5604023cc 100644
--- a/crates/ide-lsp/src/lib.rs
+++ b/crates/ide-lsp/src/lib.rs
@@ -90,6 +90,8 @@ struct Attached {
struct DocState {
path: PathBuf,
+ /// `path` with links resolved, to recognise a document under another name.
+ canonical: PathBuf,
uri: lsp::Uri,
language: LanguageId,
version: i32,
@@ -685,6 +687,11 @@ impl LspManager {
if let Some(t) = self.docs.lock().values().find(|d| d.path == path).map(|d| d.text.clone()) {
return Some(t);
}
+ if let Ok(key) = dunce::canonicalize(path)
+ && let Some(text) = self.docs.lock().values().find(|d| d.canonical == key).map(|d| d.text.clone())
+ {
+ return Some(text);
+ }
let key = path.to_str().filter(|s| is_virtual_uri(s))?;
self.virtual_docs.lock().get(key).map(|d| Arc::new(DocText::new(&d.text)))
}
@@ -730,8 +737,10 @@ impl LspManager {
text: &str,
servers: Vec<Arc<Server>>,
) {
+ let canonical = dunce::canonicalize(&path).unwrap_or_else(|_| path.clone());
let mut state = DocState {
path,
+ canonical,
uri,
language: language.clone(),
version: version as i32,
diff --git a/crates/ide-lsp/src/scope.rs b/crates/ide-lsp/src/scope.rs
index 237f33f16..bac2188f6 100644
--- a/crates/ide-lsp/src/scope.rs
+++ b/crates/ide-lsp/src/scope.rs
@@ -167,23 +167,27 @@ impl LspManager {
/// readable as text are left out and flagged on the guard.
async fn open_transient(&self, t: &Target, files: Vec<PathBuf>, cancel: &CancellationToken) -> TransientFiles<'_> {
// The server already sees the user's files, however large.
- let open: HashSet<PathBuf> = self.docs.lock().values().map(|d| d.path.clone()).collect();
+ let open: HashSet<PathBuf> = self.docs.lock().values().map(|d| d.canonical.clone()).collect();
let (read, skipped) = {
let cancel = cancel.clone();
tokio::task::spawn_blocking(move || {
let mut read = Vec::new();
let mut skipped = false;
- for f in files.into_iter().filter(|f| !open.contains(f)) {
+ for f in files {
if cancel.is_cancelled() {
break;
}
+ let canonical = dunce::canonicalize(&f).unwrap_or_else(|_| f.clone());
+ if open.contains(&canonical) {
+ continue;
+ }
// A file gone since the search no longer mentions anything.
let Ok(meta) = std::fs::metadata(&f) else { continue };
if !meta.is_file() {
continue;
}
match (meta.len() <= MAX_CANDIDATE_BYTES).then(|| std::fs::read_to_string(&f)) {
- Some(Ok(text)) => read.push((f, text)),
+ Some(Ok(text)) => read.push((f, canonical, text)),
_ => skipped = true,
}
}
@@ -198,8 +202,8 @@ impl LspManager {
return guard;
}
let docs = self.docs.lock();
- for (path, text) in read {
- if docs.values().any(|d| d.path == path) {
+ for (path, canonical, text) in read {
+ if docs.values().any(|d| d.canonical == canonical) {
continue;
}
let uri = crate::uri::path_to_uri(&path);
diff --git a/crates/ide-run/Cargo.toml b/crates/ide-run/Cargo.toml
index 076ad24e7..1e362ef3a 100644
--- a/crates/ide-run/Cargo.toml
+++ b/crates/ide-run/Cargo.toml
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
ide-core.workspace = true
+dunce.workspace = true
encoding_rs.workspace = true
serde.workspace = true
serde_json.workspace = true
diff --git a/crates/ide-run/src/detect.rs b/crates/ide-run/src/detect.rs
index 8c1dd4ce5..939dfc2d1 100644
--- a/crates/ide-run/src/detect.rs
+++ b/crates/ide-run/src/detect.rs
@@ -3,6 +3,8 @@
//!
//! Detection never fails: unreadable or malformed files simply contribute nothing.
+pub(crate) mod cmake;
+
use crate::RunConfig;
use serde_json::Value as Json;
use std::collections::{BTreeMap, HashSet};
@@ -22,6 +24,7 @@ pub(crate) fn detect_excluding(root: &Path, excluded_poms: &[PathBuf]) -> Vec<Ru
detect_maven(root, excluded_poms, &mut out);
detect_go(root, &mut out);
detect_python(root, &mut out);
+ cmake::detect(root, &mut out);
detect_make(root, &mut out);
detect_just(root, &mut out);
detect_godot(root, &mut out);
diff --git a/crates/ide-run/src/detect/cmake.rs b/crates/ide-run/src/detect/cmake.rs
new file mode 100644
index 000000000..2f4b69775
--- /dev/null
+++ b/crates/ide-run/src/detect/cmake.rs
@@ -0,0 +1,173 @@
+//! CMake targets come from the File API codemodel, including evaluated subdirectories.
+
+use super::{ConfigExt, config};
+use crate::{BeforeLaunchTask, RunConfig};
+use serde_json::Value;
+use std::fs;
+use std::path::{Path, PathBuf};
+
+fn json(path: &Path) -> Option<Value> {
+ serde_json::from_slice(&fs::read(path).ok()?).ok()
+}
+
+fn reply_file(reply: &Path, name: &str) -> Option<Value> {
+ // File API references are file names, never paths outside the reply directory.
+ (Path::new(name).components().count() == 1).then(|| json(&reply.join(name))).flatten()
+}
+
+fn before(config: &mut RunConfig, id: &str) {
+ config.extras.before_launch.push(BeforeLaunchTask { kind: "run".into(), target: id.into() });
+}
+
+pub(super) fn detect(root: &Path, out: &mut Vec<RunConfig>) {
+ if !root.join("CMakeLists.txt").is_file() {
+ return;
+ }
+ let mut builds = Vec::new();
+ if let Ok(entries) = fs::read_dir(root) {
+ builds.extend(entries.flatten().filter_map(|e| {
+ let p = e.path();
+ (p.is_dir() && p.join("CMakeCache.txt").is_file()).then_some(p)
+ }));
+ }
+ if builds.is_empty() {
+ builds.push(root.join("build"));
+ }
+ builds.sort();
+ builds.dedup();
+ for build in builds {
+ let dir = build.strip_prefix(root).unwrap_or(&build).to_string_lossy().replace('\\', "/");
+ let configuration = fs::read_to_string(build.join("CMakeCache.txt"))
+ .ok()
+ .and_then(|cache| {
+ let values = cache.lines().find_map(|line| line.strip_prefix("CMAKE_CONFIGURATION_TYPES:STRING="))?;
+ Some(if values.split(';').any(|c| c == "Debug") {
+ "Debug".to_owned()
+ } else {
+ values.split(';').find(|s| !s.is_empty())?.to_owned()
+ })
+ })
+ .unwrap_or_else(|| "Debug".into());
+ let prefix = format!("cmake:{dir}");
+ let configure_id = format!("{prefix}:configure");
+ let build_id = format!("{prefix}:build");
+ let mut args = vec!["-S", ".", "-B", &dir, "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"];
+ if !build.join("CMakeCache.txt").is_file() {
+ args.push("-DCMAKE_BUILD_TYPE=Debug");
+ }
+ let mut configure = config(&configure_id, format!("CMake Configure ({dir})"), "cmake", "cmake", &args);
+ configure.extras.params.insert("buildDir".into(), dir.clone());
+ out.push(configure);
+ let mut all = config(
+ &build_id,
+ format!("CMake Build ({dir})"),
+ "cmake",
+ "cmake",
+ &["--build", &dir, "--config", &configuration],
+ );
+ // `cmake --build` regenerates by itself once a build directory is configured.
+ if !build.join("CMakeCache.txt").is_file() {
+ before(&mut all, &configure_id);
+ }
+ out.push(all);
+ let mut test = config(
+ format!("{prefix}:test"),
+ format!("CTest ({dir})"),
+ "cmake",
+ "ctest",
+ &["--test-dir", &dir, "-C", &configuration, "--output-on-failure"],
+ );
+ before(&mut test, &build_id);
+ out.push(test);
+ targets(root, &build, &dir, &prefix, out);
+ }
+}
+
+fn targets(root: &Path, build: &Path, dir: &str, prefix: &str, out: &mut Vec<RunConfig>) {
+ let reply = build.join(".cmake/api/v1/reply");
+ let Some(index_path) = fs::read_dir(&reply).ok().and_then(|entries| {
+ entries
+ .flatten()
+ .map(|e| e.path())
+ .filter(|p| {
+ let name = p.file_name().unwrap_or_default().to_string_lossy();
+ name.starts_with("index-") && name.ends_with(".json")
+ })
+ .max()
+ }) else {
+ return;
+ };
+ let Some(index) = json(&index_path) else { return };
+ let Some(reference) = index["objects"]
+ .as_array()
+ .and_then(|a| a.iter().find(|o| o["kind"] == "codemodel" && o["version"]["major"] == 2))
+ else {
+ return;
+ };
+ let Some(model) = reference["jsonFile"].as_str().and_then(|n| reply_file(&reply, n)) else { return };
+ let Some(configurations) = model["configurations"].as_array() else { return };
+ let source_root = model["paths"]["source"].as_str().map(PathBuf::from).unwrap_or_else(|| root.into());
+ if source_root.canonicalize().ok() != root.canonicalize().ok() {
+ return;
+ }
+ let source_root = dunce::canonicalize(&source_root).unwrap_or(source_root);
+ for configuration in configurations {
+ let name = configuration["name"].as_str().unwrap_or("");
+ let Some(targets) = configuration["targets"].as_array() else { continue };
+ for target in targets {
+ let Some(target) = target["jsonFile"].as_str().and_then(|n| reply_file(&reply, n)) else { continue };
+ if target["type"] != "EXECUTABLE" {
+ continue;
+ }
+ let (Some(target_name), Some(artifact)) =
+ (target["name"].as_str(), target["artifacts"][0]["path"].as_str())
+ else {
+ continue;
+ };
+ let id = format!("{prefix}:{name}:{target_name}");
+ let target_build_id = format!("{id}:build");
+ let mut args = vec!["--build", dir, "--target", target_name];
+ if !name.is_empty() {
+ args.extend(["--config", name]);
+ }
+ let build_config =
+ config(&target_build_id, format!("Build {target_name} ({dir} {name})"), "cmake", "cmake", &args);
+ out.push(build_config);
+ let binary = build.join(artifact);
+ let mut run =
+ config(&id, format!("{target_name} ({dir} {name})"), "native", &binary.to_string_lossy(), &[])
+ .debug("lldb-dap");
+ before(&mut run, &target_build_id);
+ let sources: Vec<String> = target["sources"]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|s| {
+ let p = source_root.join(s["path"].as_str()?);
+ Some(p.to_string_lossy().replace('\\', "/"))
+ })
+ .collect();
+ run.extras.params.insert("cmakeSources".into(), sources.join("\n"));
+ if let Some(recorded) = model["paths"]["source"].as_str() {
+ run.extras.params.insert("cmakeSourceRoot".into(), recorded.into());
+ run.extras
+ .params
+ .insert("cmakeCanonicalSourceRoot".into(), source_root.to_string_lossy().replace('\\', "/"));
+ }
+ out.push(run);
+ }
+ }
+}
+
+/// Request the codemodel only when the user runs a configure configuration.
+pub(crate) fn prepare(config: &RunConfig, cwd: &Path) -> crate::IdeResult<()> {
+ if config.kind == "cmake"
+ && config.args.first().is_some_and(|a| a == "-S")
+ && let Some(dir) = config.extras.params.get("buildDir")
+ {
+ let query = cwd.join(dir).join(".cmake/api/v1/query/client-openidea");
+ fs::create_dir_all(&query)?;
+ fs::write(query.join("codemodel-v2"), "")?;
+ }
+ Ok(())
+}
diff --git a/crates/ide-run/src/process.rs b/crates/ide-run/src/process.rs
index fe9a69f62..1179c9688 100644
--- a/crates/ide-run/src/process.rs
+++ b/crates/ide-run/src/process.rs
@@ -309,6 +309,7 @@ impl ProcessManager {
if !cwd.is_dir() {
return Err(IdeError::not_found(format!("working directory does not exist: {}", cwd.display())));
}
+ crate::detect::cmake::prepare(config, &cwd)?;
let mut inv = invocation(config, &cwd);
let extras = &config.extras;
if extras.emulate_terminal && extras.stdin_file.is_some() {
diff --git a/crates/ide-run/tests/detect.rs b/crates/ide-run/tests/detect.rs
index aa5cfb4a8..d0ed4e184 100644
--- a/crates/ide-run/tests/detect.rs
+++ b/crates/ide-run/tests/detect.rs
@@ -551,6 +551,44 @@ fn root_package_disables_nested_scan() {
assert!(!ids(&c).contains(&"go:test:svc"));
}
+#[test]
+fn cmake_detection_is_read_only_and_preserves_existing_build_directories() {
+ let dir = project(&[
+ ("CMakeLists.txt", "project(demo)"),
+ ("cmake-build-debug/CMakeCache.txt", "CMAKE_CONFIGURATION_TYPES:STRING=Release;RelWithDebInfo\n"),
+ ]);
+ let configs = detect(dir.path());
+ let configure = find(&configs, "cmake:cmake-build-debug:configure");
+ assert_eq!(configure.args, ["-S", ".", "-B", "cmake-build-debug", "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON"]);
+ assert!(!dir.path().join("build").exists());
+ assert!(!dir.path().join("cmake-build-debug/.cmake").exists());
+ let build = find(&configs, "cmake:cmake-build-debug:build");
+ assert!(build.extras.before_launch.is_empty(), "a configured build regenerates by itself");
+ assert!(build.args.windows(2).any(|a| a == ["--config", "Release"]));
+ let test = find(&configs, "cmake:cmake-build-debug:test");
+ assert_eq!(test.extras.before_launch[0].target, build.id);
+}
+
+#[test]
+fn cmake_configures_before_the_first_build() {
+ let dir = project(&[("CMakeLists.txt", "project(demo)")]);
+ let configs = detect(dir.path());
+ let build = find(&configs, "cmake:build:build");
+ assert_eq!(build.extras.before_launch[0].target, "cmake:build:configure");
+}
+
+#[test]
+fn cmake_ignores_malformed_file_api_replies() {
+ let dir = project(&[
+ ("CMakeLists.txt", "project(demo)"),
+ ("build/CMakeCache.txt", ""),
+ ("build/.cmake/api/v1/reply/index-1.json", "not JSON"),
+ ]);
+ let configs = detect(dir.path());
+ assert_eq!(configs.iter().filter(|c| c.kind == "cmake").count(), 3);
+ assert!(!configs.iter().any(|c| c.kind == "native"));
+}
+
#[test]
fn go_work_members_define_configs_including_deep_and_quoted_directories() {
let dir = project(&[
diff --git a/crates/ide-run/tests/process.rs b/crates/ide-run/tests/process.rs
index 47d67386c..791ffcef2 100644
--- a/crates/ide-run/tests/process.rs
+++ b/crates/ide-run/tests/process.rs
@@ -474,6 +474,39 @@ fn python_scripts_import_sibling_packages_and_preserve_env_file_paths() {
}
}
+#[test]
+#[ignore = "requires CMake, CTest and a C++ compiler"]
+fn cmake_configure_discovers_builds_and_runs_a_multifile_target() {
+ let h = harness();
+ std::fs::write(h.root.path().join("CMakeLists.txt"), "cmake_minimum_required(VERSION 3.20)\nproject(smoke LANGUAGES CXX)\nadd_executable(smoke main.cpp math.cpp)\nenable_testing()\nadd_test(NAME smoke COMMAND smoke)\n").unwrap();
+ std::fs::write(h.root.path().join("main.cpp"), "int add(int,int); int main() { return add(2,3)==5 ? 0 : 1; }\n")
+ .unwrap();
+ std::fs::write(h.root.path().join("math.cpp"), "int add(int a,int b) { return a+b; }\n").unwrap();
+ let initial = ide_run::detect(h.root.path());
+ assert!(!h.root.path().join("build").exists(), "detection must not modify the project");
+ let configure = initial.iter().find(|c| c.id.ends_with(":configure")).unwrap();
+ let (id, output) = start(&h, configure);
+ assert_eq!(wait_exit(&h, id, Duration::from_secs(60)), Some(0), "{}", text(&output, stderr));
+ assert!(h.root.path().join("build/.cmake/api/v1/query/client-openidea/codemodel-v2").exists());
+ let root = h.root.path().canonicalize().unwrap();
+ let configs = ide_run::detect(&root);
+ let target = configs.iter().find(|c| c.kind == "native").expect("File API executable");
+ assert_eq!(target.debug_adapter.as_deref(), Some("lldb-dap"));
+ let sources = &target.extras.params["cmakeSources"];
+ assert!(sources.lines().any(|s| s.ends_with("/main.cpp")));
+ assert!(sources.lines().any(|s| s.ends_with("/math.cpp")));
+ assert!(sources.lines().any(|s| s == root.join("main.cpp").to_string_lossy()));
+ assert_eq!(target.extras.params["cmakeCanonicalSourceRoot"], root.to_string_lossy());
+ let build = configs.iter().find(|c| c.id == target.extras.before_launch[0].target).unwrap();
+ let (id, output) = start(&h, build);
+ assert_eq!(wait_exit(&h, id, Duration::from_secs(60)), Some(0), "{}", text(&output, stderr));
+ let (id, _) = start(&h, target);
+ assert_eq!(wait_exit(&h, id, Duration::from_secs(10)), Some(0));
+ let ctest = configs.iter().find(|c| c.command == "ctest").unwrap();
+ let (id, output) = start(&h, ctest);
+ assert_eq!(wait_exit(&h, id, Duration::from_secs(10)), Some(0), "{}", text(&output, stdout));
+}
+
#[test]
fn go_build_runs_with_separate_arguments_environment_and_working_directory() {
let h = harness();
diff --git a/src/editor/core/cm/cmake.test.ts b/src/editor/core/cm/cmake.test.ts
new file mode 100644
index 000000000..8a42fbf49
--- /dev/null
+++ b/src/editor/core/cm/cmake.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it } from "vitest";
+import { EditorState } from "@codemirror/state";
+import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";
+import { highlightTree, tagHighlighter, tags as t } from "@lezer/highlight";
+import { findLanguageDescription, loadSupport } from "./languages";
+
+const highlighter = tagHighlighter([
+ { tag: t.standard(t.function(t.variableName)), class: "command" },
+ { tag: t.function(t.definition(t.variableName)), class: "definition" },
+ { tag: t.function(t.variableName), class: "call" },
+ { tag: t.standard(t.variableName), class: "builtinVariable" },
+ { tag: t.special(t.variableName), class: "expansion" },
+ { tag: t.keyword, class: "keyword" },
+ { tag: t.bool, class: "bool" },
+ { tag: t.number, class: "number" },
+ { tag: t.string, class: "string" },
+ { tag: t.escape, class: "escape" },
+ { tag: t.comment, class: "comment" },
+]);
+
+async function state(source: string) {
+ const support = await loadSupport(findLanguageDescription("CMake", "CMakeLists.txt")!);
+ return EditorState.create({ doc: source, extensions: [support!] });
+}
+
+function tokens(state: EditorState) {
+ ensureSyntaxTree(state, state.doc.length, 1000);
+ const out: { text: string; style: string }[] = [];
+ highlightTree(syntaxTree(state), highlighter, (from, to, style) =>
+ out.push({ text: state.doc.sliceString(from, to), style }),
+ );
+ return out;
+}
+
+describe("CMake highlighting", () => {
+ it("styles the screenshot's commands, argument keywords and built-in variables", async () => {
+ const out = tokens(
+ await state(`cmake_minimum_required(VERSION 3.20)
+project(OpenIdeaSmoke LANGUAGES C CXX)
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
+add_executable(cpp_smoke main.cpp math.cpp)
+enable_testing()
+add_test(NAME cpp_result COMMAND cpp_smoke)
+`),
+ );
+ for (const text of ["cmake_minimum_required", "project", "set", "add_executable", "enable_testing", "add_test"])
+ expect(out).toContainEqual({ text, style: "command" });
+ for (const text of ["VERSION", "LANGUAGES", "NAME", "COMMAND"])
+ expect(out).toContainEqual({ text, style: "keyword" });
+ for (const text of ["CMAKE_CXX_STANDARD", "CMAKE_EXPORT_COMPILE_COMMANDS"])
+ expect(out).toContainEqual({ text, style: "builtinVariable" });
+ expect(out).toContainEqual({ text: "3.20", style: "number" });
+ expect(out).toContainEqual({ text: "17", style: "number" });
+ expect(out).toContainEqual({ text: "ON", style: "bool" });
+ });
+
+ it("styles version ranges and the project, CTest and CPack predefined variables", async () => {
+ const out = tokens(
+ await state(
+ "find_package(Qt6 6.2...<7.0 REQUIRED)\nmessage(${PROJECT_NAME} ${CTEST_SOURCE_DIRECTORY} ${CPACK_GENERATOR})\nset(PROJECT_VERSION 1.2.3)",
+ ),
+ );
+ expect(out).toContainEqual({ text: "6.2...<7.0", style: "number" });
+ expect(out).toContainEqual({ text: "1.2.3", style: "number" });
+ expect(out).toContainEqual({ text: "PROJECT_VERSION", style: "builtinVariable" });
+ });
+
+ it("recognizes case-insensitive commands, control flow and user-defined functions", async () => {
+ const out = tokens(
+ await state(
+ "FUNCTION(Build target)\n MESSAGE(STATUS hello)\nENDFUNCTION()\nBuild(app)\nif(DEFINED CMAKE_BUILD_TYPE AND NOT OFF)\nendif()",
+ ),
+ );
+ for (const text of ["FUNCTION", "ENDFUNCTION", "if", "DEFINED", "AND", "NOT", "endif"])
+ expect(out).toContainEqual({ text, style: "keyword" });
+ expect(out).toContainEqual({ text: "MESSAGE", style: "command" });
+ expect(out).toContainEqual({ text: "Build", style: "definition" });
+ expect(out).toContainEqual({ text: "Build", style: "call" });
+ });
+
+ it("separates quoted text, nested variable expansions, environment/cache lookups and escapes", async () => {
+ const out = tokens(await state('message("hello ${${PREFIX}_NAME} $ENV{HOME} $CACHE{SDK} \\"quote\\" # text")'));
+ for (const text of ["${${PREFIX}_NAME}", "$ENV{HOME}", "$CACHE{SDK}"])
+ expect(out).toContainEqual({ text, style: "expansion" });
+ expect(out).toContainEqual({ text: '\\"', style: "escape" });
+ expect(out.some((t) => t.style === "comment")).toBe(false);
+ expect(out.some((t) => t.style === "string" && t.text.includes("# text"))).toBe(true);
+ });
+
+ it("keeps multiline bracket comments and literal bracket strings opaque", async () => {
+ const out = tokens(
+ await state(
+ "#[=[\nset(CMAKE_FAKE ON)\n]=]\nset(TEXT [==[\n${LITERAL} # raw\n]==])\n# line comment\nmessage(hello)",
+ ),
+ );
+ expect(out.some((t) => t.style === "command" && t.text === "set")).toBe(true);
+ expect(out.some((t) => t.text.includes("CMAKE_FAKE") && t.style === "comment")).toBe(true);
+ expect(out.some((t) => t.text.includes("${LITERAL}") && t.style === "string")).toBe(true);
+ expect(out.some((t) => t.style === "expansion")).toBe(false);
+ expect(out).toContainEqual({ text: "message", style: "command" });
+ });
+
+ it("handles nested generator expressions without swallowing following commands", async () => {
+ const expression = "$<IF:$<BOOL:${ENABLE}>,a,b>";
+ const out = tokens(await state(`target_link_libraries(app PRIVATE ${expression})\nmessage(done)`));
+ expect(out).toContainEqual({ text: expression, style: "expansion" });
+ expect(out).toContainEqual({ text: "message", style: "command" });
+ });
+
+ it("reparses multiline string edits and resolves CMake filename associations", async () => {
+ const before = await state("set(TEXT [=[\nmessage(hidden)\n]=])\nmessage(visible)");
+ const out = tokens(before);
+ expect(out.filter((t) => t.style === "command" && t.text === "message")).toHaveLength(1);
+ const after = before.update({ changes: { from: 9, to: 12, insert: '"' } }).state;
+ expect(tokens(after).filter((t) => t.style === "command" && t.text === "message")).toHaveLength(0);
+ expect(tokens(before)).toEqual(out);
+ for (const path of ["CMakeLists.txt", "module.cmake", "toolchain.cmake.in"])
+ expect(findLanguageDescription(null, path)?.name, path).toBe("CMake");
+ });
+});
diff --git a/src/editor/core/cm/cmake.ts b/src/editor/core/cm/cmake.ts
new file mode 100644
index 000000000..0b0c3e38f
--- /dev/null
+++ b/src/editor/core/cm/cmake.ts
@@ -0,0 +1,159 @@
+import { StreamLanguage, type StreamParser, type StringStream } from "@codemirror/language";
+import { tags as t } from "@lezer/highlight";
+
+const COMMANDS = new Set(
+ `
+add_compile_definitions add_compile_options add_custom_command add_custom_target add_definitions
+add_dependencies add_executable add_library add_link_options add_subdirectory add_test aux_source_directory
+build_command build_name cmake_file_api cmake_host_system_information cmake_language cmake_minimum_required
+cmake_parse_arguments cmake_path cmake_policy configure_file create_test_sourcelist
+ctest_build ctest_configure ctest_coverage ctest_empty_binary_directory ctest_memcheck ctest_read_custom_files
+ctest_run_script ctest_sleep ctest_start ctest_submit ctest_test ctest_update ctest_upload define_property
+enable_language enable_testing exec_program execute_process export export_library_dependencies file
+find_file find_library find_package find_path find_program fltk_wrap_ui get_cmake_property
+get_directory_property get_filename_component get_property get_source_file_property get_target_property
+get_test_property include include_directories include_external_msproject include_guard include_regular_expression
+install install_files install_programs install_targets link_directories link_libraries list load_cache
+load_command make_directory mark_as_advanced math message option output_required_files project qt_wrap_cpp
+qt_wrap_ui remove remove_definitions separate_arguments set set_directory_properties set_property
+set_source_files_properties set_target_properties set_tests_properties site_name source_group string
+subdir_depends subdirs target_compile_definitions target_compile_features target_compile_options
+ target_include_directories target_link_directories target_link_libraries target_link_options
+ target_precompile_headers target_sources try_compile try_run unset use_mangled_mesa utility_source
+variable_requires variable_watch write_file
+`
+ .trim()
+ .split(/\s+/),
+);
+
+const CONTROL = new Set(
+ `
+block break continue else elseif endblock endforeach endfunction endif endmacro endwhile
+foreach function if macro return while
+`
+ .trim()
+ .split(/\s+/),
+);
+
+const ARGUMENTS = new Set(
+ `
+VERSION LANGUAGES NAME COMMAND COMMANDS WORKING_DIRECTORY COMMENT DEPENDS OUTPUT OUTPUTS BYPRODUCTS
+PRIVATE PUBLIC INTERFACE REQUIRED QUIET COMPONENTS OPTIONAL_COMPONENTS CONFIG MODULE EXACT GLOBAL
+APPEND PROPERTY PROPERTIES CACHE INTERNAL FORCE PARENT_SCOPE PATH FILEPATH BOOL STRING
+DIRECTORY DIRECTORIES FILE FILES TARGET TARGETS DESTINATION EXPORT NAMESPACE TYPE STATIC SHARED
+MODULE OBJECT IMPORTED ALIAS EXCLUDE_FROM_ALL ALL BEFORE AFTER SYSTEM CONFIGURE_DEPENDS
+AND OR NOT DEFINED EXISTS IS_DIRECTORY IS_SYMLINK IS_ABSOLUTE MATCHES LESS GREATER EQUAL
+LESS_EQUAL GREATER_EQUAL STRLESS STRGREATER STREQUAL VERSION_LESS VERSION_GREATER VERSION_EQUAL
+VERSION_LESS_EQUAL VERSION_GREATER_EQUAL IN_LIST COMMAND POLICY TARGET TEST
+`
+ .trim()
+ .split(/\s+/),
+);
+
+interface State {
+ quoted: boolean;
+ bracket: { end: string; style: "comment" | "string" } | null;
+ depth: number;
+ definition: boolean;
+}
+
+function bracket(stream: StringStream, state: State): string {
+ const { end, style } = state.bracket!;
+ const close = stream.string.indexOf(end, stream.pos);
+ if (close < 0) stream.skipToEnd();
+ else {
+ stream.pos = close + end.length;
+ state.bracket = null;
+ }
+ return style;
+}
+
+function expansion(stream: StringStream): boolean {
+ const variable = stream.match(/^\$(?:ENV|CACHE)?\{/);
+ const generator = !variable && stream.match(/^\$</);
+ if (!variable && !generator) return false;
+ let depth = 1;
+ while (!stream.eol() && depth) {
+ if (generator && stream.match("$<")) depth++;
+ else {
+ const ch = stream.next();
+ if (variable && ch === "{") depth++;
+ if (ch === (variable ? "}" : ">")) depth--;
+ }
+ }
+ return true;
+}
+
+const parser: StreamParser<State> = {
+ name: "cmake",
+ startState: () => ({ quoted: false, bracket: null, depth: 0, definition: false }),
+ copyState: (s) => ({ ...s, bracket: s.bracket && { ...s.bracket } }),
+ languageData: { commentTokens: { line: "#", block: { open: "#[[", close: "]]" } } },
+ tokenTable: {
+ command: t.standard(t.function(t.variableName)),
+ cmakeVariable: t.standard(t.variableName),
+ expansion: t.special(t.variableName),
+ functionDefinition: t.function(t.definition(t.variableName)),
+ },
+ token(stream, state) {
+ if (state.bracket) return bracket(stream, state);
+ if (expansion(stream)) return "expansion";
+ if (stream.eat("\\")) {
+ stream.next();
+ return "escape";
+ }
+ if (stream.eat('"')) {
+ state.quoted = !state.quoted;
+ return "string";
+ }
+ if (state.quoted) {
+ while (!stream.eol() && !/["\\]/.test(stream.peek()!)) {
+ if (stream.match(/^\$(?:(?:ENV|CACHE)?\{|<)/, false)) break;
+ stream.next();
+ }
+ return "string";
+ }
+ if (stream.eatSpace()) return null;
+ const open = stream.match(/^(#?)\[(=*)\[/);
+ if (open) {
+ const [, comment, equals] = open as RegExpMatchArray;
+ state.bracket = { end: `]${equals}]`, style: comment ? "comment" : "string" };
+ return bracket(stream, state);
+ }
+ if (stream.eat("#")) {
+ stream.skipToEnd();
+ return "comment";
+ }
+ if (stream.eat("(")) {
+ state.depth++;
+ return "paren";
+ }
+ if (stream.eat(")")) {
+ state.depth = Math.max(0, state.depth - 1);
+ state.definition = false;
+ return "paren";
+ }
+ const word = stream.match(/^[^\s()#"\\$]+/);
+ if (word) {
+ const text = (word as RegExpMatchArray)[0];
+ if (state.depth === 0 && /^[A-Za-z_]\w*$/.test(text) && stream.match(/^\s*\(/, false)) {
+ const command = text.toLowerCase();
+ state.definition = command === "function" || command === "macro";
+ return CONTROL.has(command) ? "keyword" : COMMANDS.has(command) ? "command" : "variableName.function";
+ }
+ if (state.definition) {
+ state.definition = false;
+ return "functionDefinition";
+ }
+ if (/^[+-]?\d+(?:\.\d+)*(?:\.\.\.<?\d+(?:\.\d+)*)?$/.test(text)) return "number";
+ if (/^(?:ON|OFF|TRUE|FALSE|YES|NO|Y|N|IGNORE|NOTFOUND)$/i.test(text)) return "bool";
+ if (/^(?:CMAKE|PROJECT|CTEST|CPACK)_\w+$/.test(text)) return "cmakeVariable";
+ if (ARGUMENTS.has(text)) return "keyword";
+ return null;
+ }
+ stream.next();
+ return null;
+ },
+};
+
+export const cmakeLanguage = StreamLanguage.define(parser);
diff --git a/src/editor/core/cm/languages.ts b/src/editor/core/cm/languages.ts
index 9b5662c98..bcd1d9bd2 100644
--- a/src/editor/core/cm/languages.ts
+++ b/src/editor/core/cm/languages.ts
@@ -60,8 +60,14 @@ export function uiModeForPath(path: string): string | null | undefined {
const supports = new Map<string, Promise<LanguageSupport | null>>();
-/** Frontend modes with template syntax missing from the bundled parsers. */
+/** Frontend modes that extend or replace the bundled parsers. */
const OWN_MODES = [
+ LanguageDescription.of({
+ name: "CMake",
+ extensions: ["cmake", "cmake.in"],
+ filename: /^(?:CMakeLists\.txt|.*\.cmake(?:\.in)?)$/,
+ load: async () => new LanguageSupport((await import("./cmake")).cmakeLanguage),
+ }),
LanguageDescription.of({
name: "Shell",
load: async () => {
@@ -169,6 +175,8 @@ export function findLanguageDescription(uiMode: string | null, path: string): La
if (loose) return OWN_MODES.find((l) => l.name === loose.name) ?? loose;
}
if (uiMode === null && infos) return null;
+ const own = LanguageDescription.matchFilename(OWN_MODES, path.slice(path.lastIndexOf("/") + 1));
+ if (own) return own;
const matched = LanguageDescription.matchFilename(BUILTIN_MODES, path.slice(path.lastIndexOf("/") + 1));
return OWN_MODES.find((l) => l.name === matched?.name) ?? matched;
}
diff --git a/src/features/debugger/__tests__/launch.test.ts b/src/features/debugger/__tests__/launch.test.ts
index 56a71e5f3..19fac437f 100644
--- a/src/features/debugger/__tests__/launch.test.ts
+++ b/src/features/debugger/__tests__/launch.test.ts
@@ -242,6 +242,20 @@ describe("run config → launch config", () => {
expect(extra(dap)).toEqual({ env: ["K=v"] });
});
+ it("maps CMake debug-info paths to the editor's canonical source root", () => {
+ const config = rc({
+ kind: "native",
+ command: "/private/tmp/project/build/app",
+ debugAdapter: "lldb-dap",
+ env: { K: "v" },
+ params: { cmakeSourceRoot: "/tmp/project", cmakeCanonicalSourceRoot: "/private/tmp/project" },
+ });
+ expect(extra(launchConfigFor(config, "/private/tmp/project")!)).toEqual({
+ env: ["K=v"],
+ sourceMap: [["/tmp/project", "/private/tmp/project"]],
+ });
+ });
+
it("Godot: the editor's adapter plays the main scene or the chosen one of the project", () => {
const project = rc({
kind: "godot",
diff --git a/src/features/debugger/launch.ts b/src/features/debugger/launch.ts
index 4bd480b9c..8f593baad 100644
--- a/src/features/debugger/launch.ts
+++ b/src/features/debugger/launch.ts
@@ -287,8 +287,14 @@ function godotLaunch(rc: RunConfig, cwd: string): LaunchConfig {
function nativeLaunch(rc: RunConfig, cwd: string, adapter: string): LaunchConfig {
const out: LaunchConfig = { ...base(rc, adapter, cwd), program: resolveCommand(rc.command, cwd), args: [...rc.args] };
// lldb-dap takes the environment as `KEY=VALUE` strings.
- if (adapter === "lldb-dap")
- out.extraJson = JSON.stringify({ env: Object.entries(rc.env).map(([k, v]) => `${k}=${v}`) });
+ if (adapter === "lldb-dap") {
+ const from = rc.params?.cmakeSourceRoot;
+ const to = rc.params?.cmakeCanonicalSourceRoot;
+ out.extraJson = JSON.stringify({
+ env: Object.entries(rc.env).map(([k, v]) => `${k}=${v}`),
+ ...(from && to && from !== to ? { sourceMap: [[from, to]] } : {}),
+ });
+ }
return out;
}
diff --git a/src/features/run/configs.ts b/src/features/run/configs.ts
index 9561520cd..7669141b6 100644
--- a/src/features/run/configs.ts
+++ b/src/features/run/configs.ts
@@ -14,6 +14,7 @@ const KIND_LABELS: Record<string, string> = {
python: "Python",
pytest: "pytest",
make: "Make",
+ cmake: "CMake",
just: "Just",
shell: "Shell Script",
program: "Program",
diff --git a/src/features/run/index.ts b/src/features/run/index.ts
index 720346763..9687af4d6 100644
--- a/src/features/run/index.ts
+++ b/src/features/run/index.ts
@@ -247,7 +247,7 @@ function useRunningCount(): number | null {
}
const CONFIG_FILES =
- /(?:^|\/)(?:\.openidea\/run\.toml|package\.json|deno\.jsonc?|Cargo\.toml|build\.gradle(?:\.kts)?|pom\.xml|go\.(?:mod|work)|pyproject\.toml|setup\.cfg|pytest\.ini|manage\.py|Makefile|justfile)$/;
+ /(?:^|\/)(?:\.openidea\/run\.toml|package\.json|deno\.jsonc?|Cargo\.toml|build\.gradle(?:\.kts)?|pom\.xml|go\.(?:mod|work)|pyproject\.toml|setup\.cfg|pytest\.ini|manage\.py|Makefile|justfile|CMakeLists\.txt|CMakeCache\.txt|index-[^/]+\.json)$/;
let reloadTimer: ReturnType<typeof setTimeout> | undefined;
function scheduleReload() {
@@ -533,6 +533,9 @@ export function activate(): () => void {
if (paths.some((p) => /(?:^|\/)go\.(?:mod|work)$/.test(p))) invalidateGoModules();
if (paths.some((p) => CONFIG_FILES.test(p))) scheduleReload();
}),
+ onIdeEvent("runExited", (e) => {
+ if (useRun.getState().sessions.some((s) => s.runId === e.run && s.config.kind === "cmake")) scheduleReload();
+ }),
// Detected configs carry the selected toolchains (interpreter, JDK, Maven home and options).
onIdeEvent("settingsChanged", (e) => {
if (e.key === "languages" || e.key.startsWith("languages.")) scheduleReload();
diff --git a/src/features/run/producers.test.ts b/src/features/run/producers.test.ts
index 8fd04d491..64a102519 100644
--- a/src/features/run/producers.test.ts
+++ b/src/features/run/producers.test.ts
@@ -385,7 +385,8 @@ describe("single-file producers (scratches)", () => {
);
const cpp = produceContext(scratch("a.cpp", "int main() {}"), env({ "g++": null }))!;
expect(cpp.config!.command).toMatch(/\/bin\/g\+\+ -g -std=c\+\+17 -o/);
- expect(cpp.debug!.config.debugAdapter).toBe("codelldb");
+ expect(cpp.debug!.config.debugAdapter).toBe("lldb-dap");
+ expect(c.debug!.config.debugAdapter).toBe("lldb-dap");
expect(produceContext(scratch("lib.c", "int add(int a, int b);"), ALL)).toBeNull();
});
@@ -761,3 +762,44 @@ describe("Go test names (GoLand)", () => {
expect(p.config!.args).toEqual(["test", ".", "-run", "^TestAdd$"]);
});
});
+
+describe("CMake file context", () => {
+ const configure = cfg({
+ id: "cmake:build:configure",
+ kind: "cmake",
+ command: "cmake",
+ args: ["-S", ".", "-B", "build"],
+ });
+ const native = cfg({
+ id: "cmake:build:Debug:app",
+ name: "app",
+ kind: "native",
+ command: "/p/build/app",
+ debugAdapter: "lldb-dap",
+ params: { cmakeSources: "main.cpp\nmath.cpp" },
+ beforeLaunch: [{ kind: "run", target: "cmake:build:Debug:app:build" }],
+ });
+ const input = { path: "/p/main.cpp", root: "/p", configs: [configure, native], content: "int main() {}", line: 0 };
+ it("runs the owning executable and keeps its build task", () => {
+ expect(produceContext(input, OPTIMISTIC)?.config).toEqual(native);
+ });
+ it("matches absolute source paths from a linked workspace member", () => {
+ const target = { ...native, params: { cmakeSources: "/workspace/native/main.cpp" } };
+ const p = produceContext(
+ { ...input, path: "/workspace/native/main.cpp", root: "/workspace", configs: [configure, target] },
+ OPTIMISTIC,
+ );
+ expect(p?.config).toEqual(target);
+ });
+ it("offers all executable targets sharing the source", () => {
+ const second = { ...native, id: "other", name: "other" };
+ expect(
+ produceContextChoices({ ...input, configs: [configure, native, second] }, OPTIMISTIC).map((p) => p.config?.id),
+ ).toEqual([native.id, second.id]);
+ });
+ it("never compiles a CMake source as a standalone file when the target is unknown", () => {
+ const p = produceContext({ ...input, configs: [configure] }, OPTIMISTIC);
+ expect(p?.config).toBeUndefined();
+ expect(p?.missing?.body).toContain("CMake Configure");
+ });
+});
diff --git a/src/features/run/producers.ts b/src/features/run/producers.ts
index 59456391f..6a784cad4 100644
--- a/src/features/run/producers.ts
+++ b/src/features/run/producers.ts
@@ -482,7 +482,7 @@ function compiled(
const run = lang === "kotlin" ? [java!.command, "-jar", out] : [out, ...runArgs];
const kind = lang === "rust" ? "rustc" : lang === "kotlin" ? "kotlinc" : "cc";
const idPath = test ? `${s.idPath}#${test.name}` : s.idPath;
- const debugAdapter = lang === "kotlin" ? null : "codelldb";
+ const debugAdapter = lang === "kotlin" ? null : lang === "rust" ? "codelldb" : "lldb-dap";
const config: RunConfig = {
...fileConfig(s, kind, `${build} && ${shellLine(run, win)}`, [], debugAdapter),
id: `context:file:${idPath}`,
@@ -575,6 +575,19 @@ export function produceFile(input: ContextInput, env: ToolEnv): Produced | null
const rel = s.idPath;
if (s.inProject) {
+ if (lang === "c" || lang === "cpp") {
+ const target = cmakeTargets(input)[0];
+ if (target) return { name: target.name, scope: "file", config: target };
+ if (configs.some((c) => c.kind === "cmake"))
+ return {
+ name: s.file,
+ scope: "file",
+ missing: {
+ title: "No CMake executable target for this file",
+ body: "Run CMake Configure from the Run selector, then choose the executable target. Files in a CMake project are built with their target.",
+ },
+ };
+ }
if (/\.t?scn$/i.test(rel)) return godotScene(rel, configs);
// Project-aware: test files through the project's test runner, Cargo / Go / Gradle / Maven mains.
const role = fileRole(rel, input.content);
@@ -868,6 +881,8 @@ export function produceContextChoices(input: ContextInput, env: ToolEnv): Produc
if (!produced?.config || produced.scope === "directory" || !inProject(input.path, input.root))
return produced ? [produced] : [];
const rel = relTo(input.path, input.root);
+ const cmake = cmakeTargets(input);
+ if (cmake.length > 1) return cmake.map((config) => ({ name: config.name, scope: produced.scope, config }));
const bases = testBasesFor(rel, [...input.configs]);
if (bases.length < 2) return [produced];
let element: RunTarget | null = null;
@@ -890,6 +905,14 @@ export function produceContextChoices(input: ContextInput, env: ToolEnv): Produc
return out.length > 1 ? out : [produced];
}
+function cmakeTargets(input: ContextInput): RunConfig[] {
+ if (!inProject(input.path, input.root)) return [];
+ const lang = scriptLanguage(input.path, input.content);
+ if (lang !== "c" && lang !== "cpp") return [];
+ const rel = relTo(input.path, input.root);
+ return input.configs.filter((c) => c.params?.cmakeSources?.split("\n").some((p) => p === rel || p === input.path));
+}
+
// ---------------------------------------------------------------------------
// Directories (project view): "Run 'Tests in 'dir''", "Run 'All Tests'"
diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json
index 9727509b3..a2c997cad 100644
--- a/src/platform/locales/text/zh.json
+++ b/src/platform/locales/text/zh.json
@@ -5319,5 +5319,7 @@
"Compiler": "编译器",
"go1.22": "go1.22",
"integration debug": "integration debug",
- "loopvar,rangefunc": "loopvar,rangefunc"
+ "loopvar,rangefunc": "loopvar,rangefunc",
+ "No CMake executable target for this file": "此文件没有对应的 CMake 可执行目标",
+ "Run CMake Configure from the Run selector, then choose the executable target. Files in a CMake project are built with their target.": "请从运行选择器执行 CMake Configure,然后选择可执行目标。CMake 项目中的文件由所属目标构建,不会单独编译。"
}