Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/facett

facett-core/tests/attribute_owner_law.rs

//! **An attribute binds to the NEXT item — so anything wedged between the two
//! silently changes its owner, and the code still compiles.**
//!
//! Three independent instances were measured across the constellation on
//! 2026-08-22, every one of them found by accident:
//!
//! * `nornir/src/lib.rs` — a doc comment landed between `#[cfg(feature = "mcp")]`
//!   and `pub mod mcp_stdio;`. `mcp_stdio` went UNCONDITIONAL (281 rmcp/schemars
//!   errors in every default build) and the freshly added `lens_chain` inherited
//!   the gate, so it built only with `--features mcp` — which is what hid that it
//!   did not build at all.
//! * `edda/crates/nornir-service` — the same wedge moved
//!   `#[cfg(feature = "auth-provider")]` onto a `pub use`, and every default build
//!   of the crate died on an unresolved `provider`.
//! * `korp/src/main.rs` — a new test was pasted between an existing `#[test]` and
//!   its function, so one function carried two `#[test]`s and
//!   `korp_state_exposes_all_views` carried none. It had not run for months. The
//!   suite was green. The only signal in the whole build was a single
//!   `duplicate_macro_attributes` warning.
//!
//! This file is what notices, and it is deliberately three rules rather than a
//! lint switch:
//!
//! | rule | what it names | what `rustc` says |
//! |---|---|---|
//! | duplicate attribute | one item carrying `#[test]` (or any byte-identical attribute) twice | `duplicate_macro_attributes`, a warning |
//! | gate above a doc comment | `#[cfg]`/`#[test]` sitting above a doc comment, i.e. gating whatever follows the doc | nothing at all — the attribute IS used, by the wrong item |
//! | test function with no `#[test]` | a sentence-named zero-arg fn in a test scope that nothing calls | `dead_code`, a warning, and only if no `allow` is in scope |
//!
//! `duplicate_macro_attributes` and `unused_attributes` are warn-by-default and
//! could be promoted to `deny` instead. Measured before writing this: promoting
//! `duplicate_macro_attributes` across the constellation would cost **3** fixes,
//! which is affordable — but it covers only the first row. It says nothing about
//! the nornir and nornir-service instances, where the attribute is used, just by
//! the wrong item; those two are exactly the rows a lint cannot see, and they are
//! the two that broke a build. So the deny is worth having AND is not enough.
//!
//! Run: `cargo test -p facett-core --test attribute_owner_law`

use facett_core::law;
use std::path::{Path, PathBuf};

/// `#` on its own, so the planted shapes below are **assembled** rather than
/// written literally — this file is scanned like every other one, and a guard
/// that has to be carved out of its own scan is a guard that has stopped
/// guarding. Same trick, same reason, as `law::rayon_call_tokens`'s `concat!`.
const H: &str = "#";

fn root() -> PathBuf {
    law::workspace_root(Path::new(env!("CARGO_MANIFEST_DIR")))
}

/// The three shapes, planted. This is the RED half of the guard and it runs on
/// every invocation, so the scanner demonstrates that it can fail instead of
/// asserting that it still could.
#[test]
fn the_scanner_names_all_three_shapes() {
    // Shape 1 — the korp instance, reduced. `#[test]` twice on one function;
    // `stranded_one` below it is a test that no longer runs.
    let dup = format!(
        "{H}[cfg(test)]\n\
         mod tests {{\n\
         \x20   /// The doc of the test that lost its attribute.\n\
         \x20   {H}[test]\n\
         \x20   /// The doc of the test that was pasted in on top of it.\n\
         \x20   {H}[test]\n\
         \x20   fn the_new_one_that_took_both_attributes() {{}}\n\
         \n\
         \x20   fn the_old_one_that_is_no_longer_a_test() {{}}\n\
         }}\n"
    );
    let hits = law::attribute_hits(Path::new("/planted/dup.rs"), &dup);
    let tokens: Vec<&str> = hits.iter().map(|h| h.token.as_str()).collect();
    assert!(
        tokens.iter().any(|t| t.contains("duplicate #[test]")),
        "the duplicate #[test] was not named; hits = {tokens:?}"
    );
    assert!(
        hits.iter().any(|h| h.token.contains("test function with no #[test]")
            && h.text.contains("the_old_one_that_is_no_longer_a_test")),
        "the stranded test function was not named; hits = {hits:?}"
    );
    assert!(
        hits.iter().any(|h| h.token.contains("gate above a doc comment")),
        "the wedge itself was not named; hits = {hits:?}"
    );

    // Shape 2 — the nornir instance, reduced: a doc + a whole new item pasted
    // between `#[cfg(feature = "mcp")]` and the module it was written for.
    let wedge = format!(
        "/// The module the gate was written for.\n\
         {H}[cfg(feature = \"mcp\")]\n\
         /// The module that was pasted in and took the gate.\n\
         pub mod the_new_module;\n\
         pub mod the_module_that_lost_its_gate;\n"
    );
    let hits = law::attribute_hits(Path::new("/planted/wedge.rs"), &wedge);
    let gate = hits.iter().find(|h| h.token.contains("gate above a doc comment")).unwrap_or_else(|| {
        panic!("the cfg wedge was not named; hits = {hits:?}");
    });
    assert_eq!(gate.line, 2, "the hit must point at the attribute's own line");
    assert!(
        gate.token.contains("cfg(feature = \"mcp\")"),
        "the hit must name the attribute it found: {}",
        gate.token
    );

    // Shape 3 — the edda/nornir-service instance: a doc between the gate and the
    // `pub use` it belonged to.
    let reexport = format!(
        "{H}[cfg(feature = \"auth-provider\")]\n\
         /// Re-exported for downstreams.\n\
         pub use provider::{{Provider, ProviderError}};\n"
    );
    let hits = law::attribute_hits(Path::new("/planted/reexport.rs"), &reexport);
    assert!(
        hits.iter().any(|h| h.token.contains("gate above a doc comment")),
        "the re-export wedge was not named; hits = {hits:?}"
    );
}

/// The other half of LAW 2: the shapes the scanner must NOT flag. A rule that
/// fires on ordinary code is a rule that gets switched off within the week, and
/// every line here is a shape that a first cut of this scanner did flag.
#[test]
fn ordinary_code_is_not_flagged() {
    let clean = r#"
/// Docs first, gate last — the conforming order.
#[cfg(feature = "mcp")]
pub mod mcp_stdio;

/// A struct whose fields carry inline attributes.
#[derive(Debug)]
pub struct Config {
    #[serde(default)] pub path: String,
    /// A documented field.
    #[serde(default)]
    pub core_saturation: bool,
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A heavy test whose #[ignore] reason spans several lines.
    #[test]
    #[ignore = "HEAVY: downloads a kernel and compiles it in a container, which is \
                thirty minutes and 150 MB, so it runs only on demand"]
    fn a_real_vanilla_kernel_compiles_in_a_container() {}

    // A blank line between the attribute and the item is legal Rust.
    #[test]

    fn bench_compare_all_methods() {}

    /// A signature pin, deliberately never called.
    #[allow(dead_code)]
    fn serve_signature_is_stable() {}

    /// garmr-webui declares every browser test this way.
    #[wasm_bindgen_test]
    fn glyph_only_controls_need_an_accessible_name() {}

    fn a_helper_that_is_called_below() {}

    #[test]
    fn the_helper_is_used() {
        a_helper_that_is_called_below();
    }
}
"#;
    let hits = law::attribute_hits(Path::new("/planted/clean.rs"), clean);
    assert!(hits.is_empty(), "ordinary code was flagged:\n{hits:#?}");

    // A file BELOW `tests/` is a shared helper module, not a test binary: cargo never
    // runs it on its own, and the sibling binary that says `mod support;` is what calls
    // into it. Judging it by "is it called in this file" reported nornir's whole MCP
    // harness as a dead test.
    let helper = "fn run_full_coverage() {}\n";
    assert!(
        law::attribute_hits(Path::new("/repo/tests/support/mcp_harness.rs"), helper).is_empty(),
        "a helper module below tests/ is not a test binary"
    );
    assert!(
        !law::attribute_hits(Path::new("/repo/tests/mcp_harness.rs"), helper).is_empty(),
        "…but the same shape in a real test binary at tests/*.rs still counts"
    );
}

/// A scan that read no files finds no violations and looks exactly like a clean
/// run. That false green is this constellation's signature bug, so the file count
/// is asserted before the verdict is believed — and asserted here to be capable of
/// being zero, which is the red proof for the assertion itself.
#[test]
fn a_scan_that_reads_nothing_is_not_a_pass() {
    let nowhere = Path::new("/home/alice/scratch/attrs-law-no-such-workspace");
    let empty = law::scan_attributes(nowhere);
    assert_eq!(empty.scanned, 0, "a workspace that does not exist reads no files");
    assert!(
        empty.hits.is_empty(),
        "…and therefore reports no hits — which is why `scanned` is the thing the \
         real guard below asserts on FIRST"
    );
}

#[test]
fn no_attribute_in_this_workspace_has_lost_its_item() {
    let root = root();
    let scan = law::scan_attributes(&root);

    assert!(
        scan.scanned > 100,
        "the attribute scan only read {} files under {} — it is not looking at the \
         workspace, and an empty scan is shaped exactly like a clean one",
        scan.scanned,
        root.display(),
    );

    assert!(
        scan.hits.is_empty(),
        "an attribute has lost the item it was written for ({} file(s) scanned). An \
         attribute binds to the NEXT item, so a doc comment or a pasted item between \
         the two silently re-parents it — the code compiles and the tests stay \
         green:\n{}",
        scan.scanned,
        scan.hits.iter().map(|h| format!("  {h}")).collect::<Vec<_>>().join("\n"),
    );
}