use super::helpers::*;
pub(super) fn confine_core_clock() -> ModuleBoundary {
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.because("core reads no wall clock — time is injected, not read")
}
#[test]
pub(super) fn inline_a_verb_outside_the_declared_set_is_a_bound() {
let narrowed = || {
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.ending_with(["now"])
.because("core reads no wall clock — time is injected, not read")
};
let (result, violations) = run_module_check(
"inline-verb-outside",
&[
("lib.rs", "pub mod clock;\npub mod core;\n"),
(
"clock.rs",
"pub fn now() -> u64 { 0 }\npub fn current() -> u64 { 0 }\n",
),
(
"core.rs",
"fn stamp() { let _ = crate::clock::current(); }\n",
),
],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("crate::clock")
.ending_with(["now"])
.because("the clock is injected"),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a verb outside the declared set is a bound the adopter owns: {violations:?}"
);
let (result, violations) = run_module_check(
"inline-verb-declared",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn stamp() { let _ = std::time::SystemTime::now(); }\n",
),
],
narrowed(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"the declared verb must react: {violations:?}"
);
}
#[test]
pub(super) fn inline_foreign_reexport_of_the_confined_path_is_a_bound() {
let (result, violations) = run_module_check_with_deps(
"inline-foreign-reexport",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn stamp() { let _ = shim::SystemTime::now(); }\n",
),
],
&[("shim", None)],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a foreign re-export of the confined path is a stated bound, not a reaction: {violations:?}"
);
let (result, violations) = run_module_check_with_deps(
"inline-foreign-reexport-control",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn stamp() { let _ = std::time::SystemTime::now(); }\n",
),
],
&[("shim", None)],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "control must react: {violations:?}");
}
#[test]
pub(super) fn inline_path_remapped_child_is_observed() {
for (label, declaration) in [
("direct", "#[path = \"elsewhere.rs\"]\npub mod inner;\n"),
(
"cfg_attr",
"#[cfg_attr(unix, path = \"elsewhere.rs\")]\npub mod inner;\n",
),
] {
let (result, violations) = run_module_check(
&format!("inline-remap-{label}"),
&[
("lib.rs", "pub mod core;\n"),
("core.rs", declaration),
(
"elsewhere.rs",
"fn stamp() { let _ = std::time::Instant::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{label}: {result:?}");
assert_eq!(violations.len(), 1, "{label}: {violations:?}");
assert_eq!(violations[0].target(), "std::time", "{label}");
assert!(
violations[0].finding.contains("crate::core::inner"),
"{label}: the finding must name the remapped module, not the declaring file: {:?}",
violations[0].finding
);
}
}
#[test]
pub(super) fn inline_default_reacts_on_an_associated_fn_call() {
let (result, violations) = run_module_check(
"inline-call",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn stamp() { let _ = std::time::SystemTime::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "{violations:?}");
assert_eq!(violations[0].target(), "std::time");
assert!(
violations[0].finding.contains("std::time::SystemTime::now"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_default_passes_a_type_annotation() {
let (result, violations) = run_module_check(
"inline-annot",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn handle(now: std::time::Instant) { let _ = now; }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a type annotation is not a call: {violations:?}"
);
}
#[test]
pub(super) fn inline_default_passes_a_constant() {
let (result, violations) = run_module_check(
"inline-const",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn f() { let _ = std::time::SystemTime::UNIX_EPOCH; }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a constant read is not a call: {violations:?}"
);
}
#[test]
pub(super) fn inline_resolves_a_rename() {
let (result, violations) = run_module_check(
"inline-rename",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"use std::time::SystemTime as SysT;\nfn f() { let _ = SysT::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a renamed alias resolves: {violations:?}"
);
assert!(
violations[0].finding.contains("std::time::SystemTime::now"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_resolves_a_self_prefixed_group_alias() {
let (result, violations) = run_module_check(
"inline-self-prefixed-group",
&[
("lib.rs", "pub mod clock;\npub mod core;\n"),
(
"clock.rs",
"pub mod self_utc {\n pub fn now() -> u8 { 0 }\n}\npub struct Duration;\n",
),
(
"core.rs",
"#[allow(unused_imports)]\nuse crate::clock::{self_utc as clk, Duration};\nfn f() { let _ = clk::now(); }\n",
),
],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("crate::clock")
.because("the clock is injected"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a self-prefixed group alias resolves and reacts: {violations:?}"
);
assert!(
violations[0]
.finding
.contains("crate::clock::self_utc::now"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_resolves_a_bare_path() {
let (result, violations) = run_module_check(
"inline-bare",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"use std::time;\nfn f() { let _ = time::Instant::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "a bare path resolves: {violations:?}");
assert!(
violations[0].finding.contains("std::time::Instant::now"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_resolves_a_type_alias() {
let (result, violations) = run_module_check(
"inline-typealias",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"type Clock = std::time::SystemTime;\nfn f() { let _ = Clock::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "a type alias resolves: {violations:?}");
}
#[test]
pub(super) fn inline_resolves_a_multi_hop_type_alias() {
let (result, violations) = run_module_check(
"inline-multihop",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"type A = std::time::SystemTime;\ntype B = A;\nfn f() { let _ = B::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a multi-hop type alias chases to a fixpoint: {violations:?}"
);
}
#[test]
pub(super) fn inline_resolves_a_type_alias_past_a_defaulted_generic_param() {
let (result, violations) = run_module_check(
"inline-defaulted-generic-alias",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"pub struct LocalTz;\ntype Clock<Tz = LocalTz> = std::marker::PhantomData<Tz>;\nfn f() { let _: Clock = Clock::default(); }\n",
),
],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::marker")
.because("no markers are made inline"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"the alias resolves past the defaulted generic param to its real target: {violations:?}"
);
}
#[test]
pub(super) fn inline_resolves_a_cross_module_local_reexport() {
let (result, violations) = run_module_check(
"inline-reexport",
&[
("lib.rs", "pub mod core;\npub mod support;\n"),
("support.rs", "pub use std::time::SystemTime;\n"),
(
"core.rs",
"use crate::support::SystemTime;\nfn f() { let _ = SystemTime::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a cross-module local re-export resolves: {violations:?}"
);
}
#[test]
pub(super) fn inline_does_not_match_an_unresolved_same_named_local() {
let (result, violations) = run_module_check(
"inline-local",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"struct Instant;\nimpl Instant { fn now() {} }\nfn f() { Instant::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a same-named local is not matched by leaf: {violations:?}"
);
}
#[test]
pub(super) fn inline_glob_of_the_prefix_reacts() {
let (result, violations) = run_module_check(
"inline-glob",
&[
("lib.rs", "pub mod core;\n"),
("core.rs", "use std::time::*;\n"),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a glob of the prefix reacts fail-closed: {violations:?}"
);
assert!(violations[0].finding.contains("glob"), "{violations:?}");
}
#[test]
pub(super) fn inline_glob_above_the_prefix_reacts() {
let (result, violations) = run_module_check(
"inline-glob-above",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"use std::*;\nfn f() { let _ = time::Instant::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.iter().any(|v| v.finding.contains("glob")),
"an ancestor glob reacts: {violations:?}"
);
}
#[test]
pub(super) fn inline_glob_of_a_local_reexporting_module_reacts() {
let (result, violations) = run_module_check(
"inline-glob-local",
&[
("lib.rs", "pub mod core;\npub mod support;\n"),
("support.rs", "pub use std::time::SystemTime;\n"),
("core.rs", "use crate::support::*;\n"),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a glob of a local re-exporting module reacts: {violations:?}"
);
}
#[test]
pub(super) fn inline_glob_of_a_module_that_itself_globs_the_prefix_reacts() {
let (result, violations) = run_module_check(
"inline-glob-recursive",
&[
("lib.rs", "pub mod core;\npub mod support;\n"),
("support.rs", "pub use std::time::*;\n"),
("core.rs", "use crate::support::*;\n"),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"recursive glob hazard reacts: {violations:?}"
);
}
#[test]
pub(super) fn inline_narrowing_drops_a_benign_constructor_and_keeps_the_read() {
let (result, violations) = run_module_check(
"inline-narrow",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn f() { let _ = std::time::Instant::now(); let _ = std::time::Duration::from_secs(5); }\n",
),
],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.ending_with(["now"])
.because("core reads no wall clock"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"only the now-read reacts under narrowing: {violations:?}"
);
assert!(
violations[0].finding.contains("Instant::now"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_narrowing_does_not_suppress_a_glob() {
let (result, violations) = run_module_check(
"inline-narrow-glob",
&[
("lib.rs", "pub mod core;\n"),
("core.rs", "use std::time::*;\n"),
],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.ending_with(["now"])
.because("core reads no wall clock"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a glob still reacts under narrowing: {violations:?}"
);
}
#[test]
pub(super) fn inline_strict_flags_a_type_annotation() {
let (result, violations) = run_module_check(
"inline-strict",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn handle(now: std::time::Instant) { let _ = now; }\n",
),
],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.strict_prefix_only()
.because("core may not name std::time at all"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"strict flags a mention: {violations:?}"
);
}
#[test]
pub(super) fn inline_value_capture_is_a_bound_under_the_default() {
let (result, violations) = run_module_check(
"inline-valuecap",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn f() { let g = std::time::SystemTime::now; let _ = g; }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"value-position capture is a stated bound under the default: {violations:?}"
);
}
#[test]
pub(super) fn inline_scans_a_macro_body() {
let (result, violations) = run_module_check(
"inline-macro",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"macro_rules! some_macro { ($($t:tt)*) => { $($t)* }; }\nfn f() { some_macro! { let _ = std::time::Instant::now(); } }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a read inside a macro body is scanned, not skipped: {violations:?}"
);
}
#[test]
pub(super) fn inline_empty_prefix_is_a_constitution_error() {
let (result, _violations) = run_module_check(
"inline-empty",
&[("lib.rs", "pub mod core;\n"), ("core.rs", "// clean\n")],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("")
.because("bad"),
);
assert_eq!(
result.unwrap_err(),
inline_empty_prefix_error("x", "must_not_call_inline")
);
}
#[test]
pub(super) fn a_misdeclared_inline_confinement_is_refused_before_the_walk() {
let files = &[
("lib.rs", "pub mod core;\npub mod clock;\nmod ghost;\n"),
("core.rs", "// clean\n"),
("clock.rs", "pub fn now() {}\n"),
];
let cases: [(ModuleBoundary, String); 5] = [
(
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("")
.because("bad"),
inline_empty_prefix_error("x", "must_not_call_inline"),
),
(
ModuleBoundary::in_crate("x")
.module("crate")
.confine_inline_call("crate::clock")
.because("bad"),
crate::errors::confine_inline_call_on_crate_error("x"),
),
(
ModuleBoundary::in_crate("x")
.module("crate::clock")
.confine_inline_call("crate::clock")
.depth(crate::ScanDepth::Shallow)
.because("bad"),
crate::errors::confine_inline_call_shallow_error("x"),
),
(
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("crate::clock")
.ending_with(["now"])
.strict_prefix_only()
.because("bad"),
inline_narrow_and_strict_error("x", "must_not_call_inline"),
),
(
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("crate::clock")
.ending_with(Vec::<String>::new())
.because("bad"),
crate::errors::inline_empty_verbs_error("x", "must_not_call_inline"),
),
];
for (index, (boundary, expected)) in cases.into_iter().enumerate() {
let (result, _) = run_module_check(&format!("inline-misdeclared-{index}"), files, boundary);
assert_eq!(result.unwrap_err(), expected, "case {index}");
}
}
#[test]
pub(super) fn inline_narrow_and_strict_is_a_constitution_error() {
let (result, _violations) = run_module_check(
"inline-combo",
&[("lib.rs", "pub mod core;\n"), ("core.rs", "// clean\n")],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.ending_with(["now"])
.strict_prefix_only()
.because("contradiction"),
);
assert_eq!(
result.unwrap_err(),
inline_narrow_and_strict_error("x", "must_not_call_inline")
);
}
#[test]
pub(super) fn inline_valid_zero_match_is_clean() {
let (result, violations) = run_module_check(
"inline-clean",
&[
("lib.rs", "pub mod core;\n"),
("core.rs", "fn f() { let _ = std::cmp::max(1, 2); }\n"),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a subtree with no std::time call is clean: {violations:?}"
);
}
pub(super) fn confine_chrono_strict(
name: &str,
files: &[(&str, &str)],
) -> (Result<(), String>, Vec<Violation>) {
run_module_check_with_deps(
name,
files,
&[("chrono", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("chrono::Utc")
.strict_external()
.because("core reads no wall clock — time is injected"),
)
}
#[test]
pub(super) fn inline_strict_external_reacts_on_a_fully_qualified_external_call() {
let (result, violations) = confine_chrono_strict(
"inline-strict-ext-fq",
&[
("lib.rs", "pub mod core;\n"),
("core.rs", "fn stamp() { let _ = chrono::Utc::now(); }\n"),
],
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "{violations:?}");
assert_eq!(violations[0].target(), "chrono::Utc");
assert!(
violations[0].finding.contains("chrono::Utc::now"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_absent_fully_qualified_call_is_a_bound() {
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-default",
&[
("lib.rs", "pub mod core;\n"),
("core.rs", "fn stamp() { let _ = chrono::Utc::now(); }\n"),
],
&[("chrono", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("chrono::Utc")
.because("core reads no wall clock"),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a fully-qualified external call is a stated bound under the default: {violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_deep_local_module_stays_clean() {
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-deepmod",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"pub mod time;\nfn f() { let _ = time::format(); }\n",
),
("core/time.rs", "pub fn format() {}\n"),
],
&[("time", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("time")
.strict_external()
.because("core reads no wall clock"),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a deep local module named like a dep stays local: {violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_local_fn_definition_stays_clean() {
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-localfn",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn rand() -> u32 { 4 }\nfn f() { let _ = rand(); }\n",
),
],
&[("rand", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("rand")
.strict_external()
.because("core is deterministic"),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a local fn shadowing a dep name stays local: {violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_local_alias_stays_clean() {
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-alias",
&[
("lib.rs", "pub mod core;\npub mod clock;\n"),
("clock.rs", "pub fn read() {}\n"),
(
"core.rs",
"use crate::clock as time;\nfn f() { let _ = time::read(); }\n",
),
],
&[("time", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("time")
.strict_external()
.because("core reads no wall clock"),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a local alias shadowing a dep name resolves through its binding: {violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_glob_reacts_and_default_glob_does_not() {
let files = &[
("lib.rs", "pub mod core;\n"),
("core.rs", "use chrono::*;\n"),
];
let (result, violations) = confine_chrono_strict("inline-strict-ext-glob", files);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "external glob reacts: {violations:?}");
assert!(violations[0].finding.contains("glob"), "{violations:?}");
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-glob-default",
files,
&[("chrono", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("chrono::Utc")
.because("core reads no wall clock"),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"the same glob under the default names nothing and does not react: {violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_composes_with_narrowing() {
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-narrow",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn f() { let _ = chrono::Utc::now(); let _ = chrono::Utc::today(); }\n",
),
],
&[("chrono", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("chrono::Utc")
.strict_external()
.ending_with(["now"])
.because("core reads no wall clock"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"only the now-read reacts under narrowing: {violations:?}"
);
assert!(
violations[0].finding.contains("chrono::Utc::now"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_adds_nothing_to_paths_that_already_react() {
let files: &[(&str, &str)] = &[
("lib.rs", "pub mod core;\npub mod support;\n"),
("support.rs", "pub use chrono::Utc;\n"),
(
"core.rs",
"use chrono::Utc;\nuse crate::support::Utc as SupUtc;\nfn f() { let _ = Utc::now(); let _ = SupUtc::now(); }\n",
),
];
let (result, plain) = run_module_check_with_deps(
"inline-strict-ext-already-default",
files,
&[("chrono", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("chrono::Utc")
.because("core reads no wall clock"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
plain.len(),
1,
"the used import + chased re-export already react under the default: {plain:?}"
);
let (result, flagged) = run_module_check_with_deps(
"inline-strict-ext-already-flag",
files,
&[("chrono", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("chrono::Utc")
.strict_external()
.because("core reads no wall clock"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
flagged.len(),
plain.len(),
"the flag adds nothing to paths that already react: {flagged:?}"
);
}
#[test]
pub(super) fn inline_strict_external_preserves_identity_no_baseline_churn() {
let files: &[(&str, &str)] = &[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn f() { let _ = std::time::SystemTime::now(); }\n",
),
];
let (r1, plain) = run_module_check(
"inline-identity-default",
files,
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.because("core reads no wall clock"),
);
let (r2, flagged) = run_module_check_with_deps(
"inline-identity-flag",
files,
&[],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.strict_external()
.because("core reads no wall clock"),
);
assert!(r1.is_ok() && r2.is_ok(), "{r1:?} {r2:?}");
assert_eq!(plain.len(), 1, "{plain:?}");
assert_eq!(flagged.len(), 1, "{flagged:?}");
assert_eq!(plain[0].target(), flagged[0].target(), "target parity");
assert_eq!(plain[0].rule, flagged[0].rule, "rule (label) parity");
assert_eq!(plain[0].finding, flagged[0].finding, "finding parity");
assert_eq!(
plain[0].rule, "inline symbol path confined to module",
"the presentation label is unchanged by the flag"
);
}
#[test]
pub(super) fn inline_strict_external_runs_the_exit_2_checks() {
let (contradiction, _) = run_module_check_with_deps(
"inline-strict-ext-contradiction",
&[("lib.rs", "pub mod core;\n"), ("core.rs", "// clean\n")],
&[("std", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.ending_with(["now"])
.strict_prefix_only()
.strict_external()
.because("contradiction"),
);
assert_eq!(
contradiction.unwrap_err(),
inline_narrow_and_strict_error("x", "must_not_call_inline")
);
let (empty, _) = run_module_check_with_deps(
"inline-strict-ext-empty",
&[("lib.rs", "pub mod core;\n"), ("core.rs", "// clean\n")],
&[],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("")
.strict_external()
.because("bad"),
);
assert_eq!(
empty.unwrap_err(),
inline_empty_prefix_error("x", "must_not_call_inline")
);
}
#[test]
pub(super) fn inline_strict_external_cross_module_local_item_does_not_mask() {
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-xmod",
&[
("lib.rs", "pub mod core;\npub mod helpers;\n"),
("helpers.rs", "pub fn rand() -> u32 { 4 }\n"),
("core.rs", "fn f() { let _ = rand::random(); }\n"),
],
&[("rand", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("rand")
.strict_external()
.because("core is deterministic"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a same-named item of ANOTHER module must not mask a real external call: {violations:?}"
);
assert_eq!(violations[0].target(), "rand");
assert!(
violations[0].finding.contains("rand::random"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_block_local_item_does_not_mask() {
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-blocklocal",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn f() {\n const log: u32 = 3;\n let _ = log::logger();\n}\n",
),
],
&[("log", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("log")
.strict_external()
.because("core does not log"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a block-local item (depth ≥ 1) must not mask a same-module external call: {violations:?}"
);
assert_eq!(violations[0].target(), "log");
assert!(
violations[0].finding.contains("log::logger"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_reacts_on_a_leading_colon_path() {
let (result, violations) = run_module_check(
"inline-leading-colon",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn f() { let _ = ::std::time::SystemTime::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a leading-:: call reacts: {violations:?}"
);
assert!(
violations[0].finding.contains("std::time::SystemTime::now"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_reacts_on_a_nested_grouped_glob() {
let (result, violations) = run_module_check(
"inline-nested-glob",
&[
("lib.rs", "pub mod core;\n"),
("core.rs", "use std::{cmp::max, time::*};\n"),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.iter().any(|v| v.finding.contains("glob")),
"a nested grouped glob of the prefix reacts: {violations:?}"
);
}
#[test]
pub(super) fn inline_reacts_on_a_two_hop_use_realias() {
let (result, violations) = run_module_check(
"inline-two-hop-use",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"use std::time::SystemTime;\nuse self::SystemTime as Clock;\nfn f() { let _ = Clock::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a two-hop use re-alias resolves to a fixpoint: {violations:?}"
);
}
#[test]
pub(super) fn inline_glob_nested_past_the_depth_cap_is_a_scan_error_not_a_silent_drop() {
let depth = 200;
let source = format!(
"use std::{{{}time::*{}}};",
"a::{".repeat(depth),
"}".repeat(depth)
);
let (result, _violations) = run_module_check(
"inline-glob-depth-cap",
&[("lib.rs", "pub mod core;\n"), ("core.rs", &source)],
confine_core_clock(),
);
let err = result.expect_err(
"a grouped glob nested past the depth cap must be a scan error, not a silent drop",
);
assert!(
err.contains("brace levels"),
"the error must name the depth bound it could not judge past: {err}"
);
}
#[test]
pub(super) fn inline_alias_chain_nested_past_the_depth_cap_is_a_scan_error_not_a_silent_drop() {
let depth = 200;
let source = format!(
"use std::{{{}time::SystemTime as Clock{}}};\nfn f() {{ let _ = Clock::now(); }}\n",
"a::{".repeat(depth),
"}".repeat(depth)
);
let (result, _violations) = run_module_check(
"inline-alias-depth-cap",
&[("lib.rs", "pub mod core;\n"), ("core.rs", &source)],
confine_core_clock(),
);
let err = result
.expect_err("an alias nested past the depth cap must be a scan error, not a silent drop");
assert!(
err.contains("brace levels"),
"the error must name the depth bound it could not judge past: {err}"
);
}
#[test]
pub(super) fn inline_grouped_glob_nested_moderately_is_still_observed() {
let depth = 40;
let source = format!(
"use std::{}time::*{};",
"{".repeat(depth),
"}".repeat(depth)
);
let (result, violations) = run_module_check(
"inline-glob-under-cap",
&[("lib.rs", "pub mod core;\n"), ("core.rs", &source)],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.iter().any(|v| v.finding.contains("glob")),
"a moderately nested grouped glob of the prefix still reacts: {violations:?}"
);
}
#[test]
pub(super) fn inline_reacts_through_a_mid_path_turbofish() {
let (result, violations) = run_module_check(
"inline-turbofish",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"type Clock<T> = std::vec::Vec<T>;\nfn f() { let _ = Clock::<u8>::new(); }\n",
),
],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::vec")
.because("no vectors are made inline"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a mid-path turbofish call reacts: {violations:?}"
);
}
#[test]
pub(super) fn inline_reacts_through_interior_whitespace_and_field_colon() {
let (result, violations) = run_module_check(
"inline-ws",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn f() { let _ = std :: time :: Instant :: now(); }\nstruct E { at: std::time::SystemTime }\nfn g() -> E { E { at:std::time::SystemTime::now() } }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
2,
"interior-whitespace and field-colon calls both react: {violations:?}"
);
}
#[test]
pub(super) fn inline_ufcs_is_a_documented_bound_under_the_default() {
let (result, violations) = run_module_check(
"inline-ufcs",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"trait Now { fn now(); }\nimpl Now for std::time::SystemTime { fn now() {} }\nfn f() { <std::time::SystemTime as Now>::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"UFCS is a stated bound under the default (type in <…>): {violations:?}"
);
}
#[test]
pub(super) fn inline_receiver_method_read_is_a_bound() {
let (result, violations) = run_module_check(
"inline-receiver",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn f(inst: std::time::Instant) { let _ = inst.elapsed(); }\n",
),
],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.ending_with(["now", "elapsed"])
.because("core reads no wall clock"),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a receiver-method read is a stated bound (type not in path): {violations:?}"
);
}
#[test]
pub(super) fn inline_grouped_self_glob_reacts() {
let (result, violations) = run_module_check(
"inline-selfglob",
&[
("lib.rs", "pub mod core;\n"),
("core.rs", "use std::time::{self, Duration, *};\n"),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.iter().any(|v| v.finding.contains("glob")),
"a grouped `{{self, *}}` glob reacts: {violations:?}"
);
}
#[test]
pub(super) fn inline_two_distinct_calls_stay_distinct() {
let (result, violations) = run_module_check(
"inline-distinct",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn f() { let _ = std::time::Instant::now(); let _ = std::time::SystemTime::now(); }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
2,
"two distinct canonical calls stay distinct findings: {violations:?}"
);
}
#[test]
pub(super) fn inline_prefix_is_carried_in_the_violation_target() {
let files: &[(&str, &str)] = &[
("lib.rs", "pub mod core;\n"),
("core.rs", "fn f() { let _ = std::time::Instant::now(); }\n"),
];
let (r1, v1) = run_module_check(
"inline-target-time",
files,
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.because("no clock"),
);
let (r2, v2) = run_module_check(
"inline-target-std",
files,
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std")
.because("no std calls"),
);
assert!(r1.is_ok() && r2.is_ok(), "{r1:?} {r2:?}");
assert_eq!(v1[0].target(), "std::time");
assert_eq!(v2[0].target(), "std");
assert_ne!(
v1[0].target(),
v2[0].target(),
"distinct prefixes → distinct identity"
);
}
#[test]
pub(super) fn inline_warn_severity_is_advisory() {
let (result, violations) = run_module_check(
"inline-warn",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn f() { let _ = std::time::SystemTime::now(); }\n",
),
],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.warn()
.because("advisory"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "{violations:?}");
assert_eq!(violations[0].severity, Severity::Warn);
}
#[test]
pub(super) fn inline_empty_verbs_is_a_constitution_error() {
let (result, _v) = run_module_check(
"inline-emptyverbs",
&[("lib.rs", "pub mod core;\n"), ("core.rs", "// clean\n")],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.ending_with(Vec::<String>::new())
.because("bad"),
);
assert_eq!(
result.unwrap_err(),
inline_empty_verbs_error("x", "must_not_call_inline")
);
}
#[test]
pub(super) fn inline_scanner_does_not_panic_or_hang_on_odd_input() {
for body in [
"use } {;\n",
"use std::{time::*;\n",
"type A = A::B;\nfn f() { let _ = A::now(); }\n",
"use ::;\nfn f() { ::::(); }\n",
"fn f() { <>::(); std :: :: now (); }\n",
] {
let (result, _v) = run_module_check(
"inline-odd",
&[("lib.rs", "pub mod core;\n"), ("core.rs", body)],
confine_core_clock(),
);
assert!(
match &result {
Ok(_) => true,
Err(refusal) => refusal.contains("cannot judge"),
},
"odd input must complete, or be refused as unjudgeable: {body:?} -> {result:?}"
);
}
}
#[test]
pub(super) fn inline_in_macro_body_alias_is_a_bound() {
let (result, violations) = run_module_check(
"inline-macro-alias",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"macro_rules! some_macro { ($($t:tt)*) => { $($t)* }; }\nfn f() { some_macro! { use std::time::SystemTime as X; let _ = X::now(); } }\n",
),
],
confine_core_clock(),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"an alias defined inside a macro body is a stated bound: {violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_inline_submodule_call_is_not_masked() {
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-submod-call",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn rand() -> u32 { 4 }\nmod tests { fn t() { let _ = rand::random(); } }\n",
),
],
&[("rand", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("rand")
.strict_external()
.because("core is deterministic"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a file-top item must not mask an external call inside an inline submodule: {violations:?}"
);
assert_eq!(violations[0].target(), "rand");
assert!(
violations[0].finding.contains("rand::random"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_submodule_local_item_stays_clean() {
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-submod-local",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"mod tests { fn rand() -> u32 { 4 } fn t() { let _ = rand(); } }\n",
),
],
&[("rand", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("rand")
.strict_external()
.because("core is deterministic"),
);
assert!(result.is_ok(), "{result:?}");
assert!(
violations.is_empty(),
"a submodule-local item named like a dep must claim its own submodule's call: {violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_deeply_nested_submodule_reacts() {
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-nested",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn rand() -> u32 { 4 }\nmod a { mod b { fn t() { let _ = rand::random(); } } }\n",
),
],
&[("rand", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("rand")
.strict_external()
.because("core is deterministic"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a file-top item must not mask a call in a deeply nested submodule: {violations:?}"
);
assert_eq!(violations[0].target(), "rand");
assert!(
violations[0].finding.contains("rand::random"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_cfg_gated_submodule_reacts() {
let (result, violations) = run_module_check_with_deps(
"inline-strict-ext-cfg-gated",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"fn rand() -> u32 { 4 }\n#[cfg(test)]\nmod tests { fn t() { let _ = rand::random(); } }\n",
),
],
&[("rand", None)],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("rand")
.strict_external()
.because("core is deterministic"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(
violations.len(),
1,
"a cfg-gated inline submodule must not perturb brace tracking: {violations:?}"
);
assert_eq!(violations[0].target(), "rand");
assert!(
violations[0].finding.contains("rand::random"),
"{violations:?}"
);
}
#[test]
pub(super) fn inline_strict_external_default_path_module_attribution_unshifted() {
let (result, violations) = run_module_check(
"inline-default-attr",
&[
("lib.rs", "pub mod core;\n"),
(
"core.rs",
"mod tests { fn t() { let _ = std::time::SystemTime::now(); } }\n",
),
],
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.because("core reads no wall clock"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "{violations:?}");
assert!(
violations[0].finding.ends_with("in crate::core"),
"default attribution must stay on the FILE module, not the inline submodule: {violations:?}"
);
}
#[test]
pub(super) fn scan_depth_shallow_vs_subtree_evaluates_submodule_matching() {
let files = &[
(
"lib.rs",
"pub mod forbidden_on_core {}\npub mod forbidden_on_sub {}\npub mod core;\n",
),
("core.rs", "pub mod sub;\nuse crate::forbidden_on_core;\n"),
("core/sub.rs", "use crate::forbidden_on_sub;\n"),
];
let shallow_boundary = ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_import("crate::forbidden_on_sub")
.depth(xuanji::ScanDepth::Shallow)
.because("core seam does not import forbidden_on_sub");
let (res1, shallow_violations) =
run_module_check("scan-depth-shallow", files, shallow_boundary);
assert!(res1.is_ok(), "{res1:?}");
assert_eq!(
shallow_violations.len(),
0,
"Shallow depth ignores submodule files"
);
let subtree_boundary = ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_import("crate::forbidden_on_sub")
.depth(xuanji::ScanDepth::Subtree)
.because("core subtree does not import forbidden_on_sub");
let (res2, subtree_violations) =
run_module_check("scan-depth-subtree", files, subtree_boundary);
assert!(res2.is_ok(), "{res2:?}");
assert_eq!(
subtree_violations.len(),
1,
"Subtree depth evaluates submodule files"
);
assert_eq!(
subtree_violations[0]
.rule_key()
.fields()
.collect::<Vec<_>>(),
vec![("module", "crate::forbidden_on_sub")]
);
}
#[test]
pub(super) fn module_boundary_including_submodules_is_a_compatible_subtree_modifier() {
let default = ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_import("crate::adapter")
.because("r");
let explicit = ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_import("crate::adapter")
.depth(xuanji::ScanDepth::Subtree)
.because("r");
let ergonomic = ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_import("crate::adapter")
.depth(xuanji::ScanDepth::Shallow)
.including_submodules()
.because("r");
assert_eq!(default.scan_depth(), xuanji::ScanDepth::Subtree);
assert_eq!(explicit.scan_depth(), xuanji::ScanDepth::Subtree);
assert_eq!(ergonomic.scan_depth(), xuanji::ScanDepth::Subtree);
assert_eq!(default.rule_key(), ergonomic.rule_key());
}
#[test]
pub(super) fn shallow_restrict_imports_to_ignores_descendant_imports() {
let files = &[
("lib.rs", "pub mod adapter {}\npub mod core;\n"),
("core.rs", "pub mod detail;\n"),
("core/detail.rs", "use crate::adapter;\n"),
];
let shallow = ModuleBoundary::in_crate("x")
.module("crate::core")
.restrict_imports_to(["crate::core"])
.depth(xuanji::ScanDepth::Shallow)
.because("the core seam depends inward");
let (shallow_result, shallow_violations) =
run_module_check("shallow-restrict-imports", files, shallow);
assert!(shallow_result.is_ok(), "{shallow_result:?}");
assert!(shallow_violations.is_empty(), "{shallow_violations:?}");
let subtree = ModuleBoundary::in_crate("x")
.module("crate::core")
.restrict_imports_to(["crate::core"])
.because("the core subtree depends inward");
let (subtree_result, subtree_violations) =
run_module_check("subtree-restrict-imports", files, subtree);
assert!(subtree_result.is_ok(), "{subtree_result:?}");
assert_eq!(subtree_violations.len(), 1, "{subtree_violations:?}");
}
#[test]
pub(super) fn shallow_inbound_rules_protect_only_the_exact_module() {
let files = &[
(
"lib.rs",
"pub mod facade {}\npub mod protected;\npub mod client;\n",
),
("protected.rs", "pub mod detail;\n"),
("protected/detail.rs", "pub struct Item;\n"),
("client.rs", "use crate::protected::detail::Item;\n"),
];
let shallow_forbid = ModuleBoundary::in_crate("x")
.module("crate::protected")
.must_not_be_imported_by("crate::client")
.depth(xuanji::ScanDepth::Shallow)
.because("only the protected seam rejects this importer");
let (_, shallow_forbid_violations) =
run_module_check("shallow-inbound-forbid", files, shallow_forbid);
assert!(
shallow_forbid_violations.is_empty(),
"{shallow_forbid_violations:?}"
);
let subtree_forbid = ModuleBoundary::in_crate("x")
.module("crate::protected")
.must_not_be_imported_by("crate::client")
.because("the protected subtree rejects this importer");
let (_, subtree_forbid_violations) =
run_module_check("subtree-inbound-forbid", files, subtree_forbid);
assert_eq!(
subtree_forbid_violations.len(),
1,
"{subtree_forbid_violations:?}"
);
let shallow_allow = ModuleBoundary::in_crate("x")
.module("crate::protected")
.must_only_be_imported_by(["crate::facade"])
.depth(xuanji::ScanDepth::Shallow)
.because("only the protected seam has a closed importer set");
let (_, shallow_allow_violations) =
run_module_check("shallow-inbound-allow", files, shallow_allow);
assert!(
shallow_allow_violations.is_empty(),
"{shallow_allow_violations:?}"
);
let subtree_allow = ModuleBoundary::in_crate("x")
.module("crate::protected")
.must_only_be_imported_by(["crate::facade"])
.because("the protected subtree has a closed importer set");
let (_, subtree_allow_violations) =
run_module_check("subtree-inbound-allow", files, subtree_allow);
assert_eq!(
subtree_allow_violations.len(),
1,
"{subtree_allow_violations:?}"
);
}
#[test]
pub(super) fn shallow_inbound_rules_react_to_an_item_import_of_the_anchored_module() {
let files = &[
(
"lib.rs",
"pub mod facade {}\npub mod protected;\npub mod client;\n",
),
("protected.rs", "pub struct Secret;\n"),
("client.rs", "use crate::protected::Secret;\n"),
];
let shallow_forbid = ModuleBoundary::in_crate("x")
.module("crate::protected")
.must_not_be_imported_by("crate::client")
.depth(xuanji::ScanDepth::Shallow)
.because("an item import of the anchored module still reacts under Shallow");
let (forbid_result, forbid_violations) =
run_module_check("shallow-inbound-item-forbid", files, shallow_forbid);
assert!(forbid_result.is_ok(), "{forbid_result:?}");
assert_eq!(
forbid_violations.len(),
1,
"an item-form import of the anchored module must react even under Shallow: {forbid_violations:?}"
);
let shallow_allow = ModuleBoundary::in_crate("x")
.module("crate::protected")
.must_only_be_imported_by(["crate::facade"])
.depth(xuanji::ScanDepth::Shallow)
.because("an item import of the anchored module still reacts under Shallow");
let (allow_result, allow_violations) =
run_module_check("shallow-inbound-item-allow", files, shallow_allow);
assert!(allow_result.is_ok(), "{allow_result:?}");
assert_eq!(
allow_violations.len(),
1,
"an item-form import by an importer outside the allowlist must react even under Shallow: {allow_violations:?}"
);
}
#[test]
pub(super) fn shallow_inbound_rules_never_flag_the_protected_modules_own_descendant_as_an_importer()
{
let files = &[
("lib.rs", "pub mod facade {}\npub mod protected;\n"),
("protected.rs", "pub mod detail;\npub struct Secret;\n"),
("protected/detail.rs", "use crate::protected::Secret;\n"),
];
let shallow_allow = ModuleBoundary::in_crate("x")
.module("crate::protected")
.must_only_be_imported_by(["crate::facade"])
.depth(xuanji::ScanDepth::Shallow)
.because("the protected module's own descendant is never an inbound importer");
let (allow_result, allow_violations) = run_module_check(
"shallow-inbound-self-descendant-allow",
files,
shallow_allow,
);
assert!(allow_result.is_ok(), "{allow_result:?}");
assert!(
allow_violations.is_empty(),
"a descendant of the protected module importing the protected module's own item must \
never be flagged, even under Shallow: {allow_violations:?}"
);
let shallow_forbid = ModuleBoundary::in_crate("x")
.module("crate::protected")
.must_not_be_imported_by("crate::protected::detail")
.depth(xuanji::ScanDepth::Shallow)
.because("the protected module's own descendant is never an inbound importer");
let (forbid_result, forbid_violations) = run_module_check(
"shallow-inbound-self-descendant-forbid",
files,
shallow_forbid,
);
assert!(forbid_result.is_ok(), "{forbid_result:?}");
assert!(
forbid_violations.is_empty(),
"a descendant of the protected module is never an inbound importer, even when it is also \
(degenerately) named as the forbidden importer: {forbid_violations:?}"
);
}
#[test]
pub(super) fn shallow_inbound_target_match_observes_the_value_namespace() {
let files = &[
(
"lib.rs",
"pub mod facade {}\npub mod protected;\npub mod consumer;\n",
),
("protected.rs", "pub mod foo;\npub fn foo() -> u8 { 7 }\n"),
("protected/foo.rs", "pub const INSIDE: u8 = 1;\n"),
("consumer.rs", "use crate::protected::foo;\n"),
];
let shallow = ModuleBoundary::in_crate("x")
.module("crate::protected")
.must_only_be_imported_by(["crate::facade"])
.depth(xuanji::ScanDepth::Shallow)
.because("only the facade may reach into protected");
let (shallow_result, shallow_violations) =
run_module_check("namespace-blind-shallow", files, shallow);
assert!(shallow_result.is_ok(), "{shallow_result:?}");
assert_eq!(
shallow_violations.len(),
1,
"`use crate::protected::foo;` binds the `fn foo` declared directly in the protected module, \
so it reaches that module and must react under Shallow: {shallow_violations:?}"
);
assert!(
shallow_violations[0].finding.contains("crate::consumer"),
"the finding names the importing module: {:?}",
shallow_violations[0].finding
);
let subtree = ModuleBoundary::in_crate("x")
.module("crate::protected")
.must_only_be_imported_by(["crate::facade"])
.depth(xuanji::ScanDepth::Subtree)
.because("only the facade may reach into protected");
let (subtree_result, subtree_violations) =
run_module_check("namespace-blind-subtree", files, subtree);
assert!(subtree_result.is_ok(), "{subtree_result:?}");
assert_eq!(
subtree_violations.len(),
1,
"under Subtree the two readings coincide, so the import must react: {subtree_violations:?}"
);
assert_eq!(subtree_violations[0].finding, "crate::consumer");
}
#[test]
pub(super) fn shallow_inbound_rules_do_not_read_a_file_the_self_import_exemption_excuses() {
let deep_use = format!(
"use crate::protected::{}Secret{};\n",
"{".repeat(200),
"}".repeat(200)
);
let files = &[
("lib.rs", "pub mod facade {}\npub mod protected;\n"),
("protected.rs", "pub mod detail;\npub struct Secret;\n"),
("protected/detail.rs", deep_use.as_str()),
];
for depth in [xuanji::ScanDepth::Shallow, xuanji::ScanDepth::Subtree] {
let boundary = ModuleBoundary::in_crate("x")
.module("crate::protected")
.must_only_be_imported_by(["crate::facade"])
.depth(depth)
.because("the protected module's own descendant is never an inbound importer");
let ws = TempWorkspace::new("shallow-inbound-self-descendant-unread");
for (file, source) in files {
ws.write(file, source);
}
let scans = crate::module_scan::EvaluationScans::shared();
let mut violations = Vec::new();
let result = crate::module_check::check_module_boundary(
&ws.metadata("x"),
&scans,
&boundary,
&mut violations,
);
assert!(
result.is_ok(),
"a file the self-import exemption excuses must never be read, so its content cannot \
produce a scan error at {depth:?}: {result:?}"
);
assert!(violations.is_empty(), "{depth:?}: {violations:?}");
assert_eq!(
scans.classifications(),
std::collections::HashMap::from([((ws.src().join("lib.rs"), "crate".to_string()), 1)]),
"only the root's imports are read; a file the self-import exemption excuses is never classified at {depth:?}"
);
}
}
#[test]
pub(super) fn shallow_external_confinement_permits_only_the_exact_module() {
let files = &[
("lib.rs", "pub mod secret;\n"),
("secret.rs", "pub mod detail;\n"),
("secret/detail.rs", "use libc::c_int;\n"),
];
let shallow = ModuleBoundary::in_crate("x")
.module("crate::secret")
.confine_external_crate("libc")
.depth(xuanji::ScanDepth::Shallow)
.because("only the secret seam may import libc");
let (shallow_result, shallow_violations) = run_module_check_with_deps(
"shallow-external-confinement",
files,
&[("libc", None)],
shallow,
);
assert!(shallow_result.is_ok(), "{shallow_result:?}");
assert_eq!(shallow_violations.len(), 1, "{shallow_violations:?}");
let subtree = ModuleBoundary::in_crate("x")
.module("crate::secret")
.confine_external_crate("libc")
.because("the secret subtree may import libc");
let (subtree_result, subtree_violations) = run_module_check_with_deps(
"subtree-external-confinement",
files,
&[("libc", None)],
subtree,
);
assert!(subtree_result.is_ok(), "{subtree_result:?}");
assert!(subtree_violations.is_empty(), "{subtree_violations:?}");
}
#[test]
pub(super) fn scan_depth_projection_omits_legacy_subtree_and_emits_shallow() {
let legacy = Constitution::new("legacy").boundary(
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_import("crate::adapter")
.because("core depends inward only"),
);
let legacy_json: serde_json::Value = serde_json::from_str(&constitution_json(&legacy)).unwrap();
assert!(
legacy_json["boundaries"][0].get("scan_depth").is_none(),
"legacy subtree projection must stay byte-compatible: {legacy_json}"
);
let shallow = Constitution::new("shallow").boundary(
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_import("crate::adapter")
.depth(xuanji::ScanDepth::Shallow)
.because("only the core seam depends inward"),
);
let shallow_json: serde_json::Value =
serde_json::from_str(&constitution_json(&shallow)).unwrap();
assert_eq!(shallow_json["boundaries"][0]["scan_depth"], "shallow");
}
#[test]
pub(super) fn legacy_inline_confinement_defaults_to_subtree_and_preserves_identity() {
let files = &[
("lib.rs", "pub mod core;\n"),
("core.rs", "pub mod sub;\n"),
(
"core/sub.rs",
"fn t() { let _ = std::time::SystemTime::now(); }\n",
),
];
let legacy_boundary = ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.because("core reads no wall clock");
let (res, violations) = run_module_check("legacy-inline-subtree", files, legacy_boundary);
assert!(res.is_ok(), "{res:?}");
assert_eq!(
violations.len(),
1,
"Legacy inline boundary governs submodules"
);
assert_eq!(
violations[0].rule_key().fields().collect::<Vec<_>>(),
vec![
("ending_with", "[]"),
("prefix", "std::time"),
("strict", "false")
]
);
let shallow_boundary = ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline("std::time")
.depth(xuanji::ScanDepth::Shallow)
.because("core seam reads no wall clock");
let (res2, shallow_violations) =
run_module_check("shallow-inline-seam", files, shallow_boundary);
assert!(res2.is_ok(), "{res2:?}");
assert_eq!(
shallow_violations.len(),
0,
"Explicit Shallow depth ignores submodule calls"
);
}
#[test]
pub(super) fn two_crates_with_the_identical_module_boundary_stay_distinct_violations() {
let alpha = TempWorkspace::new("identity-scope-alpha");
alpha.write("lib.rs", "pub mod app;\npub mod secret;\n");
alpha.write("app.rs", "use crate::secret::S;\n");
alpha.write("secret.rs", "pub struct S;\n");
let beta = TempWorkspace::new("identity-scope-beta");
beta.write("lib.rs", "pub mod app;\npub mod secret;\n");
beta.write("app.rs", "use crate::secret::S;\n");
beta.write("secret.rs", "pub struct S;\n");
fn package_json(ws: &TempWorkspace, name: &str) -> serde_json::Value {
let manifest = ws.dir().join("Cargo.toml");
serde_json::json!({
"name": name,
"manifest_path": manifest.to_string_lossy().into_owned(),
"dependencies": [],
})
}
let metadata = serde_json::json!({
"packages": [package_json(&alpha, "alpha"), package_json(&beta, "beta")]
});
fn boundary_for(package: &str) -> ModuleBoundary {
ModuleBoundary::in_crate(package)
.module("crate::app")
.must_not_import("crate::secret")
.because("app must not touch secret")
}
let constitution = Constitution::new("probe")
.boundary(boundary_for("alpha"))
.boundary(boundary_for("beta"));
let outcome = evaluate(&constitution, &metadata);
let report = match outcome {
Outcome::Violations(report) => report,
other => panic!("expected two violations, got {other:?}"),
};
assert_eq!(
report.violations.len(),
2,
"each crate's violation must survive dedup: {:?}",
report.violations
);
let ids: std::collections::BTreeSet<_> = report.violations.iter().map(Violation::id).collect();
assert_eq!(
ids.len(),
2,
"identity must differ by crate, not collapse to one"
);
let files: std::collections::BTreeSet<_> = report
.violations
.iter()
.map(|v| v.file.clone().expect("each violation carries a file"))
.collect();
assert_eq!(
files.len(),
2,
"each violation must keep its own crate's file, not share one"
);
let alpha_only_constitution = Constitution::new("probe").boundary(boundary_for("alpha"));
let alpha_only_report = match evaluate(&alpha_only_constitution, &metadata) {
Outcome::Violations(report) => report,
other => panic!("expected alpha's violation, got {other:?}"),
};
assert_eq!(alpha_only_report.violations.len(), 1);
let baseline = Baseline::of(&alpha_only_report);
let both_constitution = Constitution::new("probe")
.boundary(boundary_for("alpha"))
.boundary(boundary_for("beta"));
let mut both_report = match evaluate(&both_constitution, &metadata) {
Outcome::Violations(report) => report,
other => panic!("expected two violations, got {other:?}"),
};
apply_baseline(&mut both_report, &baseline);
let alpha_violation = both_report
.violations
.iter()
.find(|v| v.target() == "crate::app" && baseline.contains(v))
.expect("alpha's violation must match the baseline");
assert!(alpha_violation.baselined, "alpha's violation was accepted");
let unbaselined: Vec<_> = both_report
.violations
.iter()
.filter(|v| !v.baselined)
.collect();
assert_eq!(
unbaselined.len(),
1,
"beta's violation must react as new, not be suppressed by alpha's baseline: {:?}",
both_report.violations
);
}
#[test]
pub(super) fn an_unterminated_block_comment_swallowing_a_multibyte_char_does_not_panic() {
let (result, violations) = run_module_check(
"unterminated-block-comment-multibyte",
&[
(
"lib.rs",
"pub mod forbidden;\npub mod child;\n/* \u{672a}\u{5b8c}",
),
("forbidden.rs", "pub struct Thing;\n"),
("child.rs", "use crate::forbidden::Thing;\n"),
],
ModuleBoundary::in_crate("x")
.module("crate::child")
.must_not_import("crate::forbidden")
.because("probe"),
);
assert!(
result.is_ok(),
"an unterminated block comment must not abort the scan: {result:?}"
);
assert_eq!(violations.len(), 1, "{violations:?}");
assert_eq!(violations[0].target(), "crate::child");
assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}
#[test]
pub(super) fn an_unterminated_block_comment_at_end_of_file_with_no_trailing_newline_does_not_panic()
{
let (result, violations) = run_module_check(
"unterminated-block-comment-eof",
&[
("lib.rs", "pub mod forbidden {}\npub mod child;\n/*\u{7121}"),
("child.rs", "use crate::forbidden::Thing;\n"),
("forbidden.rs", "pub struct Thing;\n"),
],
ModuleBoundary::in_crate("x")
.module("crate::child")
.must_not_import("crate::forbidden")
.because("probe"),
);
assert!(
result.is_ok(),
"an unterminated block comment must not abort the scan: {result:?}"
);
assert_eq!(violations.len(), 1, "{violations:?}");
assert_eq!(violations[0].target(), "crate::child");
assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}
#[test]
pub(super) fn a_non_ascii_char_literal_adjacent_to_a_brace_literal_does_not_leak_a_spurious_brace()
{
let (result, violations) = run_module_check(
"char-literal-brace-leak-no-space",
&[
(
"lib.rs",
"pub mod forbidden;\nconst Q: [char; 2] = ['\u{ab}','{'];\npub mod hidden;\n",
),
(
"hidden.rs",
"use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
),
("forbidden.rs", "pub struct Thing;\n"),
],
ModuleBoundary::in_crate("x")
.module("crate")
.must_not_import("crate::forbidden")
.because("probe"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "{violations:?}");
assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}
#[test]
pub(super) fn a_boundary_anchored_directly_at_the_previously_dropped_module_resolves() {
let (result, violations) = run_module_check(
"char-literal-brace-leak-anchored-at-dropped",
&[
(
"lib.rs",
"pub mod forbidden;\nconst Q: [char; 2] = ['\u{ab}','{'];\npub mod hidden;\n",
),
(
"hidden.rs",
"use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
),
("forbidden.rs", "pub struct Thing;\n"),
],
ModuleBoundary::in_crate("x")
.module("crate::hidden")
.must_not_import("crate::forbidden")
.because("probe"),
);
assert!(
result.is_ok(),
"crate::hidden must be reachable, not a constitution error: {result:?}"
);
assert_eq!(violations.len(), 1, "{violations:?}");
assert_eq!(violations[0].target(), "crate::hidden");
}
#[test]
pub(super) fn a_non_ascii_char_literal_adjacent_to_a_brace_literal_in_a_match_arm_does_not_leak() {
let (result, violations) = run_module_check(
"char-literal-brace-leak-match-arm",
&[
(
"lib.rs",
"pub mod forbidden;\npub fn is_special(c: char) -> bool { match c { '\u{e9}'|'{' => true, _ => false } }\npub mod hidden;\n",
),
(
"hidden.rs",
"use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
),
("forbidden.rs", "pub struct Thing;\n"),
],
ModuleBoundary::in_crate("x")
.module("crate")
.must_not_import("crate::forbidden")
.because("probe"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "{violations:?}");
assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}
#[test]
pub(super) fn the_spaced_spelling_of_the_same_array_literal_already_reacts_and_keeps_reacting() {
let (result, violations) = run_module_check(
"char-literal-brace-leak-with-space",
&[
(
"lib.rs",
"pub mod forbidden;\nconst Q: [char; 2] = ['\u{ab}', '{'];\npub mod hidden;\n",
),
(
"hidden.rs",
"use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
),
("forbidden.rs", "pub struct Thing;\n"),
],
ModuleBoundary::in_crate("x")
.module("crate")
.must_not_import("crate::forbidden")
.because("probe"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "{violations:?}");
assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}
#[test]
pub(super) fn a_four_byte_scalar_char_literal_adjacent_to_a_brace_literal_does_not_leak() {
let (result, violations) = run_module_check(
"char-literal-brace-leak-four-byte-scalar",
&[
(
"lib.rs",
"pub mod forbidden;\nconst Q: [char; 2] = ['\u{1f980}','{'];\npub mod hidden;\n",
),
(
"hidden.rs",
"use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
),
("forbidden.rs", "pub struct Thing;\n"),
],
ModuleBoundary::in_crate("x")
.module("crate")
.must_not_import("crate::forbidden")
.because("probe"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "{violations:?}");
assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}
#[test]
pub(super) fn two_unmatched_braces_cascading_from_chained_char_literals_do_not_leak() {
let (result, violations) = run_module_check(
"char-literal-brace-leak-two-unmatched-cascade",
&[
(
"lib.rs",
"pub mod forbidden;\nconst Q: [char; 3] = ['\u{ab}','{','{'];\npub mod hidden;\n",
),
(
"hidden.rs",
"use crate::forbidden::Thing;\npub fn leak() -> crate::forbidden::Thing { crate::forbidden::Thing }\n",
),
("forbidden.rs", "pub struct Thing;\n"),
],
ModuleBoundary::in_crate("x")
.module("crate")
.must_not_import("crate::forbidden")
.because("probe"),
);
assert!(result.is_ok(), "{result:?}");
assert_eq!(violations.len(), 1, "{violations:?}");
assert_eq!(violations[0].finding, "crate::forbidden::Thing");
}
const INLINE_PREFIX_SPELLINGS: &[(&str, Result<&str, Option<&str>>)] = &[
("std::time", Ok("std::time")),
("crate::clock", Ok("crate::clock")),
("crate::r#clock", Ok("crate::clock")),
("r#std::time", Ok("std::time")),
("clock", Ok("clock")),
("crate::clock::", Err(Some("crate::clock"))),
("::std::time", Ok("::std::time")),
("::std::time::", Err(Some("::std::time"))),
("crate::::clock", Err(Some("crate::clock"))),
("std :: time", Err(Some("std::time"))),
(" crate::clock", Err(Some("crate::clock"))),
("r#crate::clock", Err(Some("crate::clock"))),
("self::clock", Err(None)),
("Self::clock", Err(None)),
("super::clock", Err(None)),
("std::time::*", Err(None)),
("std::process\u{200e}", Err(None)),
("std::\u{2028}time", Err(Some("std::time"))),
("std::pro\u{ad}cess", Err(None)),
("std::\u{2060}process", Err(None)),
("std::process\u{2014}", Err(None)),
("core::pro\u{ad}cess", Err(None)),
("md5x::pro\u{ad}cess", Err(None)),
("md5x::\u{2060}hash", Err(None)),
("md5x::\u{1f980}", Err(None)),
("md5x::\u{e9}t\u{e9}", Ok("md5x::\u{e9}t\u{e9}")),
("md5x::\u{6a21}\u{7d44}", Ok("md5x::\u{6a21}\u{7d44}")),
("md5x::_\u{e9}", Ok("md5x::_\u{e9}")),
("proc_macro::Token\u{405}tream", Err(None)),
("test::bl\u{43e}ck_box", Err(None)),
("std::_", Err(None)),
("md5x::_", Err(None)),
];
#[test]
pub(super) fn an_inline_prefix_is_accepted_only_in_its_canonical_spelling() {
let wrong: Vec<_> = INLINE_PREFIX_SPELLINGS
.iter()
.filter_map(|(written, expected)| {
let answer =
crate::module_scan::canonical_symbol_path_spelling(written).map(|prefix| {
match prefix.root {
crate::module_scan::PrefixRoot::Global => format!("::{}", prefix.path),
crate::module_scan::PrefixRoot::Bare => prefix.path,
}
});
let expected = expected
.map(str::to_string)
.map_err(|s| s.map(str::to_string));
(answer != expected).then(|| format!("{written:?}: {answer:?}, expected {expected:?}"))
})
.collect();
assert!(wrong.is_empty(), "{wrong:#?}");
}
fn inline_prefix_fixture(label: &str) -> (TempWorkspace, Value) {
let ws = TempWorkspace::new(label);
ws.write("lib.rs", "pub mod clock;\npub mod core;\n");
ws.write(
"clock.rs",
"pub fn now() -> u64 { 0 }\npub struct Clock;\nimpl Clock { pub fn now() -> u64 { 0 } }\n",
);
ws.write("core.rs", "pub fn tick() -> u64 { crate::clock::now() }\n");
ws.write("bin/tool.rs", "mod cli;\nfn main() {}\n");
ws.write("bin/cli.rs", "pub fn run() {}\n");
let metadata = serde_json::json!({
"packages": [{
"name": "x",
"dependencies": [
{ "name": "extdep" },
{ "name": "otherdep", "rename": "renamed" },
{ "name": "my-dep" },
],
"targets": [
{ "name": "x", "kind": ["lib"], "src_path": ws.src().join("lib.rs").to_string_lossy() },
{ "name": "tool", "kind": ["bin"], "src_path": ws.src().join("bin/tool.rs").to_string_lossy() },
],
}],
});
(ws, metadata)
}
type PrefixRole = fn(&str) -> ModuleBoundary;
fn inline_prefix_roles() -> [(&'static str, PrefixRole); 2] {
[
("must_not_call_inline", |p| {
ModuleBoundary::in_crate("x")
.module("crate::core")
.must_not_call_inline(p)
.because("r")
}),
("confine_inline_call", |p| {
ModuleBoundary::in_crate("x")
.module("crate::clock")
.confine_inline_call(p)
.because("r")
}),
]
}
fn check_prefix(
metadata: &Value,
boundary: ModuleBoundary,
) -> (Result<(), String>, Vec<Violation>) {
let mut violations = Vec::new();
let result = check_module_boundary(metadata, &boundary, &mut violations);
(result, violations)
}
#[test]
pub(super) fn an_inline_prefix_naming_a_module_reacts_on_its_call() {
let (_ws, metadata) = inline_prefix_fixture("inline-prefix-module");
let expected = Ok(vec!["crate::clock::now in crate::core".to_string()]);
assert_every_prefix(&metadata, &["crate::clock", "crate::clock::now"], |_, _| {
expected.clone()
});
}
#[test]
pub(super) fn a_misspelled_crate_prefix_is_refused_not_judged_clean() {
let (_ws, metadata) = inline_prefix_fixture("inline-prefix-misspelled");
assert_every_prefix(
&metadata,
&["crate::clcok", "crate::clock::nwo", "crate::cli::x"],
|rule, prefix| {
Err(crate::errors::unknown_inline_prefix_error(
prefix, "x", rule,
))
},
);
}
#[test]
pub(super) fn a_prefix_written_without_its_crate_root_is_refused_with_the_rooted_spelling() {
let (_ws, metadata) = inline_prefix_fixture("inline-prefix-unrooted");
assert_every_prefix(&metadata, &["clock", "clock::now"], |rule, prefix| {
Err(crate::errors::unknown_inline_prefix_head_error(
prefix,
"x",
rule,
&format!("crate::{prefix}"),
))
});
}
#[test]
pub(super) fn a_first_segment_naming_another_crate_is_accepted() {
let (_ws, metadata) = inline_prefix_fixture("inline-prefix-other-crate");
assert_every_prefix(
&metadata,
&["proc_macro", "test", "x::core", "inilike::load", "my_dep"],
|_, _| Ok(Vec::new()),
);
}
#[test]
pub(super) fn a_prefix_with_a_trailing_separator_is_refused() {
let (_ws, metadata) = inline_prefix_fixture("inline-prefix-trailing");
let suggestion = |prefix: &str| match prefix {
"crate::clock::" => Some("crate::clock"),
"::std::time::" => Some("::std::time"),
"std::time::" => Some("std::time"),
"extdep::api::" => Some("extdep::api"),
_ => None,
};
assert_every_prefix(
&metadata,
&[
"crate::clock::",
"std::time::",
"::std::time::",
"extdep::api::",
"my-dep",
"self::clock",
"Self::clock",
],
|rule, prefix| {
Err(crate::errors::non_canonical_inline_prefix_error(
prefix,
"x",
rule,
suggestion(prefix),
))
},
);
}
#[test]
pub(super) fn an_inline_prefix_naming_something_that_exists_is_accepted() {
let (_ws, metadata) = inline_prefix_fixture("inline-prefix-exists");
let accepted = [
"crate::clock::now",
"crate::r#clock",
"crate::clock::Clock",
"crate",
"::std::time",
"std::time",
"core::time",
"alloc::vec",
"extdep",
"extdep::api",
"renamed::x",
"my_dep::f",
"crate::cli",
"crate::cli::run",
];
assert_every_prefix(&metadata, &accepted, |rule, prefix| {
let (result, violations) = check_prefix(&metadata, inline_prefix_role(rule)(prefix));
result.map(|()| findings_of(&violations))
});
assert_every_prefix(&metadata, &[" "], |rule, _| {
Err(crate::errors::inline_empty_prefix_error("x", rule))
});
}
#[test]
pub(super) fn a_prefix_past_what_guibiao_reads_is_not_verified() {
let (_ws, metadata) = inline_prefix_fixture("inline-prefix-unread");
assert_every_prefix(
&metadata,
&[
"std::tiem",
"extdep::nosuch",
"crate::clock::Clock::nwo",
"clcok",
"otherdep",
],
|_, _| Ok(Vec::new()),
);
}
#[test]
pub(super) fn a_prefix_naming_a_macro_generated_item_is_refused() {
let mut wrong = Vec::new();
for (form, invocation) in [
("parenthesized", "make!(pub fn stamp() -> u64 { 0 });"),
("braced", "make! { pub fn stamp() -> u64 { 0 } }"),
] {
let ws = TempWorkspace::new(&format!("inline-prefix-macro-item-{form}"));
ws.write("lib.rs", "pub mod clock;\npub mod core;\n");
ws.write(
"clock.rs",
&format!("macro_rules! make {{ ($i:item) => {{ $i }}; }}\n{invocation}\n"),
);
ws.write(
"core.rs",
"pub fn tick() -> u64 { crate::clock::stamp() }\n",
);
let metadata = ws.metadata("x");
for (rule, role) in inline_prefix_roles() {
let (result, violations) = check_prefix(&metadata, role("crate::clock::stamp"));
let want = Err(crate::errors::unknown_inline_prefix_error(
"crate::clock::stamp",
"x",
rule,
));
if result != want {
wrong.push(format!("{form} {rule}: got {result:?} {violations:?}"));
}
}
}
assert!(wrong.is_empty(), "\n{}", wrong.join("\n"));
}
fn inline_prefix_role(rule: &str) -> PrefixRole {
inline_prefix_roles()
.into_iter()
.find_map(|(name, role)| (name == rule).then_some(role))
.expect("a role the table declares")
}
fn findings_of(violations: &[Violation]) -> Vec<String> {
violations.iter().map(|v| v.finding.clone()).collect()
}
fn assert_every_prefix(
metadata: &Value,
prefixes: &[&str],
expected: impl Fn(&str, &str) -> Result<Vec<String>, String>,
) {
let mut wrong = Vec::new();
for (rule, role) in inline_prefix_roles() {
for prefix in prefixes {
let (result, violations) = check_prefix(metadata, role(prefix));
let answer = result.map(|()| findings_of(&violations));
let want = expected(rule, prefix);
if answer != want {
wrong.push(format!(
"{rule}({prefix:?}):\n got {answer:?}\n want {want:?}"
));
}
}
}
assert!(wrong.is_empty(), "\n{}", wrong.join("\n"));
}