diff --git a/crates/cg-core/src/brand.rs b/crates/cg-core/src/brand.rs index d6cfb16..f9c1943 100644 --- a/crates/cg-core/src/brand.rs +++ b/crates/cg-core/src/brand.rs @@ -17,7 +17,7 @@ pub const UPSTREAM_CONFIG_FILE: &str = "codegraph.json"; pub const CONFIG_FILE: &str = "cgr.json"; /// Version of the resolution rules: changing resolver behaviour bumps this, which /// marks older indexes as "built by an older engine" (design doc 5.8). -pub const ENGINE_VERSION: u32 = 10; +pub const ENGINE_VERSION: u32 = 11; /// Version of the on-disk segment format; a mismatch forces a full rebuild. pub const FORMAT_VERSION: u32 = 2; /// The upstream commit whose kernel is vendored (see crates/cg-kernel/UPSTREAM_COMMIT). diff --git a/crates/cg-resolve/src/resolve.rs b/crates/cg-resolve/src/resolve.rs index 53ba48e..63e7ca6 100644 --- a/crates/cg-resolve/src/resolve.rs +++ b/crates/cg-resolve/src/resolve.rs @@ -2431,9 +2431,12 @@ impl<'e, 'v> FileCx<'e, 'v> { let scoped_root = self.lang == Lang::Cpp && r_name_is_scoped(view.text_str(r.name)); if let Some(b) = self.lookup_binding(root, scope, r.line, false).filter(|_| !scoped_root) { if b.kind != BindKind::LocalFn as u8 { + // With fields, the final method belongs to the last field, not + // to the root pointer (arc.field.clone() may call Field::clone). + let receiver_method = if path.is_empty() { method } else { "" }; return match self.binding_value(wcx, b, 0) { - Some(t) if t.method_receiver(method).is_some() => { - let o = self.member_call(wcx, t.method_receiver(method).unwrap(), path, method, 90, call); + Some(t) if t.method_receiver(receiver_method).is_some() => { + let o = self.member_call(wcx, t.method_receiver(receiver_method).unwrap(), path, method, 90, call); if o.status == status::RESOLVED { o } else { diff --git a/crates/cg-resolve/tests/resolve_e2e.rs b/crates/cg-resolve/tests/resolve_e2e.rs index 09caddc..80502b9 100644 --- a/crates/cg-resolve/tests/resolve_e2e.rs +++ b/crates/cg-resolve/tests/resolve_e2e.rs @@ -273,6 +273,68 @@ fn kotlin_members_and_imports() { assert!(has(&edges, &format!("{run} -calls-> src/com/x/svc/A.kt::com.x.svc::A::other"))); } +#[test] +fn rust_pointer_roots_use_the_final_field_method() { + let (_d, view) = project(&[ + ("Cargo.toml", "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n"), + ("src/lib.rs", "pub mod worker;\npub mod owner;\n"), + ( + "src/worker.rs", + r#"pub struct Worker; +impl Worker { + pub fn execute(&self) -> u8 { 7 } + pub fn clone(&self) -> u8 { 99 } +} +pub struct Noise; +impl Noise { pub fn execute(&self) -> u8 { 0 } } +"#, + ), + ( + "src/owner.rs", + r#"use crate::worker::Worker; +use std::rc::Rc; +use std::sync::Arc; +pub struct Owner { + plain: Worker, + child: Child, +} +pub struct Child { plain: Worker } +impl Child { pub fn clone(&self) -> u8 { 88 } } +impl Owner { + pub fn plain(&self) -> u8 { self.plain.execute() } + pub fn child(&self) -> u8 { self.child.plain.execute() } + pub fn plain_clone(&self) -> u8 { self.plain.clone() } + pub fn child_plain_clone(&self) -> u8 { self.child.plain.clone() } +} +pub fn local_plain(w: Child) -> u8 { w.plain.clone() } +pub fn local_arc(w: Arc) -> u8 { w.plain.clone() } +pub fn local_rc(w: Rc) -> u8 { w.plain.clone() } +pub fn local_box(w: Box) -> u8 { w.plain.clone() } +pub fn local_nested(w: Arc>) -> u8 { w.plain.clone() } +pub fn direct_plain(w: Child) -> u8 { w.clone() } +pub fn direct_arc(w: Arc) { w.clone(); } +pub fn direct_rc(w: Rc) { w.clone(); } +"#, + ), + ]); + let edges = dump::dump_edges(&view); + for name in ["plain", "child"] { + let calls: Vec<_> = edges.iter().filter(|e| e.starts_with(&format!("src/owner.rs::Owner::{name} -calls-> "))).map(String::as_str).collect(); + assert_eq!(calls, [format!("src/owner.rs::Owner::{name} -calls-> src/worker.rs::Worker::execute")], "{edges:#?}"); + } + for name in ["plain_clone", "child_plain_clone"] { + assert!(has(&edges, &format!("src/owner.rs::Owner::{name} -calls-> src/worker.rs::Worker::clone")), "{edges:#?}"); + } + for name in ["local_plain", "local_arc", "local_rc", "local_box", "local_nested"] { + let calls: Vec<_> = edges.iter().filter(|e| e.starts_with(&format!("src/owner.rs::{name} -calls-> "))).map(String::as_str).collect(); + assert_eq!(calls, [format!("src/owner.rs::{name} -calls-> src/worker.rs::Worker::clone")], "{edges:#?}"); + } + assert!(has(&edges, "src/owner.rs::direct_plain -calls-> src/owner.rs::Child::clone"), "{edges:#?}"); + for name in ["direct_arc", "direct_rc"] { + assert!(!edges.iter().any(|e| e.starts_with(&format!("src/owner.rs::{name} -calls-> "))), "{edges:#?}"); + } +} + #[test] fn debug_ts_unresolved() { let (_d, view) = project(&[ diff --git a/crates/cg-sync/src/sync.rs b/crates/cg-sync/src/sync.rs index 09d651a..20c44ac 100644 --- a/crates/cg-sync/src/sync.rs +++ b/crates/cg-sync/src/sync.rs @@ -296,6 +296,15 @@ fn js_twin_order_sig(view: &View, f: FileId) -> Vec<(String, u8)> { /// stays the same (e.g. `obj.old = function internal` -> `obj.new = ...`, or the target of a /// Rust `impl Deref`, which has no node of its own). fn resolver_fact_sig(view: &View, f: FileId) -> ResolverFactSig { + let field_owners: FxHashMap<_, _> = if view.file(f).lang().family() == LangFamily::Rust { + view.nodes_in_file(f) + .map(|n| view.node(NodeIdx(n))) + .filter(|n| n.kind().is_type()) + .map(|n| (cg_core::text::pack_pos(n.start_line(), n.start_col()), n.qname().to_owned())) + .collect() + } else { + FxHashMap::default() + }; view.bindings_of(f) .iter() .filter(|b| { @@ -309,15 +318,20 @@ fn resolver_fact_sig(view: &View, f: FileId) -> ResolverFactSig { || b.kind == BindKind::Mutation as u8 || b.kind == BindKind::CommonJsObject as u8 || b.kind == BindKind::MacroNamespace as u8 + || (b.kind == BindKind::Field as u8 && view.file(f).lang().family() == LangFamily::Rust) }) .map(|b| { - ( - b.kind, - view.text_str(b.name).to_owned(), - if b.node.is_some() { view.node(b.node).qname().to_owned() } else { String::new() }, - view.text_str(b.decl_type).to_owned(), - view.text_str(b.init_ctor).to_owned(), - ) + // A Rust field's declared type can redirect a call in an unchanged + // importer. Include its owner: two structs may have the same field. + let owner = if b.kind == BindKind::Field as u8 { + let scope = &view.scopes_of(f)[b.scope.0.wrapping_sub(view.scope_base(f)) as usize]; + field_owners.get(&scope.start).cloned().unwrap_or_default() + } else if b.node.is_some() { + view.node(b.node).qname().to_owned() + } else { + String::new() + }; + (b.kind, view.text_str(b.name).to_owned(), owner, view.text_str(b.decl_type).to_owned(), view.text_str(b.init_ctor).to_owned()) }) .collect() } diff --git a/crates/cg-sync/tests/rust_field_types.rs b/crates/cg-sync/tests/rust_field_types.rs new file mode 100644 index 0000000..74e84f6 --- /dev/null +++ b/crates/cg-sync/tests/rust_field_types.rs @@ -0,0 +1,79 @@ +use cg_resolve::{index_project, IndexOptions}; +use cg_store::{dump, Store}; +use cg_sync::{sync, SyncOptions}; +use std::path::Path; +use std::time::{Duration, SystemTime}; + +fn write(root: &Path, name: &str, source: &str, step: u64) { + let path = root.join(name); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, source).unwrap(); + let stamp = SystemTime::UNIX_EPOCH + Duration::from_secs(1_700_000_000 + step); + std::fs::OpenOptions::new().write(true).open(path).unwrap().set_modified(stamp).unwrap(); +} + +fn graph(root: &Path) -> Vec { + let snap = Store::locate(root).unwrap().open_snapshot().unwrap(); + dump::canonical(&snap.view) +} + +fn assert_targets(root: &Path, target: &str) { + let snap = Store::locate(root).unwrap().open_snapshot().unwrap(); + let edges = dump::dump_edges(&snap.view); + for caller in ["src/owner.rs::Owner::run", "src/caller.rs::call"] { + let calls: Vec<_> = edges.iter().filter(|e| e.starts_with(&format!("{caller} -calls-> "))).map(String::as_str).collect(); + assert_eq!(calls, [format!("{caller} -calls-> src/worker.rs::{target}::execute")], "{edges:#?}"); + } + for ty in ["Worker", "Other"] { + let edge = format!("src/owner.rs::Owner::clone_worker -calls-> src/worker.rs::{ty}::clone"); + assert_eq!(edges.contains(&edge), ty == target, "{edges:#?}"); + } +} + +#[test] +fn rust_field_type_swaps_retarget_unchanged_callers_without_full_rebuild() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path(); + let opts = IndexOptions { threads: Some(2), ..Default::default() }; + let mut files = vec![ + ("Cargo.toml".to_owned(), "[package]\nname = \"demo\"\nversion = \"0.1.0\"\nedition = \"2021\"\n".to_owned()), + ("src/lib.rs".to_owned(), "pub mod worker;\npub mod owner;\npub mod caller;\n".to_owned()), + ( + "src/worker.rs".to_owned(), + "pub struct Worker;\nimpl Worker { pub fn execute(&self) -> u8 { 7 } pub fn clone(&self) -> u8 { 99 } }\npub struct Other;\nimpl Other { pub fn execute(&self) -> u8 { 8 } pub fn clone(&self) -> u8 { 98 } }\n".to_owned(), + ), + ("src/caller.rs".to_owned(), "use crate::owner::Owner;\npub fn call(owner: &Owner) -> u8 { owner.worker.execute() }\n".to_owned()), + ]; + // Exercise a delta: a full rebuild must not conceal missing consumer invalidation. + for i in 0..48 { + files.push((format!("src/filler{i}.rs"), format!("fn helper{i}() {{}}\npub fn filler{i}() {{ helper{i}(); }}\n"))); + } + let owner = |ty: &str| { + let decoy = if ty == "Other" { "Worker" } else { "Other" }; + format!( + "use crate::worker::{{Worker, Other}};\npub struct Owner {{ pub worker: {ty} }}\nimpl Owner {{\n pub fn run(&self) -> u8 {{ self.worker.execute() }}\n pub fn clone_worker(&self) {{ self.worker.clone(); }}\n}}\nstruct Decoy {{ worker: {decoy} }}\n" + ) + }; + for (name, source) in &files { + write(root, name, source, 1); + } + write(root, "src/owner.rs", &owner("Worker"), 1); + index_project(root, &opts).unwrap(); + assert_targets(root, "Worker"); + // Swapping same-named fields between owners must not cancel the fact diff. + for (i, ty) in ["Other", "Worker", "Other", "Worker"].into_iter().enumerate() { + let source = owner(ty); + write(root, "src/owner.rs", &source, 100 + i as u64); + let report = sync(root, &SyncOptions { index: opts.clone(), ..Default::default() }).unwrap(); + assert!(report.full_rebuild.is_none(), "step {i}: {report:?}"); + assert_targets(root, ty); + let fresh = tempfile::tempdir().unwrap(); + for (name, contents) in &files { + write(fresh.path(), name, contents, 1); + } + write(fresh.path(), "src/owner.rs", &source, 1); + index_project(fresh.path(), &opts).unwrap(); + assert_targets(fresh.path(), ty); + assert_eq!(graph(root), graph(fresh.path()), "step {i}: {ty}"); + } +}