use super::lexer::{balanced_group_end, clean_with_positions, is_ident_byte, read_path_string};
use super::path_vocab::{canonical_segment, is_mod_declaration_keyword, path_within};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
#[allow(clippy::too_many_arguments)]
pub(crate) fn governed_files(
src_dir: &Path,
files: &[PathBuf],
module: &str,
reachable: &std::collections::BTreeSet<String>,
inline_only: &std::collections::BTreeSet<String>,
remapped: &[(PathBuf, String)],
remap_shadowed: &std::collections::BTreeSet<String>,
root_relative: Option<&Path>,
) -> Vec<(PathBuf, String)> {
let structural = files.iter().filter_map(|file| {
let relative = file.strip_prefix(src_dir).ok()?;
let module_path = module_path_of(relative, root_relative);
if inline_only.contains(&module_path) {
return None;
}
if remap_shadowed.contains(&module_path) {
return None;
}
if !reachable.contains(&module_path) {
return None;
}
if path_within(&module_path, module) {
Some((file.clone(), module_path))
} else {
None
}
});
let remap_entries = remapped.iter().filter_map(|(file, module_path)| {
if path_within(module_path, module) {
Some((file.clone(), module_path.clone()))
} else {
None
}
});
let mut seen = std::collections::BTreeSet::new();
structural
.chain(remap_entries)
.filter(|entry| seen.insert(entry.clone()))
.collect()
}
#[allow(clippy::type_complexity)]
pub(crate) fn reachable_modules(
src_dir: &Path,
files: &[PathBuf],
root_relative: Option<&Path>,
) -> Result<
(
std::collections::BTreeSet<String>,
std::collections::BTreeSet<String>,
Vec<(PathBuf, String)>,
std::collections::BTreeSet<String>,
),
String,
> {
let mut by_module: std::collections::BTreeMap<String, Vec<&PathBuf>> = Default::default();
for file in files {
if let Ok(relative) = file.strip_prefix(src_dir) {
by_module
.entry(module_path_of(relative, root_relative))
.or_default()
.push(file);
}
}
let files_literal: HashSet<&PathBuf> = files.iter().collect();
#[derive(Clone)]
enum ScanSource {
File(PathBuf, PathBuf, PathBuf, HashSet<PathBuf>),
Body(PathBuf, usize, usize, PathBuf, PathBuf, HashSet<PathBuf>),
}
let mut reachable = std::collections::BTreeSet::new();
let mut inline_only = std::collections::BTreeSet::new();
let mut remapped: Vec<(PathBuf, String)> = Vec::new();
let mut remap_shadowed = std::collections::BTreeSet::new();
reachable.insert("crate".to_string());
let mut sources: std::collections::BTreeMap<String, Vec<ScanSource>> = Default::default();
if let Some(root_files) = by_module.get("crate") {
let mut root_ancestors = HashSet::new();
for f in root_files {
if let Ok(canon) = std::fs::canonicalize(f) {
root_ancestors.insert(canon);
}
}
sources.insert(
"crate".to_string(),
root_files
.iter()
.map(|f| {
ScanSource::File(
(*f).clone(),
src_dir.to_path_buf(),
src_dir.to_path_buf(),
root_ancestors.clone(),
)
})
.collect(),
);
}
let mut queue = vec!["crate".to_string()];
while let Some(module) = queue.pop() {
let Some(scan_sources) = sources.get(&module).cloned() else {
continue; };
let mut child_kinds: std::collections::BTreeMap<String, (bool, bool)> = Default::default();
let mut child_bodies: std::collections::BTreeMap<
String,
Vec<(
PathBuf,
usize,
usize,
PathBuf,
Option<PathBuf>,
HashSet<PathBuf>,
)>,
> = Default::default();
let mut child_direct_paths: std::collections::BTreeMap<
String,
Vec<(PathBuf, PathBuf, HashSet<PathBuf>)>,
> = Default::default();
let mut child_plain_bases: std::collections::BTreeMap<
String,
Vec<(PathBuf, HashSet<PathBuf>)>,
> = Default::default();
for source in &scan_sources {
let (file, text, cleaned, positions, range, path_base, child_base, source_ancestors) =
match source {
ScanSource::File(file, path_base, child_base, ancestors) => {
let text = std::fs::read_to_string(file).map_err(|err| {
format!("cannot read source file '{}': {err}", file.display())
})?;
let (cleaned, positions) = clean_with_positions(&text);
let len = cleaned.len();
(
file.clone(),
text,
cleaned,
positions,
0..len,
path_base.clone(),
child_base.clone(),
ancestors.clone(),
)
}
ScanSource::Body(file, start, end, path_base, child_base, ancestors) => {
let text = std::fs::read_to_string(file).map_err(|err| {
format!("cannot read source file '{}': {err}", file.display())
})?;
let (cleaned, positions) = clean_with_positions(&text);
(
file.clone(),
text,
cleaned,
positions,
*start..*end,
path_base.clone(),
child_base.clone(),
ancestors.clone(),
)
}
};
for declared in declared_modules_in(&cleaned, range) {
let seen = child_kinds.entry(declared.name.clone()).or_default();
if declared.is_inline {
seen.0 = true;
let relocated_base = declared.direct_path_eq.and_then(|eq_cleaned| {
let &orig_eq = positions.get(eq_cleaned)?;
let rel = read_path_string(text.as_bytes(), orig_eq + 1, text.len())?;
Some(path_base.join(rel))
});
if let Some((start, end)) = declared.body {
child_bodies.entry(declared.name).or_default().push((
file.clone(),
start,
end,
child_base.clone(),
relocated_base,
source_ancestors.clone(),
));
}
continue;
}
let Some(eq_cleaned) = declared.direct_path_eq else {
seen.1 = true;
child_plain_bases
.entry(declared.name)
.or_default()
.push((child_base.clone(), source_ancestors.clone()));
continue;
};
let Some(&orig_eq) = positions.get(eq_cleaned) else {
continue;
};
if let Some(rel) = read_path_string(text.as_bytes(), orig_eq + 1, text.len()) {
child_direct_paths.entry(declared.name).or_default().push((
PathBuf::from(rel),
path_base.clone(),
source_ancestors.clone(),
));
}
}
}
for (child, (seen_inline, seen_plain_file)) in child_kinds {
let child_path = format!("{module}::{child}");
if seen_inline {
if let Some(bodies) = child_bodies.remove(&child) {
sources
.entry(child_path.clone())
.or_default()
.extend(bodies.into_iter().map(
|(file, start, end, base, relocated_base, source_ancestors)| {
let inline_dir =
relocated_base.unwrap_or_else(|| base.join(&child));
ScanSource::Body(
file,
start,
end,
inline_dir.clone(),
inline_dir,
source_ancestors,
)
},
));
}
}
if seen_inline && !seen_plain_file {
inline_only.insert(child_path.clone());
}
if seen_plain_file {
let mut already_sourced: HashSet<PathBuf> = HashSet::new();
let mut any_structural_match = false;
for (base, source_ancestors) in
child_plain_bases.remove(&child).into_iter().flatten()
{
for candidate in [
base.join(format!("{child}.rs")),
base.join(&child).join("mod.rs"),
] {
if !candidate.is_file() {
continue;
}
let Ok(canon) = std::fs::canonicalize(&candidate) else {
continue;
};
if !already_sourced.insert(canon.clone()) {
continue;
}
if source_ancestors.contains(&canon) {
return Err(format!(
"module '{child_path}' resolves to '{}', which cycles back to an already-open source file",
candidate.display()
));
}
let structurally_matches = files_literal.contains(&candidate)
&& candidate
.strip_prefix(src_dir)
.ok()
.is_some_and(|relative| {
module_path_of(relative, root_relative) == child_path
});
if structurally_matches {
any_structural_match = true;
} else {
remapped.push((candidate.clone(), child_path.clone()));
}
let own_dir = canon
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| base.clone());
let new_child_base = base.join(&child);
let mut anc = source_ancestors.clone();
anc.insert(canon);
sources
.entry(child_path.clone())
.or_default()
.push(ScanSource::File(candidate, own_dir, new_child_base, anc));
}
}
if !already_sourced.is_empty() && !any_structural_match {
remap_shadowed.insert(child_path.clone());
}
}
if let Some(targets) = child_direct_paths.remove(&child) {
if !seen_plain_file {
remap_shadowed.insert(child_path.clone());
}
for (rel, base, target_ancestors) in targets {
let target = base.join(&rel);
if !target.is_file() {
return Err(format!(
"module '{child_path}' is remapped by #[path = \"{}\"] to a file that does not exist: '{}'",
rel.display(),
target.display()
));
}
let canon = std::fs::canonicalize(&target)
.map_err(|err| format!("cannot resolve '{}': {err}", target.display()))?;
if target_ancestors.contains(&canon) {
return Err(format!(
"module '{child_path}' is remapped by #[path] to '{}', which cycles back to an already-open source file",
target.display()
));
}
remapped.push((target.clone(), child_path.clone()));
let own_dir = canon
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| base.clone());
let mut anc = target_ancestors.clone();
anc.insert(canon);
sources
.entry(child_path.clone())
.or_default()
.push(ScanSource::File(target, own_dir.clone(), own_dir, anc));
}
}
if reachable.insert(child_path.clone()) {
queue.push(child_path);
}
}
}
Ok((reachable, inline_only, remapped, remap_shadowed))
}
struct DeclaredModule {
name: String,
is_inline: bool,
body: Option<(usize, usize)>,
direct_path_eq: Option<usize>,
}
fn declared_modules_in(cleaned: &str, range: std::ops::Range<usize>) -> Vec<DeclaredModule> {
let bytes = cleaned.as_bytes();
let end = range.end.min(bytes.len());
let mut declared = Vec::new();
let mut depth: i32 = 0;
let mut i = range.start.min(end);
while i < end {
match bytes[i] {
b'{' => {
depth += 1;
i += 1;
}
b'}' => {
depth -= 1;
i += 1;
}
b'm' if depth == 0 && is_mod_declaration_keyword(bytes, i) => {
let mut j = i + 3;
while j < end && bytes[j].is_ascii_whitespace() {
j += 1;
}
let start = j;
while j < end
&& !bytes[j].is_ascii_whitespace()
&& bytes[j] != b';'
&& bytes[j] != b'{'
{
j += 1;
}
let ident = cleaned[start..j].trim();
let mut k = j;
while k < end && bytes[k].is_ascii_whitespace() {
k += 1;
}
if !ident.is_empty() {
match bytes.get(k) {
Some(b'{') => {
let direct_path_eq = match path_attr_before_item(bytes, i) {
PathAttrKind::Direct(eq) => Some(eq),
PathAttrKind::None | PathAttrKind::Excluded => None,
};
let close = balanced_group_end(bytes, k).unwrap_or(bytes.len());
declared.push(DeclaredModule {
name: canonical_segment(ident).to_string(),
is_inline: true,
body: Some((k + 1, close.saturating_sub(1))),
direct_path_eq,
});
i = close;
continue;
}
Some(b';') => match path_attr_before_item(bytes, i) {
PathAttrKind::Excluded => {}
PathAttrKind::None => {
declared.push(DeclaredModule {
name: canonical_segment(ident).to_string(),
is_inline: false,
body: None,
direct_path_eq: None,
});
}
PathAttrKind::Direct(eq) => {
declared.push(DeclaredModule {
name: canonical_segment(ident).to_string(),
is_inline: false,
body: None,
direct_path_eq: Some(eq),
});
}
},
_ => {}
}
}
i += 3;
}
_ => i += 1,
}
}
declared
}
#[cfg(test)]
fn declared_modules_with_kind(source: &str) -> Vec<(String, bool)> {
let (cleaned, _positions) = clean_with_positions(source);
let len = cleaned.len();
declared_modules_in(&cleaned, 0..len)
.into_iter()
.map(|declared| (declared.name, declared.is_inline))
.collect()
}
#[cfg(test)]
pub(super) fn declared_modules(source: &str) -> Vec<String> {
declared_modules_with_kind(source)
.into_iter()
.map(|(name, _)| name)
.collect()
}
enum PathAttrKind {
None,
Direct(usize),
Excluded,
}
fn path_attr_before_item(bytes: &[u8], mod_index: usize) -> PathAttrKind {
let mut start = 0;
for i in (0..mod_index).rev() {
if matches!(bytes[i], b';' | b'{' | b'}') {
start = i + 1;
break;
}
}
match attr_prefix_path_kind(&bytes[start..mod_index]) {
PathAttrKind::Direct(relative) => PathAttrKind::Direct(start + relative),
other => other,
}
}
fn attr_prefix_path_kind(bytes: &[u8]) -> PathAttrKind {
let mut i = 0;
let mut excluded = false;
while i < bytes.len() {
if bytes[i] != b'#' {
i += 1;
continue;
}
i += 1;
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if bytes.get(i) != Some(&b'[') {
continue;
}
i += 1;
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if bytes[i..].starts_with(b"path")
&& bytes.get(i + 4).is_none_or(|byte| !is_ident_byte(*byte))
{
let mut j = i + 4;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if bytes.get(j) == Some(&b'=') {
return PathAttrKind::Direct(j);
}
excluded = true;
continue;
}
if bytes[i..].starts_with(b"cfg_attr")
&& bytes.get(i + 8).is_none_or(|byte| !is_ident_byte(*byte))
&& cfg_attr_prefix_has_path(&bytes[i + 8..])
{
excluded = true;
continue;
}
}
if excluded {
PathAttrKind::Excluded
} else {
PathAttrKind::None
}
}
fn cfg_attr_prefix_has_path(bytes: &[u8]) -> bool {
let mut i = 0;
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if bytes.get(i) != Some(&b'(') {
return false;
}
i += 1;
let mut depth = 1usize;
let mut past_predicate = false;
while i < bytes.len() && depth > 0 {
match bytes[i] {
b'"' => {
i += 1;
while i < bytes.len() && bytes[i] != b'"' {
if bytes[i] == b'\\' {
i += 1;
}
i += 1;
}
i += 1;
}
b'(' => {
depth += 1;
i += 1;
}
b')' => {
depth -= 1;
i += 1;
}
b',' if depth == 1 => {
past_predicate = true;
i += 1;
}
byte if depth == 1 && past_predicate && is_ident_byte(byte) => {
let start = i;
while i < bytes.len() && is_ident_byte(bytes[i]) {
i += 1;
}
let ident = &bytes[start..i];
if ident == b"path" {
let mut j = i;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if bytes.get(j) == Some(&b'=') {
return true;
}
} else if ident == b"cfg_attr" && cfg_attr_prefix_has_path(&bytes[i..]) {
return true;
}
}
_ => i += 1,
}
}
false
}
fn module_path_of(relative: &Path, root_relative: Option<&Path>) -> String {
if root_relative == Some(relative) {
return "crate".to_string();
}
let custom_root = root_relative.is_some_and(|r| !is_conventional_root(r));
file_module_path(relative, custom_root)
}
fn is_conventional_root(relative: &Path) -> bool {
relative
.file_name()
.is_some_and(|n| matches!(n.to_string_lossy().as_ref(), "lib.rs" | "main.rs"))
&& relative.components().count() == 1
}
fn file_module_path(relative: &Path, custom_root: bool) -> String {
let components: Vec<String> = relative
.components()
.map(|component| component.as_os_str().to_string_lossy().into_owned())
.collect();
let mut segments = vec![String::from("crate")];
let last = components.len().saturating_sub(1);
for (index, component) in components.iter().enumerate() {
if index == last {
let stem = component.strip_suffix(".rs").unwrap_or(component);
let segmentless = stem == "mod"
|| (!custom_root && components.len() == 1 && matches!(stem, "lib" | "main"));
if !segmentless {
segments.push(canonical_segment(stem).to_string());
}
} else {
segments.push(canonical_segment(component).to_string());
}
}
segments.join("::")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::module_scan::rust_files;
#[test]
fn declared_modules_finds_only_top_level_declarations() {
let source = r#"
pub mod kernel;
mod projection;
pub(crate) mod runner;
mod inline { mod nested_child; } // nested_child is depth 1, not a root module
// mod commented_out;
fn f() { let _ = "mod string_literal;"; }
"#;
let mut mods = declared_modules(source);
mods.sort();
assert_eq!(
mods,
vec![
"inline".to_string(),
"kernel".to_string(),
"projection".to_string(),
"runner".to_string(),
],
"only top-level mod declarations count; nested, commented, and quoted are excluded"
);
}
#[test]
fn reachable_modules_follows_mod_declarations_not_filenames() {
let dir = std::env::temp_dir().join(format!("guibiao-reach-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("kernel")).expect("create temp src/kernel");
std::fs::write(
src.join("lib.rs"),
"pub mod kernel;\nuse serde::Deserialize;\n",
)
.expect("write lib.rs");
std::fs::write(src.join("kernel.rs"), "// kernel declares no submodule\n")
.expect("write kernel.rs");
std::fs::write(src.join("serde.rs"), "// root orphan, undeclared\n")
.expect("write serde.rs");
std::fs::write(
src.join("kernel/orphan.rs"),
"use crate::projection::Thing;\n",
)
.expect("write kernel/orphan.rs");
let files = rust_files(&src).expect("list files");
let (reachable, _inline_only, _remapped, _remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let _ = std::fs::remove_dir_all(&dir);
assert!(reachable.contains("crate"), "{reachable:?}");
assert!(
reachable.contains("crate::kernel"),
"a declared `mod kernel;` is reachable: {reachable:?}"
);
assert!(
!reachable.contains("crate::serde"),
"an undeclared root orphan is not reachable: {reachable:?}"
);
assert!(
!reachable.contains("crate::kernel::orphan"),
"an undeclared subtree orphan is not reachable: {reachable:?}"
);
}
#[test]
fn a_stray_lib_beside_a_custom_root_is_not_a_second_crate_root() {
let dir = std::env::temp_dir().join(format!("guibiao-custom-root-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(&src).expect("create temp src");
std::fs::write(src.join("core.rs"), "pub mod real;\n").expect("write core.rs");
std::fs::write(
src.join("real.rs"),
"// real, declared from the true root\n",
)
.expect("write real.rs");
std::fs::write(src.join("lib.rs"), "pub mod ghost;\n").expect("write stray lib.rs");
std::fs::write(
src.join("ghost.rs"),
"// declared only by the uncompiled lib.rs\n",
)
.expect("write ghost.rs");
let files = rust_files(&src).expect("list files");
let root_relative = std::path::PathBuf::from("core.rs");
let (reachable, _inline_only, _remapped, _remap_shadowed) =
reachable_modules(&src, &files, Some(&root_relative)).expect("walk modules");
let _ = std::fs::remove_dir_all(&dir);
assert!(
reachable.contains("crate"),
"the custom root seeds crate: {reachable:?}"
);
assert!(
reachable.contains("crate::real"),
"a module declared from the true root is reachable: {reachable:?}"
);
assert!(
!reachable.contains("crate::ghost"),
"a module declared only by the stray, uncompiled lib.rs is NOT reachable: {reachable:?}"
);
}
#[test]
fn path_remapped_modules_are_followed_to_their_target() {
let dir = std::env::temp_dir().join(format!("guibiao-path-remap-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(&src).expect("create temp src");
std::fs::write(
src.join("lib.rs"),
"#[path = \"weird.rs\"]\npub mod kernel;\npub mod normal;\n",
)
.expect("write lib.rs");
let target = src.join("weird.rs");
std::fs::write(&target, "use crate::projection::Thing;\n").expect("write remapped file");
let orphan = src.join("kernel.rs");
std::fs::write(&orphan, "use crate::wrong_file_if_observed::Thing;\n")
.expect("write conventional orphan");
std::fs::write(src.join("normal.rs"), "// normal module\n").expect("write normal.rs");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, remapped, remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let governed = governed_files(
&src,
&files,
"crate",
&reachable,
&inline_only,
&remapped,
&remap_shadowed,
None,
);
let _ = std::fs::remove_dir_all(&dir);
assert!(reachable.contains("crate::normal"), "{reachable:?}");
assert!(
reachable.contains("crate::kernel"),
"a #[path]-remapped module is now followed to its target: {reachable:?}"
);
assert_eq!(
remapped,
vec![(target.clone(), "crate::kernel".to_string())],
"the remap is recorded under its logical path: {remapped:?}"
);
assert!(
governed
.iter()
.any(|(file, module)| file == &target && module == "crate::kernel"),
"the real remapped target is governed under crate::kernel: {governed:?}"
);
assert!(
!governed.iter().any(|(file, _)| file == &orphan),
"the conventional orphan must not be governed in the remap's place: {governed:?}"
);
}
#[test]
fn a_plain_child_of_a_path_remapped_module_is_governed_from_the_remaps_own_directory() {
let dir =
std::env::temp_dir().join(format!("guibiao-remap-plain-child-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("other")).expect("create temp src/other");
std::fs::write(
src.join("lib.rs"),
"#[path = \"other/weird.rs\"]\npub mod kernel;\n",
)
.expect("write lib.rs");
std::fs::write(src.join("other/weird.rs"), "pub mod child;\n").expect("write remap target");
let child_file = src.join("other/child.rs");
std::fs::write(&child_file, "use crate::projection::Thing;\n").expect("write child.rs");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, remapped, remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let governed = governed_files(
&src,
&files,
"crate",
&reachable,
&inline_only,
&remapped,
&remap_shadowed,
None,
);
let _ = std::fs::remove_dir_all(&dir);
assert!(
reachable.contains("crate::kernel::child"),
"the remap target's own plain child is reachable: {reachable:?}"
);
assert!(
governed
.iter()
.any(|(file, module)| file == &child_file && module == "crate::kernel::child"),
"the remap target's own plain child is governed under its logical path, so its real \
`use` is observed: {governed:?}"
);
}
#[test]
fn path_attribute_detection_is_specific() {
assert_eq!(
declared_modules("#[pathology]\npub mod kernel;\n"),
vec!["kernel".to_string()],
"only the real `path` attribute is a remap marker"
);
assert_eq!(
declared_modules("# [ path = \"weird.rs\" ]\npub mod kernel;\n"),
vec!["kernel".to_string()],
);
}
#[test]
fn a_cfg_attr_nested_path_is_a_remap() {
assert!(
declared_modules("#[cfg_attr(windows, path = \"os/windows.rs\")]\npub mod os;\n")
.is_empty(),
"a cfg_attr-nested path remap puts the FILE module out of scope",
);
assert!(
declared_modules("#[cfg_attr(all(unix), deprecated, path = \"p.rs\")]\nmod a;\n")
.is_empty(),
);
assert!(
declared_modules("#[cfg_attr(a, cfg_attr(b, path = \"secret.rs\"))]\npub mod m;\n")
.is_empty(),
"a nested cfg_attr path remap is detected",
);
}
#[test]
fn an_unconditional_path_attr_wins_regardless_of_cfg_attr_order() {
assert_eq!(
declared_modules(
"#[cfg_attr(some_platform, path = \"b.rs\")]\n#[path = \"a.rs\"]\npub mod x;\n"
),
vec!["x".to_string()],
"cfg_attr before the direct #[path] must not drop the module",
);
assert_eq!(
declared_modules(
"#[path = \"a.rs\"]\n#[cfg_attr(some_platform, path = \"b.rs\")]\npub mod x;\n"
),
vec!["x".to_string()],
"the direct #[path] first must keep working as before",
);
}
#[test]
fn a_cfg_attr_without_a_path_meta_is_not_a_remap() {
assert_eq!(
declared_modules("#[cfg_attr(test, derive(Debug))]\npub mod real;\n"),
vec!["real".to_string()],
"a cfg_attr without a path meta is not a remap",
);
assert_eq!(
declared_modules("#[cfg_attr(feature = \"path\", deprecated)]\npub mod real;\n"),
vec!["real".to_string()],
"a `path` inside a predicate string is not a path meta",
);
assert_eq!(
declared_modules("#[cfg_attr(unix, target_path = \"x\")]\npub mod real;\n"),
vec!["real".to_string()],
);
assert_eq!(
declared_modules("#[cfg_attr(a, cfg_attr(b, deprecated))]\npub mod real;\n"),
vec!["real".to_string()],
"a nested cfg_attr without a path meta is not a remap",
);
assert_eq!(
declared_modules("#[cfg_attr(path = \"x\", deprecated)]\npub mod real;\n"),
vec!["real".to_string()],
"a `path` cfg predicate key is not an applied path remap",
);
}
#[test]
fn a_cfg_attr_nested_path_on_an_inline_module_does_not_drop_it() {
assert_eq!(
declared_modules(
"#[cfg_attr(windows, path = \"x.rs\")]\npub mod a { pub mod inner; }\n"
),
vec!["a".to_string()],
);
}
#[test]
fn a_path_attr_on_an_inline_module_does_not_drop_it() {
assert_eq!(
declared_modules("#[path = \"x.rs\"]\npub mod a { pub mod inner; }\n"),
vec!["a".to_string()],
"an inline module with a (no-op) #[path] is still declared",
);
assert_eq!(
declared_modules("#[path = \"x.rs\"]\npub mod a;\n"),
vec!["a".to_string()],
"a #[path]-remapped FILE module is declared, to be followed to its target",
);
}
#[test]
fn a_block_comment_before_a_mod_name_does_not_fuse_it() {
assert_eq!(
declared_modules("mod/*c*/foo;"),
vec!["foo".to_string()],
"a block comment after `mod` must not swallow the declaration",
);
}
#[test]
fn a_custom_crate_root_filename_maps_to_crate() {
let dir = std::env::temp_dir().join(format!("guibiao-customroot-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(&src).expect("mkdir src");
std::fs::write(src.join("core.rs"), "pub mod sub;\n").expect("write core.rs");
std::fs::write(src.join("sub.rs"), "// sub\n").expect("write sub.rs");
let files = rust_files(&src).expect("list files");
let (with_root, _, _, _) =
reachable_modules(&src, &files, Some(std::path::Path::new("core.rs"))).expect("walk");
let (without_root, _, _, _) = reachable_modules(&src, &files, None).expect("walk");
let _ = std::fs::remove_dir_all(&dir);
assert!(
with_root.contains("crate::sub"),
"with the custom root mapped to crate, its submodule is reachable: {with_root:?}"
);
assert!(
!without_root.contains("crate::sub"),
"without the root override, core.rs maps to crate::core and sub is unreachable: {without_root:?}"
);
}
#[test]
fn declared_modules_ignores_a_mod_inside_a_macro_invocation() {
assert!(declared_modules("some_macro!( mod ghost; );").is_empty());
assert!(declared_modules("some_macro![ mod ghost; ];").is_empty());
assert!(declared_modules("macro_rules! m { () => { mod ghost; }; }").is_empty());
assert_eq!(declared_modules("mod real;"), vec!["real".to_string()]);
}
#[test]
fn an_inline_modules_file_backed_child_is_reachable() {
let dir = std::env::temp_dir().join(format!("guibiao-inline-child-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("parent")).expect("create temp src/parent");
std::fs::write(
src.join("lib.rs"),
"pub mod parent {\n pub mod child;\n}\n",
)
.expect("write lib.rs");
std::fs::write(
src.join("parent/child.rs"),
"use crate::projection::Thing;\n",
)
.expect("write parent/child.rs");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, _remapped, _remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let _ = std::fs::remove_dir_all(&dir);
assert!(
inline_only.contains("crate::parent"),
"parent has no file of its own: {inline_only:?}"
);
assert!(
reachable.contains("crate::parent::child"),
"the real compiled file-backed child of an inline module must be reachable: {reachable:?}"
);
assert!(
!inline_only.contains("crate::parent::child"),
"the child is file-backed, not inline-only: {inline_only:?}"
);
}
#[test]
fn an_inline_modules_file_backed_child_is_governed() {
let dir =
std::env::temp_dir().join(format!("guibiao-inline-child-gov-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("parent")).expect("create temp src/parent");
std::fs::write(
src.join("lib.rs"),
"pub mod parent {\n pub mod child;\n}\n",
)
.expect("write lib.rs");
let child_file = src.join("parent/child.rs");
std::fs::write(&child_file, "use crate::projection::Thing;\n").expect("write child.rs");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, remapped, remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let governed = governed_files(
&src,
&files,
"crate",
&reachable,
&inline_only,
&remapped,
&remap_shadowed,
None,
);
let _ = std::fs::remove_dir_all(&dir);
assert!(
governed
.iter()
.any(|(file, module)| file == &child_file && module == "crate::parent::child"),
"the real compiled child file must be governed: {governed:?}"
);
}
#[test]
fn a_chain_of_inline_modules_reaches_its_file_backed_leaf() {
let dir = std::env::temp_dir().join(format!("guibiao-inline-chain-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("kernel/parent/a/b")).expect("mkdirs");
std::fs::write(src.join("lib.rs"), "pub mod kernel;\n").expect("write lib.rs");
std::fs::write(
src.join("kernel.rs"),
"pub mod parent {\n pub mod a {\n pub mod b {\n pub mod c;\n }\n }\n}\n",
)
.expect("write kernel.rs");
std::fs::write(
src.join("kernel/parent/a/b/c.rs"),
"use crate::projection::Thing;\n",
)
.expect("write the deep leaf file");
let files = rust_files(&src).expect("list files");
let (reachable, _inline_only, _remapped, _remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let _ = std::fs::remove_dir_all(&dir);
assert!(
reachable.contains("crate::kernel::parent::a::b::c"),
"a file-backed leaf beneath a chain of inline modules must be reachable: {reachable:?}"
);
}
#[test]
fn an_inline_modules_mod_rs_style_child_is_reachable() {
let dir = std::env::temp_dir().join(format!("guibiao-inline-modrs-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("parent/child")).expect("mkdirs");
std::fs::write(
src.join("lib.rs"),
"pub mod parent {\n pub mod child;\n}\n",
)
.expect("write lib.rs");
std::fs::write(
src.join("parent/child/mod.rs"),
"use crate::projection::Thing;\n",
)
.expect("write parent/child/mod.rs");
let files = rust_files(&src).expect("list files");
let (reachable, _inline_only, _remapped, _remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let _ = std::fs::remove_dir_all(&dir);
assert!(
reachable.contains("crate::parent::child"),
"a mod.rs-style child beneath an inline parent must be reachable: {reachable:?}"
);
}
#[test]
fn an_inline_only_grandparents_conventional_orphan_stays_excluded() {
let dir =
std::env::temp_dir().join(format!("guibiao-inline-orphan-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("parent")).expect("mkdirs");
std::fs::write(
src.join("lib.rs"),
"pub mod parent {\n pub mod child;\n}\n",
)
.expect("write lib.rs");
std::fs::write(
src.join("parent/child.rs"),
"use crate::projection::Thing;\n",
)
.expect("write the real compiled child");
std::fs::write(
src.join("parent.rs"),
"use crate::wrong_file_if_observed::Thing;\n",
)
.expect("write the conventional orphan Rust never compiles");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, _remapped, _remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let _ = std::fs::remove_dir_all(&dir);
assert!(
inline_only.contains("crate::parent"),
"parent is declared inline-only: {inline_only:?}"
);
assert!(
reachable.contains("crate::parent::child"),
"the real compiled child stays reachable: {reachable:?}"
);
}
#[test]
fn a_path_remapped_child_nested_in_an_inline_parent_is_followed() {
let dir =
std::env::temp_dir().join(format!("guibiao-inline-path-remap-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("parent")).expect("mkdirs");
std::fs::write(
src.join("lib.rs"),
"pub mod parent {\n #[path = \"weird.rs\"]\n pub mod child;\n}\n",
)
.expect("write lib.rs");
let target = src.join("parent/weird.rs");
std::fs::write(&target, "use crate::projection::Thing;\n")
.expect("write the real #[path] target");
let orphan = src.join("parent/child.rs");
std::fs::write(&orphan, "use crate::wrong_file_if_observed::Thing;\n")
.expect("write the conventional orphan the remap must not fall back to");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, remapped, remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let governed = governed_files(
&src,
&files,
"crate",
&reachable,
&inline_only,
&remapped,
&remap_shadowed,
None,
);
let _ = std::fs::remove_dir_all(&dir);
assert!(
inline_only.contains("crate::parent"),
"parent is declared inline-only: {inline_only:?}"
);
assert!(
reachable.contains("crate::parent::child"),
"a #[path]-remapped child nested in an inline parent is followed to its target, \
resolved relative to parent's own accumulated directory: {reachable:?}"
);
assert_eq!(
remapped,
vec![(target.clone(), "crate::parent::child".to_string())],
"resolved from src/parent/, not src/: {remapped:?}"
);
assert!(
!governed.iter().any(|(file, _)| file == &orphan),
"the conventional orphan must not be governed in the remap's place: {governed:?}"
);
}
#[test]
fn a_path_remap_to_a_missing_target_is_a_scan_error() {
let dir =
std::env::temp_dir().join(format!("guibiao-path-remap-missing-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(&src).expect("create temp src");
std::fs::write(
src.join("lib.rs"),
"#[path = \"absent.rs\"]\npub mod kernel;\n",
)
.expect("write lib.rs");
let files = rust_files(&src).expect("list files");
let result = reachable_modules(&src, &files, None);
let _ = std::fs::remove_dir_all(&dir);
assert!(
result.is_err(),
"a #[path] target that does not exist is a scan error, not a silent skip: {result:?}"
);
}
#[test]
fn a_path_remap_cycle_is_a_scan_error_not_a_hang() {
let dir =
std::env::temp_dir().join(format!("guibiao-path-remap-cycle-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("a")).expect("mkdirs");
std::fs::write(
src.join("lib.rs"),
"pub mod a {\n #[path = \"../lib.rs\"]\n pub mod b;\n}\n",
)
.expect("write lib.rs");
let files = rust_files(&src).expect("list files");
let result = reachable_modules(&src, &files, None);
let _ = std::fs::remove_dir_all(&dir);
let err = result.expect_err(
"a #[path] chain cycling back to an already-open file is a scan error, not a hang",
);
assert!(
err.contains("cycles back"),
"expected the ancestor-cycle guard's own message, got: {err}"
);
}
#[test]
fn two_declarations_sharing_one_path_remap_target_is_not_a_cycle() {
let dir =
std::env::temp_dir().join(format!("guibiao-path-remap-shared-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(&src).expect("create temp src");
std::fs::write(
src.join("lib.rs"),
"#[path = \"s.rs\"]\npub mod a;\n#[path = \"s.rs\"]\npub mod b;\n",
)
.expect("write lib.rs");
std::fs::write(src.join("s.rs"), "// shared target\n").expect("write s.rs");
let files = rust_files(&src).expect("list files");
let (reachable, _inline_only, remapped, _remap_shadowed) = reachable_modules(
&src, &files, None,
)
.expect("two modules sharing one #[path] target is not a cycle (rustc compiles it)");
let _ = std::fs::remove_dir_all(&dir);
assert!(reachable.contains("crate::a"), "{reachable:?}");
assert!(reachable.contains("crate::b"), "{reachable:?}");
assert_eq!(remapped.len(), 2, "{remapped:?}");
}
#[test]
fn cfg_gated_sibling_path_declarations_are_followed_cfg_blind_both() {
let dir =
std::env::temp_dir().join(format!("guibiao-cfg-dual-path-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(&src).expect("create temp src");
std::fs::write(
src.join("lib.rs"),
"#[cfg(unix)]\n#[path = \"unix_impl.rs\"]\npub mod imp;\n#[cfg(windows)]\n#[path = \"windows_impl.rs\"]\npub mod imp;\n",
)
.expect("write lib.rs");
let unix_target = src.join("unix_impl.rs");
std::fs::write(&unix_target, "use crate::projection::Unix;\n").expect("write unix_impl.rs");
let windows_target = src.join("windows_impl.rs");
std::fs::write(&windows_target, "use crate::projection::Windows;\n")
.expect("write windows_impl.rs");
let files = rust_files(&src).expect("list files");
let (reachable, _inline_only, remapped, _remap_shadowed) =
reachable_modules(&src, &files, None).expect("both cfg-gated targets are followed");
let _ = std::fs::remove_dir_all(&dir);
assert!(reachable.contains("crate::imp"), "{reachable:?}");
let mut targets: Vec<&PathBuf> = remapped
.iter()
.filter(|(_, module)| module == "crate::imp")
.map(|(file, _)| file)
.collect();
targets.sort();
let mut expected = vec![&unix_target, &windows_target];
expected.sort();
assert_eq!(
targets, expected,
"both platform targets are followed under crate::imp, cfg-blind: {remapped:?}"
);
}
#[test]
fn a_nested_path_crossing_into_a_cfg_siblings_own_target_is_not_a_cycle() {
let dir = std::env::temp_dir().join(format!(
"guibiao-cfg-cross-arm-nested-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(&src).expect("create temp src");
std::fs::write(
src.join("lib.rs"),
"#[cfg(feature = \"a\")]\n#[path = \"variant_a.rs\"]\npub mod imp;\n#[cfg(feature = \"b\")]\n#[path = \"variant_b.rs\"]\npub mod imp;\n",
)
.expect("write lib.rs");
let variant_a = src.join("variant_a.rs");
std::fs::write(
&variant_a,
"#[path = \"variant_b.rs\"]\nmod also_b;\nuse crate::projection::A;\n",
)
.expect("write variant_a.rs");
let variant_b = src.join("variant_b.rs");
std::fs::write(&variant_b, "use crate::projection::B;\n").expect("write variant_b.rs");
let files = rust_files(&src).expect("list files");
let (reachable, _inline_only, remapped, _remap_shadowed) =
reachable_modules(&src, &files, None).expect(
"a nested #[path] crossing into a mutually-exclusive cfg sibling's own target must \
not be misreported as a cycle",
);
let _ = std::fs::remove_dir_all(&dir);
assert!(reachable.contains("crate::imp"), "{reachable:?}");
assert!(
reachable.contains("crate::imp::also_b"),
"the nested #[path] inside variant_a.rs is followed and governed: {reachable:?}"
);
let also_b_targets: Vec<&PathBuf> = remapped
.iter()
.filter(|(_, module)| module == "crate::imp::also_b")
.map(|(file, _)| file)
.collect();
assert_eq!(
also_b_targets,
vec![&variant_b],
"crate::imp::also_b resolves to variant_b.rs: {remapped:?}"
);
}
#[test]
fn a_nested_path_inside_an_inline_cfg_siblings_plain_child_is_not_a_cycle() {
let dir = std::env::temp_dir().join(format!(
"guibiao-cfg-inline-plain-child-cross-arm-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("x")).expect("create temp src/x");
std::fs::write(
src.join("lib.rs"),
"#[cfg(feature = \"u\")]\npub mod x {\n pub mod y;\n}\n#[cfg(feature = \"w\")]\n#[path = \"windows_x.rs\"]\npub mod x;\n",
)
.expect("write lib.rs");
std::fs::write(
src.join("x/y.rs"),
"#[path = \"../windows_x.rs\"]\nmod cross;\n",
)
.expect("write x/y.rs");
std::fs::write(src.join("windows_x.rs"), "// the other cfg arm's target\n")
.expect("write windows_x.rs");
let files = rust_files(&src).expect("list files");
let (reachable, _inline_only, remapped, _remap_shadowed) = reachable_modules(
&src, &files, None,
)
.expect(
"a plain child's own nested #[path] crossing into a cfg sibling's target must not be a cycle",
);
let _ = std::fs::remove_dir_all(&dir);
assert!(reachable.contains("crate::x::y"), "{reachable:?}");
assert!(
reachable.contains("crate::x::y::cross"),
"the nested #[path] inside y.rs is followed: {reachable:?}"
);
assert!(
remapped
.iter()
.any(|(_, module)| module == "crate::x::y::cross"),
"{remapped:?}"
);
}
#[test]
fn a_grandchild_of_a_probed_plain_child_is_governed() {
let dir = std::env::temp_dir().join(format!(
"guibiao-probed-child-grandchild-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("other/child")).expect("create temp dirs");
std::fs::write(
src.join("lib.rs"),
"#[path = \"other/weird.rs\"]\npub mod kernel;\n",
)
.expect("write lib.rs");
std::fs::write(src.join("other/weird.rs"), "pub mod child;\n").expect("write weird.rs");
std::fs::write(src.join("other/child.rs"), "pub mod grandchild;\n")
.expect("write other/child.rs");
let grandchild_file = src.join("other/child/grandchild.rs");
std::fs::write(&grandchild_file, "use crate::projection::Thing;\n")
.expect("write grandchild.rs");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, remapped, remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let governed = governed_files(
&src,
&files,
"crate",
&reachable,
&inline_only,
&remapped,
&remap_shadowed,
None,
);
let _ = std::fs::remove_dir_all(&dir);
assert!(
reachable.contains("crate::kernel::child::grandchild"),
"{reachable:?}"
);
assert!(
governed
.iter()
.any(|(file, module)| file == &grandchild_file
&& module == "crate::kernel::child::grandchild"),
"the probed child's own grandchild is governed under its logical path: {governed:?}"
);
}
#[test]
fn a_stray_file_at_a_remapped_modules_naive_structural_path_is_not_phantom_governed() {
let dir = std::env::temp_dir().join(format!(
"guibiao-remap-stray-structural-sibling-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("other")).expect("create temp src/other");
std::fs::create_dir_all(src.join("kernel")).expect("create temp src/kernel");
std::fs::write(
src.join("lib.rs"),
"#[path = \"other/weird.rs\"]\npub mod kernel;\n",
)
.expect("write lib.rs");
std::fs::write(src.join("other/weird.rs"), "pub mod child;\n").expect("write weird.rs");
let real_child = src.join("other/child.rs");
std::fs::write(&real_child, "// the real, rustc-compiled child\n")
.expect("write real child");
std::fs::write(
src.join("kernel/child.rs"),
"this is not even valid rust syntax {{{",
)
.expect("write stray file");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, remapped, remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let governed = governed_files(
&src,
&files,
"crate",
&reachable,
&inline_only,
&remapped,
&remap_shadowed,
None,
);
let _ = std::fs::remove_dir_all(&dir);
assert!(
governed
.iter()
.any(|(file, module)| file == &real_child && module == "crate::kernel::child"),
"the real probed child is governed: {governed:?}"
);
assert_eq!(
governed
.iter()
.filter(|(_, module)| module == "crate::kernel::child")
.count(),
1,
"the stray file at the naive structural location must NOT be phantom-governed alongside the real one: {governed:?}"
);
}
#[test]
fn a_plain_file_sibling_of_a_path_remap_is_still_governed() {
let dir = std::env::temp_dir().join(format!(
"guibiao-cfg-plain-path-sibling-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(&src).expect("create temp src");
std::fs::write(
src.join("lib.rs"),
"#[cfg(unix)]\npub mod x;\n#[cfg(windows)]\n#[path = \"windows_x.rs\"]\npub mod x;\n",
)
.expect("write lib.rs");
let plain = src.join("x.rs");
std::fs::write(&plain, "use crate::projection::Unix;\n").expect("write x.rs");
let remapped_target = src.join("windows_x.rs");
std::fs::write(&remapped_target, "use crate::projection::Windows;\n")
.expect("write windows_x.rs");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, remapped, remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let governed = governed_files(
&src,
&files,
"crate",
&reachable,
&inline_only,
&remapped,
&remap_shadowed,
None,
);
let _ = std::fs::remove_dir_all(&dir);
assert!(reachable.contains("crate::x"), "{reachable:?}");
assert!(
governed.iter().any(|(f, _)| f == &plain),
"the plain-file sibling must still be governed, not suppressed by the #[path] \
sibling: {governed:?}"
);
assert!(
governed.iter().any(|(f, _)| f == &remapped_target),
"the #[path] sibling's real target must also be governed: {governed:?}"
);
assert!(
!remap_shadowed.contains("crate::x"),
"a plain-file sibling means x.rs is real, not an orphan-shadow: {remap_shadowed:?}"
);
}
#[test]
fn an_inline_sibling_of_a_path_remap_is_still_governed() {
let dir = std::env::temp_dir().join(format!(
"guibiao-cfg-inline-path-sibling-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(&src).expect("create temp src");
std::fs::create_dir_all(src.join("x")).expect("mkdir x");
std::fs::write(
src.join("lib.rs"),
"#[cfg(unix)]\npub mod x {\n pub mod y;\n}\n#[cfg(windows)]\n#[path = \"windows_x.rs\"]\npub mod x;\n",
)
.expect("write lib.rs");
std::fs::write(src.join("x/y.rs"), "use crate::projection::Unix;\n").expect("write x/y.rs");
let remapped_target = src.join("windows_x.rs");
std::fs::write(&remapped_target, "use crate::projection::Windows;\n")
.expect("write windows_x.rs");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, remapped, remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let governed = governed_files(
&src,
&files,
"crate",
&reachable,
&inline_only,
&remapped,
&remap_shadowed,
None,
);
let _ = std::fs::remove_dir_all(&dir);
assert!(
reachable.contains("crate::x::y"),
"the inline sibling's own file-backed child must still be reachable: {reachable:?}"
);
assert!(
remapped
.iter()
.any(|(f, m)| f == &remapped_target && m == "crate::x"),
"the #[path] sibling's real target must also be followed: {remapped:?}"
);
assert!(
governed
.iter()
.any(|(f, m)| f == &remapped_target && m == "crate::x"),
"crate::x is governed via its #[path] target regardless of the inline sibling: {governed:?}"
);
}
#[test]
fn an_inline_sibling_of_a_plain_file_is_still_governed() {
let dir = std::env::temp_dir().join(format!(
"guibiao-cfg-plain-inline-sibling-{}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(src.join("x")).expect("mkdirs");
std::fs::write(
src.join("lib.rs"),
"#[cfg(not(feature = \"b\"))]\npub mod x;\n#[cfg(feature = \"b\")]\npub mod x {\n pub mod y;\n}\n",
)
.expect("write lib.rs");
let plain = src.join("x.rs");
std::fs::write(&plain, "use crate::projection::Plain;\n").expect("write x.rs");
let inline_child = src.join("x/y.rs");
std::fs::write(&inline_child, "use crate::projection::InlineChild;\n")
.expect("write x/y.rs");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, _remapped, _remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let _ = std::fs::remove_dir_all(&dir);
assert!(
!inline_only.contains("crate::x"),
"a plain file is declared, so crate::x is not inline-only: {inline_only:?}"
);
assert!(
reachable.contains("crate::x::y"),
"the inline sibling's own file-backed child must still be reachable even though a \
plain-file sibling of crate::x also exists: {reachable:?}"
);
}
#[test]
fn governed_files_does_not_duplicate_a_plain_files_own_path_remap_target() {
let dir =
std::env::temp_dir().join(format!("guibiao-dup-remap-target-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let src = dir.join("src");
std::fs::create_dir_all(&src).expect("create temp src");
std::fs::write(
src.join("lib.rs"),
"#[cfg(not(feature = \"b\"))]\npub mod a;\n#[cfg(feature = \"b\")]\n#[path = \"a.rs\"]\npub mod a;\n",
)
.expect("write lib.rs");
std::fs::write(src.join("a.rs"), "use crate::projection::Thing;\n").expect("write a.rs");
let files = rust_files(&src).expect("list files");
let (reachable, inline_only, remapped, remap_shadowed) =
reachable_modules(&src, &files, None).expect("walk modules");
let governed = governed_files(
&src,
&files,
"crate",
&reachable,
&inline_only,
&remapped,
&remap_shadowed,
None,
);
let _ = std::fs::remove_dir_all(&dir);
let a_entries: Vec<_> = governed
.iter()
.filter(|(_, module)| module == "crate::a")
.collect();
assert_eq!(
a_entries.len(),
1,
"the plain sibling and its own #[path] target are the same file — governed once, \
not twice: {governed:?}"
);
}
}