diff --git a/.changepacks/changepack_log_collector_round30.json b/.changepacks/changepack_log_collector_round30.json new file mode 100644 index 00000000..7d3ecd83 --- /dev/null +++ b/.changepacks/changepack_log_collector_round30.json @@ -0,0 +1 @@ +{"changes":{"crates/vespera/Cargo.toml":"Patch","crates/vespera_core/Cargo.toml":"Patch","crates/vespera_macro/Cargo.toml":"Patch","crates/vespera_inprocess/Cargo.toml":"Patch","crates/vespera_jni/Cargo.toml":"Patch","libs/vespera-bridge/build.gradle.kts":"Patch","libs/vespera-bridge-gradle-plugin/build.gradle.kts":"Patch"},"note":"Route collector: cfg-disjoint twin mod declarations (#[cfg(unix)] mod m; beside #[cfg(not(unix))] mod m;) mount their routes under any(all(..), all(..)) instead of an always-false AND; an ungated #[path] module loads only its target in every build, so a test-only child of it stays out of the OpenAPI document; #[path] children are resolved as rustc resolves them (beside a non-mod.rs target); ungated mod and #[path] declarations of every declaring file count, not only files with cfg and test text, and a declaration counts only when its declaring file is itself loaded in every build.","date":"2026-11-19T00:00:00.000Z"} diff --git a/crates/vespera_macro/src/collector/module_scope.rs b/crates/vespera_macro/src/collector/module_scope.rs index 0c7fc4ae..e9aa5bab 100644 --- a/crates/vespera_macro/src/collector/module_scope.rs +++ b/crates/vespera_macro/src/collector/module_scope.rs @@ -52,19 +52,46 @@ pub(super) fn module_cfg_predicates(folder_path: &Path, segments: &[String]) -> let mut parent = folder_path.to_path_buf(); let mut predicates = Vec::new(); for segment in segments { - for declarer in [parent.join("mod.rs"), sibling_rs_file(&parent)] { - for module in declared_mods(&declarer) - .iter() - .filter(|module| &module.segment == segment) - { - predicates.extend(module.cfgs.iter().cloned()); - } - } + let declarations: Vec> = [parent.join("mod.rs"), sibling_rs_file(&parent)] + .iter() + .flat_map(|declarer| { + declared_mods(declarer) + .iter() + .filter(|module| &module.segment == segment) + .map(|module| module.cfgs.clone()) + .collect::>() + }) + .collect(); + predicates.extend(declared_cfg(&declarations)); parent.push(segment); } predicates } +/// The predicates under which the `mod` declarations of one module load it +/// (each declaration's `#[cfg]` predicates), in the form the generator ANDs +/// them. An ungated declaration loads the module in every build, so nothing +/// gates it. One declaration gives its predicates. Cfg-disjoint twins are +/// ORed (only one of them is compiled per build), so they give one +/// `any(all(..), ..)`: `#[cfg(unix)] mod m;` beside `#[cfg(not(unix))] mod m;` +/// is `any(all(unix), all(not(unix)))`, not `unix` AND `not(unix)`. +fn declared_cfg(declarations: &[Vec]) -> Vec { + if declarations.iter().any(Vec::is_empty) { + return Vec::new(); + } + match declarations { + [] => Vec::new(), + [single] => single.clone(), + many => { + let twins: Vec = many + .iter() + .map(|cfgs| format!("all({})", cfgs.join(", "))) + .collect(); + vec![format!("any({})", twins.join(", "))] + } + } +} + /// The Rust module path of a route file, as its `mod` declarations name the /// modules: a `#[path]` module is named by its declaration (`mod admin` with /// `#[path = "admin_impl.rs"]` is `routes::admin`, though the file is @@ -383,6 +410,21 @@ mod tests { #[case::path_mod_rs_bare("#[cfg(unix)] #[path = \"mod.rs\"] mod admin;", &["admin"], &["unix"])] #[case::path_without_stem("#[cfg(unix)] #[path = \"\"] mod admin;", &["admin"], &["unix"])] #[case::non_literal_path("#[cfg(unix)] #[path = concat!(\"a\", \".rs\")] mod admin;", &["admin"], &["unix"])] + #[case::undeclared_module("mod other;", &["admin"], &[])] + // Cfg-disjoint twins load the module under either predicate (round-30 M1): + // ANDing them would never load it. + #[case::cfg_twins( + "#[cfg(unix)] pub mod admin;\n#[cfg(not(unix))] pub mod admin;", + &["admin"], + &["any(all(unix), all(not (unix)))"] + )] + #[case::multi_cfg_twins( + "#[cfg(unix)] #[cfg(test)] mod admin; #[cfg(windows)] mod admin;", + &["admin"], + &["any(all(unix, test), all(windows))"] + )] + // An ungated twin loads the module in every build: nothing gates it. + #[case::ungated_twin("#[cfg(unix)] pub mod admin;\npub mod admin;", &["admin"], &[])] fn module_declaration_cfg( #[case] mod_rs: &str, #[case] segments: &[&str], diff --git a/crates/vespera_macro/src/collector/test_scope.rs b/crates/vespera_macro/src/collector/test_scope.rs index d99c9abf..589886b8 100644 --- a/crates/vespera_macro/src/collector/test_scope.rs +++ b/crates/vespera_macro/src/collector/test_scope.rs @@ -28,6 +28,8 @@ use syn::{Item, punctuated::Punctuated}; use super::module_scope::sibling_rs_file; use crate::{metadata::CollectedMetadata, schema_macro::file_cache}; +mod path_tree; + /// Whether the `#[cfg(..)]` predicate `predicate` (token text) can only hold /// in a `cfg(test)` build. pub fn is_test_only_predicate(predicate: &str) -> bool { @@ -125,12 +127,6 @@ fn attrs_test_harness(attrs: &[syn::Attribute]) -> bool { }) } -/// Whether `content` could hold a test-only `#[cfg(..)]` — a cheap text -/// filter that spares the parse of (almost) every file. -fn may_gate_tests(content: &str) -> bool { - content.contains("cfg") && content.contains("test") -} - /// Test-only classification for one crate, memoizing each declaring file's /// test-gated `mod` names. pub struct TestScope { @@ -145,6 +141,12 @@ pub struct TestScope { /// The files the `#[path]` modules of `src/` name, found by one scan of /// the crate (`None` until a file needs it). path_targets: Option, + /// The module tree of each `#[path]` target, by how the walk may reach + /// into it (see [`path_tree`]). + path_trees: HashMap<(PathBuf, path_tree::Reach), std::rc::Rc>>, + /// Declaring files whose own test-only classification is in progress + /// (see `loads_in_every_build`). + resolving: HashSet, } /// The files named by `#[path]` modules of a crate, by whether every build @@ -152,7 +154,8 @@ pub struct TestScope { #[derive(Default)] struct PathTargets { gated: Vec, - open: Vec, + /// Each ungated target with the file declaring it. + open: Vec<(PathBuf, PathBuf)>, } impl TestScope { @@ -163,6 +166,8 @@ impl TestScope { canonical_src_dir: src_dir.and_then(file_cache::canonicalize_cached), gated_mods: HashMap::new(), path_targets: None, + path_trees: HashMap::new(), + resolving: HashSet::new(), } } @@ -227,12 +232,29 @@ impl TestScope { /// Whether one of `declarers` declares ungated one of the `gated` chains /// of the same name (the module at the gated depth, not a deeper one). fn ungated_twin_loads(&mut self, declarers: &[PathBuf], gated: &[String]) -> bool { - let mut loads = false; for declarer in declarers { let mods = self.gated_mods_of(declarer); - loads |= mods.open_chains.iter().any(|open| gated.contains(open)); + if mods.open_chains.iter().any(|open| gated.contains(open)) + && self.loads_in_every_build(declarer) + { + return true; + } } - loads + false + } + + /// Whether the `mod` declarations of `declarer` load their files in every + /// build: the declarer itself is not test-only. A declaration in a + /// test-only file (`#[cfg(test)] mod routes;` whose `routes.rs` declares + /// `mod helpers;`) is test-only with it. A declarer whose own + /// classification is in progress (a `#[path]` cycle) counts as loaded. + fn loads_in_every_build(&mut self, declarer: &Path) -> bool { + if !self.resolving.insert(declarer.to_path_buf()) { + return true; + } + let test_only = self.file_test_only(declarer); + self.resolving.remove(declarer); + !test_only } /// Whether a test-gated `#[path = ".."]` module names `file` and no @@ -242,30 +264,56 @@ impl TestScope { /// by the directory of a non-`mod.rs` module's own file, whose child /// modules sit beside it). fn file_path_gated(&mut self, file: &Path, src_dir: &Path, segments: &[String]) -> bool { - let gated = self.path_loads(file, |targets| &targets.gated); + let targets = self.path_targets(); + let all: Vec = targets + .gated + .iter() + .cloned() + .chain(targets.open.iter().map(|(_, target)| target.clone())) + .collect(); + let gated = self.tree_holds(file, &all, path_tree::Reach::Any); gated && !self.open_path_loads(file) && !self.open_chain_loads(src_dir, segments) } - /// Whether an ungated `#[path]` module names `file` (or a module file - /// under it), so every build loads it. + /// Whether an ungated `#[path]` module of a file that is loaded in every + /// build names `file`, or a file its module tree loads through ungated + /// `mod`s only, so every build loads it. fn open_path_loads(&mut self, file: &Path) -> bool { - self.path_loads(file, |targets| &targets.open) + let open = self.path_targets().open.clone(); + open.iter().any(|(declarer, target)| { + self.tree_holds( + file, + std::slice::from_ref(target), + path_tree::Reach::OpenOnly, + ) && self.loads_in_every_build(declarer) + }) } - /// Whether one of the `#[path]` targets `select` picks names `file`. - /// The file and the targets are compared in one spelling (canonical when - /// the filesystem has it): `file` may come from the canonical fallback, - /// and a target is written under the lexical `src/`, which can name the - /// same file through a symlinked alias of the crate. - fn path_loads(&mut self, file: &Path, select: fn(&PathTargets) -> &Vec) -> bool { + /// Whether the module tree of one of `targets` (walked as `reach` allows) + /// holds `file`. The file and the trees are compared in one spelling + /// (canonical when the filesystem has it): `file` may come from the + /// canonical fallback, and a target is written under the lexical `src/`, + /// which can name the same file through a symlinked alias of the crate. + fn tree_holds(&mut self, file: &Path, targets: &[PathBuf], reach: path_tree::Reach) -> bool { same_spelling_key(file).is_some_and(|file| { - select(self.path_targets()).iter().any(|target| { - same_spelling_key(target) - .is_some_and(|target| file == target || file.starts_with(child_dir(&target))) - }) + targets + .iter() + .any(|target| self.path_tree(target, reach).contains(&file)) }) } + /// The module tree of the `#[path]` target `target` (memoized per reach). + fn path_tree( + &mut self, + target: &Path, + reach: path_tree::Reach, + ) -> std::rc::Rc> { + self.path_trees + .entry((target.to_path_buf(), reach)) + .or_insert_with(|| std::rc::Rc::new(path_tree::tree_of(target, reach))) + .clone() + } + /// Whether an ungated `mod` declaration on the module chain of `segments` /// loads the file (the chain's own name, not a `#[path]`). fn open_chain_loads(&mut self, src_dir: &Path, segments: &[String]) -> bool { @@ -273,13 +321,15 @@ impl TestScope { for (depth, segment) in segments.iter().enumerate() { let declarers = declarers_at(src_dir, &parent, depth); let rest = &segments[depth..]; - if declarers.iter().any(|declarer| { - self.gated_mods_of(declarer) + for declarer in &declarers { + let open = self + .gated_mods_of(declarer) .open_chains .iter() - .any(|open| chain_is(rest, open)) - }) { - return true; + .any(|open| chain_is(rest, open)); + if open && self.loads_in_every_build(declarer) { + return true; + } } parent.push(segment); } @@ -290,16 +340,20 @@ impl TestScope { /// the crate (memoized per scope). fn path_targets(&mut self) -> &PathTargets { if self.path_targets.is_none() { - let files: Vec = self + // Every `#[path]` of the crate's module tree, resolved by the one + // rustc-rule resolver (`path_tree`), not by a per-file guess. + let decls = self .src_dir .as_deref() - .map(|dir| file_cache::list_rs_files(dir).to_vec()) + .map(path_tree::path_declarations) .unwrap_or_default(); let mut targets = PathTargets::default(); - for file in &files { - let gated = self.gated_mods_of(file); - targets.gated.extend(gated.path_targets.iter().cloned()); - targets.open.extend(gated.open_path_targets.iter().cloned()); + for decl in decls { + if decl.gated { + targets.gated.push(decl.target); + } else { + targets.open.push((decl.declarer, decl.target)); + } } self.path_targets = Some(targets); } @@ -311,29 +365,15 @@ impl TestScope { if let Some(gated) = self.gated_mods.get(declarer) { return gated.clone(); } - let dir = declarer.parent().map(Path::to_path_buf).unwrap_or_default(); - let is_crate_root = matches!( - declarer.file_name().and_then(|name| name.to_str()), - Some("lib.rs" | "main.rs") - ) && self.src_dir.as_deref() == Some(dir.as_path()); - // rustc resolves a `#[path]` inside an inline module relative to the - // inline module's directory: for a non-mod-rs declarer (`routes.rs`) - // that directory is named after the file (`routes//`). - let inline_dir = if mod_rs(declarer) { - dir.clone() - } else { - declarer - .file_stem() - .map_or_else(|| dir.clone(), |stem| dir.join(stem)) - }; let gated = file_cache::derived(declarer, |content| { let mut gated = GatedMods::default(); - // A crate root is loaded by every build, so its ungated `mod`s are - // always recorded; other files only when they may gate a test. - if (may_gate_tests(content) || is_crate_root) + // Every declarer's `mod`s load their files in some build (ungated + // ones in every build), whatever cfg text the file holds, so each + // file that declares any `mod` is read. + if content.contains("mod") && let Ok(ast) = syn::parse_file(content) { - gated_mod_paths(&ast.items, "", &dir, &inline_dir, false, &mut gated); + gated_mod_paths(&ast.items, "", false, &mut gated); } gated }) @@ -344,18 +384,15 @@ impl TestScope { } } -/// A declarer's test-gated `mod`s: the `::`-joined chain paths (relative to -/// the declarer: `b` for `#[cfg(test)] mod b;`, `a::b` inside an inline -/// `mod a { .. }`) of those loaded by their own name, and the files of those -/// given a `#[path]`. +/// A declarer's `mod`s loaded by their own name: the `::`-joined chain paths +/// (relative to the declarer: `b` for `#[cfg(test)] mod b;`, `a::b` inside an +/// inline `mod a { .. }`), split by whether a test-only `cfg` gates them. A +/// `#[path]` module is not here: `path_tree` resolves its file. #[derive(Clone, Default)] struct GatedMods { chains: HashSet, - path_targets: Vec, - /// The ungated `mod`s loaded by their own name (`::`-joined as `chains`) - /// and the files of the ungated ones given a `#[path]`. + /// The ungated `mod`s loaded by their own name (`::`-joined as `chains`). open_chains: HashSet, - open_path_targets: Vec, } /// The `#[path = ".."]` value of `attrs`. @@ -379,25 +416,12 @@ fn string_literal(expr: &syn::Expr) -> Option { Some(value.value()) } -/// Collect the test-gated `mod`s among `items` (prefixed by `prefix`; `dir` -/// is the directory their out-of-line files are loaded from), recursing into -/// every inline module. A gated inline module gates everything it nests: its -/// own name goes in as a chain, and the `#[path]` modules nested in it are -/// gated too (they name files only test builds load). A gated `#[path]` -/// module names its file directly, relative to `dir` (rustc resolves it from -/// the declaring file's directory). `inline_dir` is where the inline modules -/// of `items` nest: `dir` itself for a mod-rs declarer, `dir/` for -/// any other, so a `#[path]` inside `mod v2 { .. }` of `routes.rs` resolves -/// under `routes/v2/`. `within_gated` says `items` already sit in a gated -/// inline module. -fn gated_mod_paths( - items: &[Item], - prefix: &str, - dir: &Path, - inline_dir: &Path, - within_gated: bool, - out: &mut GatedMods, -) { +/// Collect the `mod`s loaded by their own name among `items` (prefixed by +/// `prefix`), recursing into every inline module. A gated inline module gates +/// everything it nests: its own name goes in as a chain. `within_gated` says +/// `items` already sit in a gated inline module. A `#[path]` module is skipped: +/// `path_tree` resolves its file with the directory rules. +fn gated_mod_paths(items: &[Item], prefix: &str, within_gated: bool, out: &mut GatedMods) { for item in items { let Item::Mod(module) = item else { continue }; let name = syn::ext::IdentExt::unraw(&module.ident).to_string(); @@ -405,53 +429,22 @@ fn gated_mod_paths( let gated = within_gated || attrs_test_only(&module.attrs); match &module.content { Some((_, content)) => { - // Everything nested inside an inline module lives under it. - let nested = inline_dir.join(&name); if gated { out.chains.insert(path.clone()); } - gated_mod_paths(content, &format!("{path}::"), &nested, &nested, gated, out); + gated_mod_paths(content, &format!("{path}::"), gated, out); + } + None if path_attr(&module.attrs).is_some() => {} + None if gated => { + out.chains.insert(path); } - None if gated => match path_attr(&module.attrs) { - Some(target) => out.path_targets.extend(lexical(&dir.join(target))), - None => { - out.chains.insert(path); - } - }, None => { - // An ungated out-of-line module: every build loads its file. - match path_attr(&module.attrs) { - Some(target) => out.open_path_targets.extend(lexical(&dir.join(target))), - None => { - out.open_chains.insert(path); - } - } + out.open_chains.insert(path); } } } } -/// Whether `declarer` is a mod-rs file (`lib.rs`, `main.rs`, `mod.rs`): its -/// inline modules nest under its own directory, any other file's under a -/// directory named after the file. -fn mod_rs(declarer: &Path) -> bool { - matches!( - declarer.file_stem().and_then(|stem| stem.to_str()), - Some("lib" | "main" | "mod") - ) -} - -/// The directory whose files are the child modules of a `#[path]` target: -/// a `mod.rs` (or crate root) owns its directory, any other file owns the -/// directory named after it (`helpers.rs` -> `helpers/`). -fn child_dir(target: &Path) -> PathBuf { - if mod_rs(target) { - target.parent().unwrap_or(target).to_path_buf() - } else { - target.with_extension("") - } -} - /// The files that may declare the module at `depth` of a chain: the crate /// root at depth 0, else the `mod.rs` / sibling file of its parent directory. fn declarers_at(src_dir: &Path, parent: &Path, depth: usize) -> Vec { diff --git a/crates/vespera_macro/src/collector/test_scope/path_tree.rs b/crates/vespera_macro/src/collector/test_scope/path_tree.rs new file mode 100644 index 00000000..110bf272 --- /dev/null +++ b/crates/vespera_macro/src/collector/test_scope/path_tree.rs @@ -0,0 +1,218 @@ +//! The files a `#[path]` module loads, found by walking the module tree from +//! its target file. +//! +//! rustc's directory rules, checked against rustc (`cargo check` of a +//! `#[path = "beside/support.rs"] mod s;` crate whose `support.rs` declares +//! `mod child;`, which resolves to `beside/child.rs`, not +//! `beside/support/child.rs`): +//! +//! - A file loaded through a `#[path]` attribute owns the directory it sits +//! in for its own `mod`s, whatever its name (`beside/support.rs` -> +//! `beside/`). +//! - A by-name `mod x;` loads `/x.rs` or `/x/mod.rs`, where `` +//! is the module's directory: a mod-rs file's directory, or the directory +//! named after a non-mod-rs file (`routes.rs` -> `routes/`). +//! - A `#[path]` on a module outside inline blocks is relative to the +//! directory of the file declaring it; inside an inline `mod a { .. }` it is +//! relative to the module's directory (`/a/`). +//! +//! The tree is walked from the target, so it covers each child module of a +//! path-loaded file, however deep. Ungated edges only, for the modules every +//! build loads ([`Reach::OpenOnly`]). + +use std::collections::HashSet; +use std::path::{Path, PathBuf}; + +use syn::Item; + +use super::{attrs_test_only, lexical, path_attr, same_spelling_key}; +use crate::schema_macro::file_cache; + +/// Which edges of a `#[path]` target's module tree a walk follows. +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub(super) enum Reach { + /// Only the `mod` declarations no `cfg(test)` build can leave out. + OpenOnly, + /// Every `mod` declaration the tree holds, gated or not. + Any, +} + +/// One `mod` declaration of a file. +#[derive(Clone)] +struct ModDecl { + /// The inline `mod name { .. }` blocks it sits in, outermost first. + inline: Vec, + /// Its own name (unraw). + name: String, + /// The value of its `#[path]`, when it is a string literal. + path: Option, + /// Gated by a test-only `cfg`, on it or on an enclosing inline module. + gated: bool, +} + +/// A file's `mod` declarations (kept while the file is unchanged). +#[derive(Default)] +struct ModDecls(Vec); + +/// The `mod` declarations of `file` (none when it is unreadable or does not +/// parse, or holds no `mod` text at all). +fn mod_decls(file: &Path) -> std::rc::Rc { + file_cache::derived(file, |content| { + let mut decls = Vec::new(); + if content.contains("mod") + && let Ok(ast) = syn::parse_file(content) + { + collect(&ast.items, &mut Vec::new(), false, &mut decls); + } + ModDecls(decls) + }) + .unwrap_or_default() +} + +/// Collect the `mod` declarations among `items`, recursing into inline +/// modules (`inline` names the blocks around `items`; `within_gated` says +/// they sit in a test-only inline module). +fn collect(items: &[Item], inline: &mut Vec, within_gated: bool, out: &mut Vec) { + for item in items { + let Item::Mod(module) = item else { continue }; + let name = syn::ext::IdentExt::unraw(&module.ident).to_string(); + let gated = within_gated || attrs_test_only(&module.attrs); + match &module.content { + Some((_, nested)) => { + inline.push(name); + collect(nested, inline, gated, out); + inline.pop(); + } + None => out.push(ModDecl { + inline: inline.clone(), + name, + path: path_attr(&module.attrs), + gated, + }), + } + } +} + +/// A file of a module tree and the directory its child modules are loaded +/// from. +struct Node { + file: PathBuf, + children_dir: PathBuf, +} + +/// The [`same_spelling_key`]s of `target` and of every file its module tree +/// loads (through the edges `reach` allows). The target is taken as loaded by +/// a `#[path]` attribute, so its children sit beside it. Files a `mod` names +/// but which do not exist simply hold no declarations. +pub(super) fn tree_of(target: &Path, reach: Reach) -> HashSet { + let start = lexical(target).unwrap_or_else(|| target.to_path_buf()); + let start_dir = start.parent().map(Path::to_path_buf).unwrap_or_default(); + let mut found = HashSet::new(); + let mut pending = vec![Node { + file: start, + children_dir: start_dir, + }]; + while let Some(Node { file, children_dir }) = pending.pop() { + let key = same_spelling_key(&file).unwrap_or_else(|| file.clone()); + if found.insert(key) { + pending.extend(children(&file, &children_dir, reach)); + } + } + found +} + +/// The files the `mod` declarations of `file` load (`children_dir` is the +/// directory its child modules are loaded from), through the edges `reach` +/// allows. +fn children(file: &Path, children_dir: &Path, reach: Reach) -> Vec { + let mut nodes = Vec::new(); + for decl in mod_decls(file) + .0 + .iter() + .filter(|decl| reach == Reach::Any || !decl.gated) + { + if decl.path.is_some() { + if let Some(child) = path_target(file, children_dir, decl) { + nodes.push(Node { + children_dir: child.parent().map(Path::to_path_buf).unwrap_or_default(), + file: child, + }); + } + } else { + // A by-name child: `/.rs` or `//mod.rs` (the + // one that exists is the module; the other holds no declarations). + let child_dir = inline_dir(children_dir, decl).join(&decl.name); + nodes.push(Node { + file: child_dir.with_extension("rs"), + children_dir: child_dir.clone(), + }); + nodes.push(Node { + file: child_dir.join("mod.rs"), + children_dir: child_dir, + }); + } + } + nodes +} + +/// The directory a `mod` declaration of a file with child directory +/// `children_dir` is resolved in: its inline blocks nest under it. +fn inline_dir(children_dir: &Path, decl: &ModDecl) -> PathBuf { + decl.inline + .iter() + .fold(children_dir.to_path_buf(), |dir, block| dir.join(block)) +} + +/// The file a `#[path]` declaration names, the one rustc resolves: outside +/// inline blocks relative to the declaring file's directory, inside them to +/// the inline module's directory. A declaration with no `#[path]` names none. +fn path_target(file: &Path, children_dir: &Path, decl: &ModDecl) -> Option { + let path_value = decl.path.as_deref()?; + let base = if decl.inline.is_empty() { + file.parent().map(Path::to_path_buf).unwrap_or_default() + } else { + inline_dir(children_dir, decl) + }; + lexical(&base.join(path_value)) +} + +/// A `#[path]` declaration of the crate: the file declaring it, the file it +/// names, and whether a test-only `cfg` gates it. +pub(super) struct PathDecl { + pub(super) declarer: PathBuf, + pub(super) target: PathBuf, + pub(super) gated: bool, +} + +/// Every `#[path]` declaration in the module tree of the crate whose sources +/// are under `src_dir`. The tree is walked from `lib.rs` / `main.rs` with +/// rustc's directory rules and every `cfg` ignored (a gated declaration is +/// listed with `gated`). A file no declaration reaches is not compiled, so its +/// declarations are not listed. +pub(super) fn path_declarations(src_dir: &Path) -> Vec { + let mut decls = Vec::new(); + let mut found = HashSet::new(); + let mut pending: Vec = ["lib.rs", "main.rs"] + .iter() + .map(|root| Node { + file: src_dir.join(root), + children_dir: src_dir.to_path_buf(), + }) + .collect(); + while let Some(Node { file, children_dir }) = pending.pop() { + let key = same_spelling_key(&file).unwrap_or_else(|| file.clone()); + if found.insert(key) { + for decl in &mod_decls(&file).0 { + if let Some(target) = path_target(&file, &children_dir, decl) { + decls.push(PathDecl { + declarer: file.clone(), + target, + gated: decl.gated, + }); + } + } + pending.extend(children(&file, &children_dir, Reach::Any)); + } + } + decls +} diff --git a/crates/vespera_macro/src/collector/test_scope/tests.rs b/crates/vespera_macro/src/collector/test_scope/tests.rs index dcc836ad..085fe95f 100644 --- a/crates/vespera_macro/src/collector/test_scope/tests.rs +++ b/crates/vespera_macro/src/collector/test_scope/tests.rs @@ -321,6 +321,175 @@ fn file_also_loaded_by_an_ungated_path_is_production() { assert!(!scope.file_test_only(&src.join("shared.rs"))); } +/// Only the target of an ungated `#[path]` module is loaded in every build; +/// its own `#[cfg(test)]` child stays test-only (round-30 L1, a regression of +/// round 29, which classified every file under the target's directory as +/// loaded). +#[test] +fn test_gated_child_of_an_ungated_path_module_is_test_only() { + let krate = crate_with(&[ + ("lib.rs", "#[path = \"support.rs\"]\nmod support;\n"), + ( + "support.rs", + "#[cfg(test)]\nmod fixtures;\npub struct Kept {}\n", + ), + ("support/fixtures.rs", "pub struct Fixture {}"), + ]); + let src = krate.path().join("src"); + let mut scope = TestScope::new(Some(&src)); + assert!(scope.file_test_only(&src.join("support/fixtures.rs"))); + assert!(!scope.file_test_only(&src.join("support.rs"))); +} + +/// The same for a non-mod-rs target: the children of `beside/support.rs` sit +/// beside it (`beside/child.rs`, as rustc resolves them), so a test-gated +/// child is test-only, and a sibling of the target that is no child is not. +#[test] +fn test_gated_child_of_an_ungated_path_module_beside_its_file_is_test_only() { + let krate = crate_with(&[ + ("lib.rs", "#[path = \"beside/support.rs\"]\nmod support;\n"), + ("beside/support.rs", "#[cfg(test)]\nmod child;\n"), + ("beside/child.rs", "pub struct Fixture {}"), + ("beside/other.rs", "pub struct Kept {}"), + ]); + let src = krate.path().join("src"); + let mut scope = TestScope::new(Some(&src)); + assert!(scope.file_test_only(&src.join("beside/child.rs"))); + assert!(!scope.file_test_only(&src.join("beside/other.rs"))); +} + +/// A test-gated `#[path]` module whose target is not `mod.rs` gates the +/// children declared in that target, which sit beside it (`beside/child.rs`), +/// not in a directory named after it. +#[test] +fn path_attributed_test_module_gates_children_beside_a_non_mod_rs_file() { + let krate = crate_with(&[ + ( + "lib.rs", + "#[cfg(test)]\n#[path = \"beside/support.rs\"]\nmod support;\n", + ), + ("beside/support.rs", "mod child;"), + ("beside/child.rs", "pub struct Fixture {}"), + ("beside/support/child.rs", "pub struct Kept {}"), + ]); + let src = krate.path().join("src"); + let mut scope = TestScope::new(Some(&src)); + assert!(scope.file_test_only(&src.join("beside/child.rs"))); + assert!(!scope.file_test_only(&src.join("beside/support/child.rs"))); +} + +/// An ungated `#[path]` declared in a non-root file without any `cfg`/`test` +/// text still loads its file in every build (round-30 L2): `api/mod.rs` +/// loads `shared.rs`, which `lib.rs` gates by name. +#[test] +fn ungated_path_declaration_in_a_non_root_file_keeps_the_file_production() { + let krate = crate_with(&[ + ("lib.rs", "#[cfg(test)]\nmod shared;\npub mod api;\n"), + ( + "api/mod.rs", + "#[path = \"../shared.rs\"]\npub mod shared_prod;\n", + ), + ("shared.rs", "pub struct Kept {}"), + ]); + let src = krate.path().join("src"); + let mut scope = TestScope::new(Some(&src)); + assert!(!scope.file_test_only(&src.join("shared.rs"))); +} + +/// The inline block of an ungated `#[path]` target nests its children +/// beside the target too (`beside/inner/deep.rs`, as rustc resolves a path +/// inside an inline module of a path-loaded file); a test-gated one is +/// test-only. +#[test] +fn test_gated_path_inside_an_inline_block_of_an_ungated_path_target() { + let krate = crate_with(&[ + ("lib.rs", "#[path = \"beside/support.rs\"]\nmod support;\n"), + ( + "beside/support.rs", + "mod inner {\n #[cfg(test)]\n #[path = \"deep.rs\"]\n mod probe;\n}\n", + ), + ("beside/inner/deep.rs", "pub struct Fixture {}"), + ]); + let src = krate.path().join("src"); + let mut scope = TestScope::new(Some(&src)); + assert!(scope.file_test_only(&src.join("beside/inner/deep.rs"))); +} + +/// An ungated `#[path]` declared in a file only test builds load is loaded +/// only by them (round-30 L2 records it, so the declarer's own gate must +/// count): `lib.rs` gates `fixtures`, and `fixtures.rs` names `shared.rs`. +#[test] +fn ungated_path_declared_in_a_test_only_file_stays_test_only() { + let krate = crate_with(&[ + ("lib.rs", "#[cfg(test)]\nmod fixtures;\n"), + ( + "fixtures.rs", + "#[path = \"shared.rs\"]\npub mod shared_prod;\n", + ), + ("shared.rs", "pub struct Fixture {}"), + ]); + let src = krate.path().join("src"); + let mut scope = TestScope::new(Some(&src)); + assert!(scope.file_test_only(&src.join("shared.rs"))); +} + +/// An ungated `mod` of a production file loads a file the crate otherwise +/// gates by `#[path]` (`routes/mod.rs` declares `pub mod probe;` ungated, next +/// to `#[cfg(test)] #[path = "routes/probe.rs"] mod probe_mod;` in `lib.rs`): +/// every build loads `probe.rs`, so it is production. +#[test] +fn ungated_mod_of_a_production_file_loads_a_path_gated_file() { + let krate = crate_with(&[ + ( + "lib.rs", + "#[cfg(test)]\n#[path = \"routes/probe.rs\"]\nmod probe_mod;\npub mod routes;\n", + ), + ("routes/mod.rs", "pub mod probe;\n"), + ("routes/probe.rs", "pub struct Kept {}"), + ]); + let src = krate.path().join("src"); + let mut scope = TestScope::new(Some(&src)); + assert!(!scope.file_test_only(&src.join("routes/probe.rs"))); +} + +/// Two `#[path]`s naming each other (`a.rs` declares `b.rs`, which declares +/// `a.rs` again) terminate. A cycle has no build's module tree, so it counts +/// as loaded: the files stay production, the conservative answer for a +/// document. +#[test] +fn path_cycle_terminates_and_stays_production() { + let krate = crate_with(&[ + ("lib.rs", "#[cfg(test)]\n#[path = \"a.rs\"]\nmod a;\n"), + ("a.rs", "#[path = \"b.rs\"]\npub mod b;\n"), + ("b.rs", "#[path = \"a.rs\"]\npub mod a_again;\n"), + ]); + let src = krate.path().join("src"); + let mut scope = TestScope::new(Some(&src)); + assert!(!scope.file_test_only(&src.join("b.rs"))); +} + +/// An inline `#[path]` inside a path-loaded non-mod-rs file resolves beside +/// that file's directory, as rustc does: `beside/support.rs` declares +/// `mod inner { #[cfg(test)] #[path = "keep.rs"] mod probe; }`, so the file is +/// `beside/inner/keep.rs`. The stem rule (`beside/support/inner/keep.rs`, the +/// directory named after the file) classified the other file instead. +#[test] +fn inline_path_of_a_path_loaded_file_resolves_beside_it_not_under_its_stem() { + let krate = crate_with(&[ + ("lib.rs", "#[path = \"beside/support.rs\"]\nmod support;\n"), + ( + "beside/support.rs", + "mod inner {\n #[cfg(test)]\n #[path = \"keep.rs\"]\n mod probe;\n}\n", + ), + ("beside/inner/keep.rs", "pub struct Fixture {}"), + ("beside/support/inner/keep.rs", "pub struct Kept {}"), + ]); + let src = krate.path().join("src"); + let mut scope = TestScope::new(Some(&src)); + assert!(scope.file_test_only(&src.join("beside/inner/keep.rs"))); + assert!(!scope.file_test_only(&src.join("beside/support/inner/keep.rs"))); +} + fn schema(name: &str, identity: Option) -> StructMetadata { let mut schema = StructMetadata::new(name.to_string(), format!("struct {name} {{}}")); schema.source_identity = identity; diff --git a/crates/vespera_macro/src/collector/tests.rs b/crates/vespera_macro/src/collector/tests.rs index 6950ed68..4effc996 100644 --- a/crates/vespera_macro/src/collector/tests.rs +++ b/crates/vespera_macro/src/collector/tests.rs @@ -699,6 +699,36 @@ fn cfg_gated_route_modules_and_handlers_are_mounted_conditionally() { insta::assert_snapshot!("cfg_gated_routes", gated.join("\n")); } +/// Cfg-disjoint twin `mod` declarations load the module under either +/// predicate, so the route is mounted under their `any` (round-30 M1). Without +/// a `#[route]` storage entry the file takes the slow path, which used to AND +/// the two predicates into `all(unix, not(unix))`: never mounted. +#[test] +fn cfg_twin_module_declarations_mount_the_route_under_either_predicate() { + let temp_dir = TempDir::new().expect("Failed to create temp dir"); + create_temp_file( + &temp_dir, + "mod.rs", + "#[cfg(unix)]\npub mod users;\n#[cfg(not(unix))]\npub mod users;\n", + ); + create_temp_file( + &temp_dir, + "users.rs", + "#[route(get)] pub async fn list() {}\n", + ); + crate::schema_macro::file_cache::bump_epoch(); + + let (metadata, _) = collect_metadata(temp_dir.path(), "routes", &[]).unwrap(); + + assert!(metadata.routes.is_empty()); + let cfgs: Vec = metadata + .cfg_routes + .iter() + .map(|route| route.cfg.join(" & ")) + .collect(); + assert_eq!(cfgs, ["any(all(unix), all(not (unix)))"]); +} + #[test] fn inline_module_route_is_a_compile_error() { let temp_dir = TempDir::new().expect("Failed to create temp dir");