use super::{UnitMatchIndex, WorkspaceIndex};
use crate::writer::IndexWriter;
use crate::{DefKind, RawDefinition};
use std::collections::HashMap;
use std::fs::File;
use std::path::{Path, PathBuf};
fn write_shard(dir: &Path, crate_name: &str, files: &[(&str, &str, u32)]) -> PathBuf {
let path = dir.join(format!("{crate_name}.ridx"));
let mut writer = IndexWriter::new(crate_name, "0.1.0");
for (i, (file, item, line)) in files.iter().enumerate() {
writer.add_definition(RawDefinition {
def_id: i as u32 + 1,
kind: DefKind::Fn,
visibility: 1,
is_macro_expansion: false,
name: item.to_string(),
path: format!("{crate_name}::{item}"),
signature: None,
file: file.to_string(),
start_line: *line,
start_col: 1,
end_line: *line,
end_col: 10,
});
}
let mut f = File::create(&path).unwrap();
writer.write_to(&mut f).unwrap();
path
}
fn workspace(shards: &[(PathBuf, Option<&str>, bool)], ws_root: &str) -> WorkspaceIndex {
let readers: Vec<_> = shards.iter().map(|(p, _, _)| crate::reader::IndexReader::open(p).unwrap()).collect();
let n = readers.len();
let unit_keys: Vec<Option<String>> = (0..n).map(|i| Some(format!("unit{i}"))).collect();
let reader_extern_units = vec![HashMap::new(); n];
let unit_match = UnitMatchIndex::build(&readers, &unit_keys, &reader_extern_units);
WorkspaceIndex {
readers,
paths: shards.iter().map(|(p, _, _)| p.clone()).collect(),
mtimes: vec![None; n],
source_roots: shards.iter().map(|(_, r, _)| r.map(PathBuf::from)).collect(),
unit_keys,
unit_match,
path_index: super::PathIndex::default(),
target_kinds: vec![None; n],
reader_generations: vec![None; n],
reader_dependencies: vec![Vec::new(); n],
reader_extern_units,
reader_file_hashes: vec![HashMap::new(); n],
own_sources: Default::default(),
reader_is_dependency: shards.iter().map(|(_, _, d)| *d).collect(),
meta_paths: vec![None; n],
meta_mtimes: vec![None; n],
last_reloaded_files: std::collections::HashSet::new(),
root_dir: None,
workspace_root: Some(PathBuf::from(ws_root)),
manifest_path: None,
manifest_mtime: None,
manifest_len: None,
manifest_hash: None,
manifest_generation: None,
manifest_ino: None,
active_variant_id: None,
sysroot_cas_key: None,
instance_id: 1,
generation: 1,
}
}
fn target(ws: &WorkspaceIndex, idx: usize, file: &str) -> Option<String> {
ws.target_file_for_reader(idx, file).map(|c| c.into_owned())
}
#[test]
fn test_root_package_shard_does_not_claim_nested_crate_file() {
let dir = tempfile::tempdir().unwrap();
let root = write_shard(dir.path(), "bevy", &[("src/lib.rs", "root_item", 3)]);
let nested = write_shard(dir.path(), "bevy_time", &[("crates/time/src/lib.rs", "time_item", 10)]);
let ws = workspace(&[(root, Some("/ws"), false), (nested, Some("/ws/crates/time"), false)], "/ws");
assert_eq!(target(&ws, 0, "/ws/crates/time/src/lib.rs"), None, "stored src/lib.rs is not crates/time/src/lib.rs");
assert_eq!(target(&ws, 0, "/ws/src/lib.rs").as_deref(), Some("src/lib.rs"));
assert_eq!(target(&ws, 1, "/ws/crates/time/src/lib.rs").as_deref(), Some("crates/time/src/lib.rs"));
assert_eq!(target(&ws, 1, "/ws/src/lib.rs"), None, "the nested crate's root does not contain the workspace lib");
assert_eq!(
ws.find_definition_at("/ws/crates/time/src/lib.rs", 3, 2).map(|d| d.name),
None,
"line 3 of the nested file is empty; the root crate's item at line 3 of its own lib must not answer"
);
assert_eq!(ws.find_definition_at("/ws/crates/time/src/lib.rs", 10, 2).map(|d| d.name), Some("time_item"));
assert_eq!(ws.find_definition_at("/ws/src/lib.rs", 3, 2).map(|d| d.name), Some("root_item"));
}
#[cfg(unix)]
#[test]
fn test_relative_inputs_anchor_to_a_root_and_match_whole_paths() {
let dir = tempfile::tempdir().unwrap();
let serde = write_shard(dir.path(), "serde", &[("serde/src/lib.rs", "serde_item", 2)]);
let dep = write_shard(dir.path(), "dep", &[("src/lib.rs", "dep_item", 2)]);
let ws = workspace(&[(serde, Some("/ws/serde"), false), (dep, Some("/deps/dep-1.0.0"), true)], "/ws");
assert_eq!(target(&ws, 0, "serde/src/lib.rs").as_deref(), Some("serde/src/lib.rs"), "workspace-relative input");
assert_eq!(target(&ws, 0, "src/lib.rs").as_deref(), Some("serde/src/lib.rs"), "relative to the crate root, re-expressed");
assert_eq!(target(&ws, 0, "/ws/serde/src/lib.rs").as_deref(), Some("serde/src/lib.rs"));
assert_eq!(target(&ws, 1, "src/lib.rs").as_deref(), Some("src/lib.rs"), "dependency paths are stored relative to the package");
assert_eq!(target(&ws, 1, "serde/src/lib.rs"), None, "another crate's path ends with src/lib.rs but is not the dependency's file");
assert_eq!(target(&ws, 1, "/deps/dep-1.0.0/src/lib.rs").as_deref(), Some("src/lib.rs"));
assert_eq!(target(&ws, 1, "/ws/serde/src/lib.rs"), None);
assert_eq!(ws.find_definition_at("serde/src/lib.rs", 2, 2).map(|d| d.name), Some("serde_item"));
}
#[cfg(unix)]
#[test]
fn test_a_module_included_from_outside_its_package_is_found_by_its_path() {
let dir = tempfile::tempdir().unwrap();
let root = write_shard(dir.path(), "app", &[("src/app/lib.rs", "root_item", 2)]);
let core = write_shard(dir.path(), "core_lib", &[("crates/core/src/lib.rs", "core_item", 1), ("crates/core/src/../../../src/api/client.rs", "run", 25)]);
let dep = write_shard(dir.path(), "dep", &[("src/api/client.rs", "dep_item", 25)]);
let ws = workspace(&[(root, Some("/ws"), false), (core.clone(), Some("/ws/crates/core"), false), (dep, Some("/deps/dep-1.0.0"), true)], "/ws");
let client = "/ws/src/api/client.rs";
assert_eq!(target(&ws, 1, client).as_deref(), Some("src/api/client.rs"), "the workspace-relative form names the stored `..` path");
assert_eq!(target(&ws, 0, client), None);
assert_eq!(target(&ws, 2, client), None, "a dependency's own src/api/client.rs is another file");
assert_eq!(ws.reader_indices_for_file(client), vec![1], "the crate including it, not the root package whose directory holds it");
assert_eq!(ws.reader_index_for_file(client), Some(1));
assert_eq!(ws.find_definition_at(client, 25, 2).map(|d| d.name), Some("run"));
assert_eq!(ws.reader_indices_for_file("/ws/src/app/lib.rs"), vec![0], "a file of the root package stays its own");
let hash_only = write_shard(dir.path(), "app_bin", &[]);
let mut ws = workspace(&[(hash_only, Some("/ws"), false), (core, Some("/ws/crates/core"), false)], "/ws");
ws.reader_file_hashes[0].insert(client.to_string(), 1);
assert_eq!(ws.reader_indices_for_file(client), vec![0], "the reader recording the file, not the includer");
let shard = ws.paths[0].clone();
ws.own_sources.insert(shard.clone(), ["/ws/src/app/main.rs".to_string()].into());
assert_eq!(ws.reader_indices_for_file(client), vec![1], "hashed, not its own: the includer");
ws.own_sources.insert(shard, [client.to_string()].into());
assert_eq!(ws.reader_indices_for_file(client), vec![0], "hashed and its own");
ws.reader_file_hashes[0].clear();
assert_eq!(ws.reader_indices_for_file(client), vec![1], "with nothing recorded, the includer");
}
#[cfg(unix)]
#[test]
fn test_a_parent_spelling_through_a_symlink_names_the_file_it_resolves_to() {
let dir = tempfile::tempdir().unwrap();
let base = dir.path().canonicalize().unwrap();
for d in ["plain/src/api", "plain/crates/core/src", "link/src/api", "link/crates", "other/core/src", "src/api", "shards"] {
std::fs::create_dir_all(base.join(d)).unwrap();
}
for f in ["plain/src/api/client.rs", "link/src/api/client.rs", "src/api/client.rs"] {
std::fs::write(base.join(f), "").unwrap();
}
std::os::unix::fs::symlink(base.join("other/core"), base.join("link/crates/core")).unwrap();
let stored = &[("crates/core/src/../../../src/api/client.rs", "run", 25)];
for (layout, expected) in [("plain", 1), ("link", 0)] {
let root = write_shard(&base.join("shards"), &format!("app_{layout}"), &[("src/app/lib.rs", "root_item", 2)]);
let core = write_shard(&base.join("shards"), &format!("core_{layout}"), stored);
let ws_root = base.join(layout);
let (ws_str, core_root) = (ws_root.to_str().unwrap(), ws_root.join("crates/core"));
let ws = workspace(&[(root, Some(ws_str), false), (core, core_root.to_str(), false)], ws_str);
let client = ws_root.join("src/api/client.rs");
let client = client.to_str().unwrap();
assert_eq!(ws.reader_indices_for_file(client), vec![expected], "{layout}: the reader for {client}");
let found = ws.find_definition_at(client, 25, 2).map(|d| d.name);
assert_eq!(found, (layout == "plain").then_some("run"), "{layout}: the definition in {client}");
}
}
#[cfg(unix)]
#[test]
fn test_a_linked_file_is_matched_by_its_target() {
let dir = tempfile::tempdir().unwrap();
let base = dir.path().canonicalize().unwrap();
for d in ["ws/src", "ws/crates/core/src", "shared", "shards"] {
std::fs::create_dir_all(base.join(d)).unwrap();
}
std::fs::write(base.join("shared/client.rs"), "").unwrap();
std::os::unix::fs::symlink(base.join("shared/client.rs"), base.join("ws/src/client.rs")).unwrap();
let target = base.join("shared/client.rs");
let target = target.to_str().unwrap();
let (ws_root, query) = (base.join("ws"), base.join("ws/src/client.rs"));
let (ws_str, query) = (ws_root.to_str().unwrap(), query.to_str().unwrap());
let core_root = ws_root.join("crates/core");
let root = write_shard(&base.join("shards"), "app", &[]);
let core = write_shard(&base.join("shards"), "core_lib", &[(target, "run", 3)]);
let mut ws = workspace(&[(root, Some(ws_str), false), (core, core_root.to_str(), false)], ws_str);
assert_eq!(ws.reader_indices_for_file(query), vec![1], "the includer storing the target");
assert_eq!(ws.find_definition_at(query, 3, 2).map(|d| d.name), Some("run"));
ws.reader_file_hashes[0].insert(query.to_string(), 1);
let shard = ws.paths[0].clone();
ws.own_sources.insert(shard, [target.to_string()].into());
assert_eq!(ws.reader_indices_for_file(query), vec![0], "hashed under the link, own under its target");
}
#[cfg(unix)]
#[test]
fn test_a_linked_file_with_its_target_elsewhere_in_the_workspace() {
let dir = tempfile::tempdir().unwrap();
let base = dir.path().canonicalize().unwrap();
for d in ["ws/src", "ws/shared", "ws/crates/core/src", "shards"] {
std::fs::create_dir_all(base.join(d)).unwrap();
}
std::fs::write(base.join("ws/shared/client.rs"), "").unwrap();
std::os::unix::fs::symlink(base.join("ws/shared/client.rs"), base.join("ws/src/client.rs")).unwrap();
let (ws_root, query) = (base.join("ws"), base.join("ws/src/client.rs"));
let (ws_str, query) = (ws_root.to_str().unwrap(), query.to_str().unwrap());
let core_root = ws_root.join("crates/core");
let root = write_shard(&base.join("shards"), "app", &[("src/app.rs", "root_item", 1)]);
let core = write_shard(&base.join("shards"), "core_lib", &[("shared/client.rs", "run", 3)]);
let mut ws = workspace(&[(root, Some(ws_str), false), (core, core_root.to_str(), false)], ws_str);
assert_eq!(ws.reader_indices_for_file(query), vec![1]);
assert_eq!(target(&ws, 1, query).as_deref(), Some("shared/client.rs"), "the stored spelling of the target");
assert_eq!(ws.find_definition_at(query, 3, 2).map(|d| d.name), Some("run"));
let target = ws_root.join("shared/client.rs").to_str().unwrap().to_string();
ws.reader_file_hashes[0].insert(target.clone(), 1);
let shard = ws.paths[0].clone();
ws.own_sources.insert(shard, [target].into());
assert_eq!(ws.reader_indices_for_file(query), vec![0], "hashed and own under the target");
}
#[cfg(unix)]
#[test]
fn test_includer_spellings_with_dot_and_through_a_missing_directory() {
let dir = tempfile::tempdir().unwrap();
let base = dir.path().canonicalize().unwrap();
for d in ["ws/src/api", "shards"] {
std::fs::create_dir_all(base.join(d)).unwrap();
}
std::fs::write(base.join("ws/src/api/client.rs"), "").unwrap();
let ws_root = base.join("ws");
let ws_str = ws_root.to_str().unwrap();
let file = |rel: &str| ws_root.join(rel).to_str().unwrap().to_string();
let root = write_shard(&base.join("shards"), "app", &[("src/app.rs", "root_item", 1)]);
let dotted = write_shard(&base.join("shards"), "dotted", &[("src/./api/client.rs", "run", 3)]);
let ws = workspace(&[(root.clone(), Some(ws_str), false), (dotted, Some(&file("crates/dotted")), false)], ws_str);
assert_eq!(ws.reader_indices_for_file(&file("src/api/client.rs")), vec![1], "`src/./api/client.rs` is the file");
let gone = &[("crates/gone/src/../../../src/api/client.rs", "run", 3), ("crates/gone/src/../../../src/api/unsaved.rs", "later", 1)];
let gone = write_shard(&base.join("shards"), "gone", gone);
let ws = workspace(&[(root.clone(), Some(ws_str), false), (gone, Some(&file("crates/gone")), false)], ws_str);
assert_eq!(ws.reader_indices_for_file(&file("src/api/client.rs")), vec![0], "on disk, and the spelling does not resolve");
assert_eq!(ws.reader_indices_for_file(&file("src/api/unsaved.rs")), vec![1], "not on disk: its lexical reading");
std::fs::create_dir_all(base.join("other/core/src")).unwrap();
std::fs::create_dir_all(base.join("ws/links")).unwrap();
std::os::unix::fs::symlink(base.join("other/core"), base.join("ws/links/core")).unwrap();
let linked = write_shard(&base.join("shards"), "linked", &[("links/core/src/../../../src/api/unsaved_link.rs", "later", 1)]);
let ws = workspace(&[(root.clone(), Some(ws_str), false), (linked, Some(&file("links/core")), false)], ws_str);
assert_eq!(ws.reader_indices_for_file(&file("src/api/unsaved_link.rs")), vec![1], "not on disk, through a link: its lexical reading");
use std::os::unix::fs::PermissionsExt;
let locked = base.join("ws/locked");
std::fs::create_dir_all(&locked).unwrap();
std::fs::write(locked.join("x.rs"), "").unwrap();
let blocked = write_shard(&base.join("shards"), "blocked", &[("crates/c/src/../../../locked/x.rs", "run", 1)]);
let ws = workspace(&[(root, Some(ws_str), false), (blocked, Some(&file("crates/c")), false)], ws_str);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
let enforced = std::fs::read_dir(&locked).is_err(); let readers = ws.reader_indices_for_file(&file("locked/x.rs"));
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
if enforced {
assert_eq!(readers, vec![0], "unreadable is no lexical match");
}
}
#[test]
fn test_file_outside_every_root_has_no_reader() {
let dir = tempfile::tempdir().unwrap();
let a = write_shard(dir.path(), "dep_a", &[("src/lib.rs", "a_item", 2)]);
let b = write_shard(dir.path(), "dep_b", &[("src/lib.rs", "b_item", 2)]);
let ws_crate = write_shard(dir.path(), "ws_crate", &[("ws_crate/src/lib.rs", "ws_item", 2)]);
let ws = workspace(&[(a, Some("/deps/a-1.0.0"), true), (b, Some("/deps/b-2.0.0"), true), (ws_crate, Some("/ws/ws_crate"), false)], "/ws");
assert_eq!(
ws.reader_indices_for_file("/ws/tests/ui/src/lib.rs"),
Vec::<usize>::new(),
"a file under no source root is owned by nobody, even though its path ends with src/lib.rs"
);
assert_eq!(ws.find_definition_at("/ws/tests/ui/src/lib.rs", 2, 2).map(|d| d.name), None);
assert_eq!(ws.reader_indices_for_file("/ws/ws_crate/src/lib.rs"), vec![2]);
}
#[test]
fn test_new_file_under_a_root_is_routed_but_unowned() {
let dir = tempfile::tempdir().unwrap();
let serde = write_shard(dir.path(), "serde", &[("serde/src/lib.rs", "serde_item", 2)]);
let ws = workspace(&[(serde, Some("/ws/serde"), false)], "/ws");
assert_eq!(ws.reader_indices_for_file("/ws/serde/src/new.rs"), vec![0], "the crate's readers are candidates");
assert_eq!(target(&ws, 0, "/ws/serde/src/new.rs"), None, "but none of them stores the new file");
assert_eq!(ws.find_definition_at("/ws/serde/src/new.rs", 1, 1).map(|d| d.name), None);
}
#[test]
fn test_sysroot_reader_only_answers_its_stored_paths() {
let dir = tempfile::tempdir().unwrap();
let core = write_shard(dir.path(), "core", &[("library/core/src/lib.rs", "core_item", 5)]);
let ws = workspace(&[(core, None, true)], "/ws");
assert_eq!(target(&ws, 0, "library/core/src/lib.rs").as_deref(), Some("library/core/src/lib.rs"));
assert_eq!(target(&ws, 0, "/ws/core/src/lib.rs"), None, "a workspace file whose path ends with core/src/lib.rs is not the sysroot file");
assert_eq!(ws.find_definition_at("library/core/src/lib.rs", 5, 2).map(|d| d.name), Some("core_item"));
}
#[test]
fn test_single_shard_opened_alone_resolves_against_its_directory() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir_all(dir.path().join("src")).unwrap();
std::fs::write(dir.path().join("src/lib.rs"), "pub fn alone() {}\n").unwrap();
let shard = write_shard(dir.path(), "alone", &[("src/lib.rs", "alone", 1)]);
let ws = WorkspaceIndex::open(&shard).expect("open the shard on its own");
let file = dir.path().join("src/lib.rs");
let file = file.to_str().unwrap();
assert_eq!(ws.workspace_root, None, "a lone shard records no workspace root");
assert_eq!(ws.reader_indices_for_file(file), vec![0]);
assert_eq!(target(&ws, 0, file).as_deref(), Some("src/lib.rs"));
assert_eq!(ws.find_definition_at(file, 1, 2).map(|d| d.name), Some("alone"));
let elsewhere = dir.path().join("other/src/lib.rs");
assert_eq!(target(&ws, 0, elsewhere.to_str().unwrap()), None, "a nested path is not the stored src/lib.rs");
}