use super::helpers::*;
use crate::module_scan::EvaluationScans;
use std::collections::{BTreeSet, HashMap};
use std::path::PathBuf;
fn shared_and_independent(constitution: &Constitution, metadata: &Value) -> (Outcome, Outcome) {
(
crate::evaluate_with_scans(constitution, metadata, &EvaluationScans::shared()),
crate::evaluate_with_scans(constitution, metadata, &EvaluationScans::independent()),
)
}
fn constitution_of(boundaries: Vec<ModuleBoundary>) -> Constitution {
let mut constitution = Constitution::new("corpus");
for boundary in boundaries {
constitution = constitution.boundary(boundary);
}
constitution
}
#[test]
fn two_workspaces_built_from_one_label_hold_separate_roots() {
let first = TempWorkspace::new("eq-same-label");
let written = first.write("lib.rs", "pub fn first() {}\n");
let second = TempWorkspace::new("eq-same-label");
assert!(
written.is_file(),
"building a second workspace of the same label removed the first workspace's file"
);
assert_ne!(first.dir(), second.dir());
}
#[test]
pub(super) fn many_boundaries_over_one_root_build_its_scan_once() {
let ws = TempWorkspace::new("root-scan-once");
ws.write(
"lib.rs",
"pub mod kernel;\npub mod projection;\npub mod types;\n",
);
ws.write("kernel.rs", "use crate::projection::P;\npub struct K;\n");
ws.write("projection.rs", "pub struct P;\n");
ws.write("types.rs", "pub struct T;\n");
let metadata = ws.metadata("x");
let constitution = Constitution::new("t")
.boundary(
ModuleBoundary::in_crate("x")
.module("crate::kernel")
.must_not_import("crate::projection")
.because("the kernel does not reach the projection"),
)
.boundary(
ModuleBoundary::in_crate("x")
.module("crate::kernel")
.restrict_imports_to(vec!["crate::types"])
.because("the kernel imports only the types"),
)
.boundary(
ModuleBoundary::in_crate("x")
.module("crate::projection")
.must_not_import("crate::kernel")
.because("the projection does not reach back"),
)
.boundary(
ModuleBoundary::in_crate("x")
.module("crate::kernel")
.must_not_call_inline("std::process")
.because("the kernel spawns no process"),
);
let scans = EvaluationScans::shared();
let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
assert_eq!(
outcome.exit_code(),
1,
"the forbidden import reacts: {outcome:?}"
);
assert_eq!(
scans.roots_built(),
1,
"four boundaries over one root build its scan once, not once per boundary"
);
let ws = TempWorkspace::new("root-scan-per-root");
ws.write("lib.rs", "pub mod kernel;\npub mod types;\n");
ws.write("kernel.rs", "pub struct K;\n");
ws.write("types.rs", "pub struct T;\n");
ws.write("bin/tool.rs", "fn main() {}\n");
let metadata = serde_json::json!({
"packages": [{
"name": "x",
"targets": [
{ "kind": ["lib"], "src_path": ws.src().join("lib.rs").to_string_lossy() },
{ "kind": ["bin"], "src_path": ws.src().join("bin/tool.rs").to_string_lossy() },
],
}],
});
let constitution = Constitution::new("t")
.boundary(
ModuleBoundary::in_crate("x")
.module("crate::kernel")
.must_not_import("crate::types")
.because("the kernel does not reach the types"),
)
.boundary(
ModuleBoundary::in_crate("x")
.module("crate::types")
.must_not_import("crate::kernel")
.because("the types do not reach back"),
);
let scans = EvaluationScans::shared();
let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
assert_eq!(outcome.exit_code(), 0, "{outcome:?}");
assert_eq!(
scans.roots_built(),
2,
"a package of a lib and a bin builds each root once across both boundaries"
);
}
type CorpusEntry = (TempWorkspace, Value, Vec<ModuleBoundary>);
struct Corpus {
name: &'static str,
build: fn() -> CorpusEntry,
}
fn outbound() -> CorpusEntry {
let ws = TempWorkspace::new("eq-outbound");
ws.write(
"lib.rs",
"pub mod kernel;\npub mod projection;\npub mod types;\n",
);
ws.write("kernel.rs", "use crate::projection::P;\npub struct K;\n");
ws.write("projection.rs", "pub struct P;\n");
ws.write("types.rs", "pub struct T;\n");
let metadata = ws.metadata("x");
let boundaries = vec![
ModuleBoundary::in_crate("x")
.module("crate::kernel")
.must_not_import("crate::projection")
.because("the kernel does not reach the projection"),
ModuleBoundary::in_crate("x")
.module("crate::kernel")
.restrict_imports_to(vec!["crate::types"])
.because("the kernel imports only the types"),
];
(ws, metadata, boundaries)
}
fn inbound() -> CorpusEntry {
let ws = TempWorkspace::new("eq-inbound");
ws.write(
"lib.rs",
"pub mod internal;\npub mod api;\npub mod kernel;\n",
);
ws.write("internal.rs", INBOUND_INTERNAL);
ws.write("api.rs", "use crate::internal::foo;\npub fn a() {}\n");
ws.write(
"kernel.rs",
"use crate::internal::foo as f;\npub fn k() {}\n",
);
let metadata = ws.metadata("x");
let boundaries = vec![
ModuleBoundary::in_crate("x")
.module("crate::internal")
.must_not_be_imported_by("crate::api")
.depth(ScanDepth::Shallow)
.because("internal is private to the crate"),
ModuleBoundary::in_crate("x")
.module("crate::internal")
.must_only_be_imported_by(vec!["crate::kernel"])
.because("only the kernel reaches internal"),
];
(ws, metadata, boundaries)
}
const INBOUND_INTERNAL: &str = "pub mod foo { pub const INSIDE: u8 = 0; }\npub fn foo() {}\n\
pub fn host() { mod nested { pub fn foo() {} } nested::foo(); }\n\
m! { fn g() { mod k { pub fn foo() {} } } }\n";
#[test]
pub(super) fn a_governed_modules_value_items_are_read_from_the_units_tables() {
let (_ws, metadata, boundaries) = inbound();
let constitution = constitution_of(boundaries);
crate::module_scan::take_table_builds();
let outcome = crate::evaluate_with_scans(&constitution, &metadata, &EvaluationScans::shared());
let builds = crate::module_scan::take_table_builds();
let importers: BTreeSet<String> = match &outcome {
Outcome::Violations(report) => report
.violations
.iter()
.map(|violation| violation.finding.clone())
.collect(),
other => panic!("the value-namespace reading reacts: {other:?}"),
};
assert!(
importers
.iter()
.any(|finding| finding.contains("crate::api")),
"the shallow rule reacts on `crate::api` only through the governed module's value items: {importers:?}"
);
let mut per_module: HashMap<&str, usize> = HashMap::new();
for ((module, _table), count) in &builds {
*per_module.entry(module.as_str()).or_default() += count;
}
assert_eq!(
per_module,
HashMap::from([
("crate", 1),
("crate::internal", 1),
("crate::api", 1),
("crate::kernel", 1),
]),
"each file's table is built once, as its module, and the inventory builds none: {builds:?}"
);
let package = &metadata["packages"][0];
let lib = PathBuf::from(package["targets"][0]["src_path"].as_str().unwrap());
let root = EvaluationScans::shared()
.root_scan(package, "x", Some(&lib), None)
.unwrap();
let items: BTreeSet<String> = root
.governed_module_value_items("crate::internal")
.unwrap()
.into_iter()
.collect();
assert_eq!(
items,
BTreeSet::from([
"crate::internal::foo".to_string(),
"crate::internal::foo::INSIDE".to_string(),
"crate::internal::host".to_string(),
"crate::internal::{block}::nested::foo".to_string(),
]),
"the inventory holds the values of the governed module and of each inline module it declares, a \
block-declared module's among them, keyed by their true module, and no segment \
naming a table's number, which a macro's group alone would carry"
);
}
fn external_confinement() -> CorpusEntry {
let ws = TempWorkspace::new("eq-external");
ws.write("lib.rs", "pub mod ffi;\npub mod service;\npub mod extra;\n");
ws.write("ffi.rs", "\n");
ws.write("service.rs", "use libc::c_int;\n");
ws.write("extra.rs", "use serde::Deserialize;\n");
let metadata = ws.metadata("x");
let boundaries = vec![
ModuleBoundary::in_crate("x")
.module("crate::ffi")
.confine_external_crate("libc")
.because("the raw libc surface stays behind the ffi module"),
ModuleBoundary::in_crate("x")
.module("crate::service")
.must_not_import("crate::ffi")
.because("service does not reach the ffi module"),
];
(ws, metadata, boundaries)
}
fn inline() -> CorpusEntry {
let ws = TempWorkspace::new("eq-inline");
ws.write("lib.rs", "pub mod core;\npub mod exec;\n");
ws.write(
"core.rs",
"pub fn stamp() { let _ = std::process::id(); }\npub fn tick() { let _ = chrono::Utc::now(); }\n",
);
ws.write("exec.rs", "pub fn run() { std::process::exit(0); }\n");
let metadata = ws.metadata_with_deps("x", &[("chrono", None)]);
let boundaries = vec![
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::process")
.because("core spawns no process"),
ModuleBoundary::in_crate("x")
.module("crate::exec")
.confine_inline_call("std::process")
.because("only exec spawns a process"),
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::process")
.strict_prefix_only()
.because("core does not even name a process"),
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("chrono::Utc")
.strict_external()
.because("core reads no wall clock — time is injected"),
];
(ws, metadata, boundaries)
}
fn several_roots() -> CorpusEntry {
let ws = TempWorkspace::new("eq-roots");
ws.write(
"lib.rs",
"pub mod kernel;\npub mod shared;\npub mod internal;\n",
);
ws.write("kernel.rs", "pub struct K;\n");
ws.write("shared.rs", "use crate::kernel::K;\n");
ws.write("internal.rs", "\n");
ws.write("bin/tool.rs", "mod tooling;\nmod shared;\nfn main() {}\n");
ws.write("bin/tooling.rs", "use libc::c_int;\n");
ws.write("bin/shared.rs", "use crate::tooling;\nuse libc::c_void;\n");
let metadata = serde_json::json!({
"packages": [{
"name": "x",
"targets": [
{ "kind": ["lib"], "src_path": ws.src().join("lib.rs").to_string_lossy() },
{ "kind": ["bin"], "src_path": ws.src().join("bin/tool.rs").to_string_lossy() },
],
}],
});
let boundaries = vec![
ModuleBoundary::in_crate("x")
.module("crate::shared")
.must_not_import("crate::tooling")
.because("shared must not reach the tooling"),
ModuleBoundary::in_crate("x")
.module("crate::kernel")
.must_not_import("crate::tooling")
.because("the kernel must not reach the tooling"),
ModuleBoundary::in_crate("x")
.module("crate::internal")
.confine_external_crate("libc")
.because("the raw libc surface stays behind internal"),
];
(ws, metadata, boundaries)
}
fn refused_unknown_module() -> CorpusEntry {
let ws = TempWorkspace::new("eq-refused-named");
ws.write("lib.rs", "pub mod real;\n");
ws.write("real.rs", "\n");
let metadata = ws.metadata("x");
let boundaries = vec![
ModuleBoundary::in_crate("x")
.module("crate::real")
.must_not_import("crate::io")
.because("real does not reach the io"),
ModuleBoundary::in_crate("x")
.module("crate::ghost")
.must_not_import("crate::real")
.because("a ghost does not reach the real"),
];
(ws, metadata, boundaries)
}
fn refused_inline_target() -> CorpusEntry {
let ws = TempWorkspace::new("eq-refused-inline");
ws.write("lib.rs", "pub mod wrapper;\npub mod real;\n");
ws.write("wrapper.rs", "pub mod inline {}\n");
ws.write("real.rs", "\n");
let metadata = ws.metadata("x");
let boundaries = vec![
ModuleBoundary::in_crate("x")
.module("crate::wrapper::inline")
.must_not_import("crate::real")
.because("an inline module cannot be governed"),
ModuleBoundary::in_crate("x")
.module("crate::real")
.must_not_import("crate::wrapper")
.because("real does not reach the wrapper"),
];
(ws, metadata, boundaries)
}
fn import_ring() -> CorpusEntry {
let ws = TempWorkspace::new("eq-ring");
ws.write("lib.rs", "pub mod t0;\npub mod t1;\npub mod r;\n");
ws.write("t0.rs", "pub fn f() {}\n");
ws.write("t1.rs", "pub fn f() {}\n");
ws.write(
"r.rs",
"#[cfg(unix)]\npub use crate::t0 as x;\n#[cfg(not(unix))]\npub use y as x;\n\
#[cfg(unix)]\npub use crate::t1 as y;\n#[cfg(not(unix))]\npub use x as y;\n\
pub use y as z;\npub mod ra;\npub mod rb;\n",
);
ws.write("r/ra.rs", "pub fn run() { super::x::f(); }\n");
ws.write("r/rb.rs", "pub fn run() { super::z::f(); }\n");
let metadata = ws.metadata("x");
let boundaries = vec![
ModuleBoundary::in_crate("x")
.module("crate::r::ra")
.must_not_call_inline("crate::t1")
.because("ra does not reach the second terminal"),
ModuleBoundary::in_crate("x")
.module("crate::r::rb")
.must_not_call_inline("crate::t0")
.strict_prefix_only()
.because("rb does not even name the first terminal"),
];
(ws, metadata, boundaries)
}
#[test]
pub(super) fn shared_and_independent_scans_yield_one_outcome() {
let corpus = [
Corpus {
name: "outbound",
build: outbound,
},
Corpus {
name: "inbound",
build: inbound,
},
Corpus {
name: "external-confinement",
build: external_confinement,
},
Corpus {
name: "inline",
build: inline,
},
Corpus {
name: "import-ring",
build: import_ring,
},
Corpus {
name: "several-roots",
build: several_roots,
},
Corpus {
name: "refused-unknown-module",
build: refused_unknown_module,
},
Corpus {
name: "refused-inline-target",
build: refused_inline_target,
},
];
let mut saw_violations = false;
let mut saw_refusal = false;
for Corpus { name, build } in corpus {
let (_ws, metadata, boundaries) = build();
for reversed in [false, true] {
let mut ordered = boundaries.clone();
if reversed {
ordered.reverse();
}
let constitution = constitution_of(ordered);
let (shared, independent) = shared_and_independent(&constitution, &metadata);
match &shared {
Outcome::Violations(_) => saw_violations = true,
Outcome::ConstitutionError(_) => saw_refusal = true,
_ => {}
}
assert_eq!(
shared, independent,
"{name} (reversed: {reversed}): a shared scan per root and a scan per boundary \
yield one outcome"
);
}
}
assert!(
saw_violations,
"the corpus judges violations — without one, the equivalence shown is vacuous"
);
assert!(
saw_refusal,
"the corpus is refused — without one, the equivalence shown is vacuous"
);
}
fn read_once(paths: &[PathBuf]) -> HashMap<PathBuf, usize> {
paths.iter().map(|path| (path.clone(), 1)).collect()
}
#[test]
pub(super) fn each_source_path_is_read_once_on_demand() {
let ws = TempWorkspace::new("read-once");
ws.write(
"lib.rs",
"pub mod internal;\npub mod api;\npub mod core;\n#[path = \"../outside.rs\"]\npub mod outside;\n",
);
ws.write(
"internal.rs",
"pub mod foo { pub const INSIDE: u8 = 0; }\npub fn foo() {}\n",
);
ws.write("api.rs", "use crate::internal::foo;\npub fn a() {}\n");
ws.write(
"core.rs",
"use crate::internal::foo as f;\npub fn stamp() { let _ = std::process::id(); }\n",
);
ws.write_at("outside.rs", "pub fn o() { std::process::exit(0); }\n");
let metadata = ws.metadata("x");
let constitution = constitution_of(vec![
ModuleBoundary::in_crate("x")
.module("crate::internal")
.must_not_be_imported_by("crate::api")
.depth(ScanDepth::Shallow)
.because("internal is private to the crate"),
ModuleBoundary::in_crate("x")
.module("crate::internal")
.must_only_be_imported_by(vec!["crate::core"])
.because("only core reaches internal"),
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::process")
.because("core spawns no process"),
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::process")
.strict_prefix_only()
.because("core does not even name a process"),
ModuleBoundary::in_crate("x")
.module("crate::outside")
.must_not_call_inline("std::process")
.because("the outside module spawns no process"),
]);
let scans = EvaluationScans::shared();
let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
assert_eq!(outcome.exit_code(), 1, "the boundaries react: {outcome:?}");
let src = ws.src();
assert_eq!(
scans.source_reads(),
read_once(&[
src.join("lib.rs"),
src.join("internal.rs"),
src.join("api.rs"),
src.join("core.rs"),
src.join("../outside.rs"),
]),
"every source the boundaries reach is read once, by the path it was opened at, and no other is read"
);
}
#[test]
pub(super) fn a_source_two_roots_reach_is_read_once() {
let ws = TempWorkspace::new("read-once-two-roots");
ws.write("lib.rs", "pub mod kernel;\npub mod common;\n");
ws.write("main.rs", "mod kernel;\nmod common;\nfn main() {}\n");
ws.write("kernel.rs", "pub struct K;\n");
ws.write("common.rs", "use crate::kernel::K;\n");
let metadata = serde_json::json!({
"packages": [{
"name": "x",
"targets": [
{ "kind": ["lib"], "src_path": ws.src().join("lib.rs").to_string_lossy() },
{ "kind": ["bin"], "src_path": ws.src().join("main.rs").to_string_lossy() },
],
}],
});
let constitution = constitution_of(vec![
ModuleBoundary::in_crate("x")
.module("crate::common")
.must_not_import("crate::kernel")
.because("common does not reach the kernel"),
]);
let scans = EvaluationScans::shared();
let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
let src = ws.src();
assert_eq!(
scans.source_reads(),
read_once(&[
src.join("lib.rs"),
src.join("main.rs"),
src.join("kernel.rs"),
src.join("common.rs"),
]),
"a file both roots compile is read once across them"
);
let units: BTreeSet<String> = match &outcome {
Outcome::Violations(report) => report
.violations
.iter()
.flat_map(|violation| violation.fact().fields())
.filter(|(field, _)| *field == "unit")
.map(|(_, unit)| unit.to_string())
.collect(),
other => panic!("each root's common module reacts: {other:?}"),
};
assert_eq!(
units,
BTreeSet::from(["lib.rs".to_string(), "main.rs".to_string()]),
"each root judges its own position of the shared file: {outcome:?}"
);
assert_eq!(
outcome,
crate::evaluate_with_scans(&constitution, &metadata, &EvaluationScans::independent()),
"the shared reading judges each root as a reading per boundary does"
);
}
#[test]
pub(super) fn a_source_two_modules_reach_is_read_once() {
let ws = TempWorkspace::new("read-once-two-modules");
ws.write(
"lib.rs",
"#[path = \"twin.rs\"]\npub mod a;\n#[path = \"twin.rs\"]\npub mod b;\n",
);
ws.write("twin.rs", "pub fn t() { std::process::exit(0); }\n");
let metadata = ws.metadata("x");
let constitution = constitution_of(vec![
ModuleBoundary::in_crate("x")
.module("crate::a")
.must_not_call_inline("std::process")
.because("a spawns no process"),
ModuleBoundary::in_crate("x")
.module("crate::b")
.must_not_call_inline("std::process")
.strict_prefix_only()
.because("b does not even name a process"),
]);
let scans = EvaluationScans::shared();
let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
let src = ws.src();
assert_eq!(
scans.source_reads(),
read_once(&[src.join("lib.rs"), src.join("twin.rs")]),
"a file loaded as two modules is read once for both"
);
let findings: BTreeSet<String> = match &outcome {
Outcome::Violations(report) => report
.violations
.iter()
.map(|violation| violation.finding.clone())
.collect(),
other => panic!("each module the file is loaded as reacts: {other:?}"),
};
assert_eq!(
findings,
BTreeSet::from([
"std::process::exit in crate::a".to_string(),
"std::process::exit in crate::b".to_string(),
]),
"each module position of the one file is judged: {outcome:?}"
);
assert_eq!(
outcome,
crate::evaluate_with_scans(&constitution, &metadata, &EvaluationScans::independent()),
"the shared reading judges each module position as a reading per boundary does"
);
}
#[cfg(unix)]
#[test]
pub(super) fn a_source_no_root_reaches_is_never_read() {
let ws = TempWorkspace::new("read-never");
ws.write("lib.rs", "pub mod kernel;\npub mod projection;\n");
ws.write("kernel.rs", "use crate::projection::P;\npub struct K;\n");
ws.write("projection.rs", "pub struct P;\n");
let orphan = ws.write("orphan.rs", "use crate::kernel::K;\n");
let Some(_unreadable) = xingbiao::Unreadable::try_new(&orphan) else {
return;
};
let metadata = ws.metadata("x");
let constitution = constitution_of(vec![
ModuleBoundary::in_crate("x")
.module("crate::kernel")
.must_not_import("crate::projection")
.because("the kernel does not reach the projection"),
]);
let scans = EvaluationScans::shared();
let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
assert_eq!(
outcome.exit_code(),
1,
"the reachable sources decide the exit code: {outcome:?}"
);
let src = ws.src();
assert_eq!(
scans.source_reads(),
read_once(&[
src.join("lib.rs"),
src.join("kernel.rs"),
src.join("projection.rs"),
]),
"the unreachable, unreadable file is never read"
);
}
#[test]
pub(super) fn a_files_uses_are_classified_once_across_rules_and_boundaries() {
let ws = TempWorkspace::new("classify-once");
ws.write(
"lib.rs",
"pub mod internal;\npub mod service;\npub mod ffi;\n",
);
ws.write("internal.rs", "pub mod detail;\npub struct Secret;\n");
ws.write("internal/detail.rs", "use crate::internal::Secret;\n");
ws.write(
"service.rs",
"use crate::internal::Secret;\nuse libc::c_int;\n",
);
ws.write(
"ffi.rs",
"use crate::internal::Secret;\nuse libc::c_void;\n",
);
let metadata = ws.metadata("x");
let constitution = constitution_of(vec![
ModuleBoundary::in_crate("x")
.module("crate::service")
.must_not_import("crate::internal")
.because("service does not import internal"),
ModuleBoundary::in_crate("x")
.module("crate::service")
.restrict_imports_to(["crate::ffi"])
.because("service imports only ffi"),
ModuleBoundary::in_crate("x")
.module("crate::internal")
.must_not_be_imported_by("crate::service")
.because("service does not reach internal"),
ModuleBoundary::in_crate("x")
.module("crate::internal")
.must_only_be_imported_by(["crate::ffi"])
.because("only ffi reaches internal"),
ModuleBoundary::in_crate("x")
.module("crate::internal")
.confine_external_crate("libc")
.because("only internal imports libc"),
ModuleBoundary::in_crate("x")
.module("crate::internal")
.confine_external_crate("serde")
.because("only internal imports serde"),
]);
for reversed in [false, true] {
let constitution = if reversed {
let mut boundaries = constitution.boundaries().to_vec();
boundaries.reverse();
let mut reversed = Constitution::new("reverse");
for boundary in boundaries {
reversed = reversed.boundary(boundary);
}
reversed
} else {
constitution.clone()
};
let scans = EvaluationScans::shared();
let outcome = crate::evaluate_with_scans(&constitution, &metadata, &scans);
assert_eq!(outcome.exit_code(), 1, "the rules react: {outcome:?}");
let expected: HashMap<_, _> = [
("lib.rs", "crate"),
("service.rs", "crate::service"),
("ffi.rs", "crate::ffi"),
]
.into_iter()
.map(|(file, module)| ((ws.src().join(file), module.to_string()), 1))
.collect();
assert_eq!(
scans.classifications(),
expected,
"each pair at least one rule reads is classified once and no other pair is classified (reversed: {reversed})"
);
}
}