lean-ctx-engine 3.12.12

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
Documentation
// SPDX-License-Identifier: Apache-2.0
use super::*;

/// Two-crate workspace: `a-lib` (re-exports, a glob, a `#[path]` module, a
/// `#[cfg(test)]` child file, an inline `mod tests`, a `mod.rs` facade) and
/// the binary `b` that reaches `a-lib` items through its re-exports.
const FIXTURE: &[(&str, &str)] = &[
    ("Cargo.toml", "[workspace]\nmembers = [\"a-lib\", \"b\"]\n"),
    (
        "a-lib/Cargo.toml",
        "[package]\nname = \"a-lib\"\nversion = \"0.1.0\"\n",
    ),
    (
        "a-lib/src/lib.rs",
        r#"//! a_lib::ghost is mentioned only in this comment.
pub mod config;
mod util;
pub mod net;
#[path = "gen/generated.rs"]
pub mod generated;

pub use config::Settings;
pub use util::*;
"#,
    ),
    (
        "a-lib/src/config.rs",
        r"pub struct Settings;

pub fn load() -> Settings {
    crate::generated::make()
}

#[cfg(test)]
mod config_tests;

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

    #[test]
    fn loads() {
        let _ = load();
    }
}
",
    ),
    (
        "a-lib/src/config/config_tests.rs",
        "use super::Settings;\n\n#[test]\nfn builds() {\n    let _ = Settings;\n}\n",
    ),
    (
        "a-lib/src/util.rs",
        r#"/// Unlike crate::config::Settings, this needs no setup.
pub fn helper() -> &'static str {
    "crate::net::client::get"
}
"#,
    ),
    (
        "a-lib/src/gen/generated.rs",
        "pub fn make() -> crate::config::Settings {\n    crate::config::Settings\n}\n",
    ),
    ("a-lib/src/net/mod.rs", "pub mod client;\n"),
    ("a-lib/src/net/client.rs", "pub fn get() {}\n"),
    (
        "b/Cargo.toml",
        "[package]\nname = \"b\"\nversion = \"0.1.0\"\n\n[dependencies]\na-lib = { path = \"../a-lib\" }\n",
    ),
    (
        "b/src/main.rs",
        r"use a_lib::helper;
use a_lib::Settings;

fn main() {
    let _s: Settings = a_lib::config::load();
    a_lib::net::client::get();
    let _ = helper();
}
",
    ),
    // Declared by no module: its dependents are unknown, not "none".
    ("b/src/orphan.rs", "pub fn lost() {}\n"),
];

fn resolve_fixture() -> RustModuleGraph {
    let dir = tempfile::tempdir().expect("tempdir");
    for (path, body) in FIXTURE {
        let full = dir.path().join(path);
        std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
        std::fs::write(&full, body).expect("write fixture");
    }
    let files: Vec<String> = FIXTURE
        .iter()
        .map(|(p, _)| (*p).to_string())
        .filter(|p| is_rs(p))
        .collect();
    // Empty cache: sources are read from disk like an uncached scan.
    resolve_workspace(dir.path(), &files, &HashMap::new())
}

fn pairs(list: &[(&str, &str)]) -> Vec<(String, String)> {
    let mut out: Vec<(String, String)> = list
        .iter()
        .map(|(a, b)| ((*a).to_string(), (*b).to_string()))
        .collect();
    out.sort();
    out
}

#[test]
fn fixture_import_edges_are_exact() {
    let graph = resolve_fixture();
    assert_eq!(
        graph.imports,
        pairs(&[
            ("a-lib/src/config.rs", "a-lib/src/gen/generated.rs"),
            ("a-lib/src/config/config_tests.rs", "a-lib/src/config.rs"),
            ("a-lib/src/gen/generated.rs", "a-lib/src/config.rs"),
            ("a-lib/src/lib.rs", "a-lib/src/config.rs"),
            ("a-lib/src/lib.rs", "a-lib/src/util.rs"),
            ("b/src/main.rs", "a-lib/src/config.rs"),
            ("b/src/main.rs", "a-lib/src/net/client.rs"),
            ("b/src/main.rs", "a-lib/src/util.rs"),
        ])
    );
}

#[test]
fn fixture_module_edges_follow_path_and_cfg_test_children() {
    let graph = resolve_fixture();
    assert_eq!(
        graph.modules,
        pairs(&[
            ("a-lib/src/config.rs", "a-lib/src/config/config_tests.rs"),
            ("a-lib/src/lib.rs", "a-lib/src/config.rs"),
            ("a-lib/src/lib.rs", "a-lib/src/gen/generated.rs"),
            ("a-lib/src/lib.rs", "a-lib/src/net/mod.rs"),
            ("a-lib/src/lib.rs", "a-lib/src/util.rs"),
            ("a-lib/src/net/mod.rs", "a-lib/src/net/client.rs"),
        ])
    );
}

#[test]
fn facades_never_receive_import_edges() {
    let graph = resolve_fixture();
    let mut facades: Vec<&str> = graph.facades.iter().map(String::as_str).collect();
    facades.sort_unstable();
    assert_eq!(
        facades,
        ["a-lib/src/lib.rs", "a-lib/src/net/mod.rs", "b/src/main.rs"]
    );
    for (from, to) in &graph.imports {
        assert!(
            !graph.facades.contains(to),
            "import edge {from} -> facade {to}"
        );
    }
}

#[test]
fn comments_and_strings_add_no_edges() {
    let graph = resolve_fixture();
    // util.rs names `crate::config::Settings` in a doc comment and
    // `crate::net::client::get` in a string; neither is a use.
    assert!(
        graph
            .imports
            .iter()
            .all(|(from, _)| from != "a-lib/src/util.rs"),
        "{:?}",
        graph.imports
    );
}

#[test]
fn undeclared_file_is_not_mapped() {
    let graph = resolve_fixture();
    assert!(!graph.mapped.contains("b/src/orphan.rs"));
    for file in [
        "a-lib/src/lib.rs",
        "a-lib/src/config.rs",
        "a-lib/src/config/config_tests.rs",
        "a-lib/src/gen/generated.rs",
        "a-lib/src/net/client.rs",
        "b/src/main.rs",
    ] {
        assert!(graph.mapped.contains(file), "{file} not mapped");
    }
}

#[test]
fn super_chain_and_self_resolve_from_nested_inline_modules() {
    let dir = tempfile::tempdir().expect("tempdir");
    let files = [
        (
            "Cargo.toml",
            "[package]\nname = \"c\"\nversion = \"0.1.0\"\n",
        ),
        ("src/lib.rs", "pub mod outer;\npub mod leaf;\n"),
        ("src/outer/mod.rs", "pub mod inner;\n"),
        (
            "src/outer/inner.rs",
            "mod deep {\n    mod deeper {\n        use super::super::super::super::leaf::Leaf;\n        use self::x::Y;\n        mod x { pub struct Y; }\n    }\n}\n",
        ),
        ("src/leaf.rs", "pub struct Leaf;\n"),
    ];
    for (path, body) in files {
        let full = dir.path().join(path);
        std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
        std::fs::write(&full, body).expect("write fixture");
    }
    let rs: Vec<String> = files
        .iter()
        .map(|(p, _)| (*p).to_string())
        .filter(|p| is_rs(p))
        .collect();
    let graph = resolve_workspace(dir.path(), &rs, &HashMap::new());
    assert_eq!(
        graph.imports,
        pairs(&[("src/outer/inner.rs", "src/leaf.rs")])
    );
}

fn resolve_files(files: &[(&str, &str)]) -> RustModuleGraph {
    let dir = tempfile::tempdir().expect("tempdir");
    for (path, body) in files {
        let full = dir.path().join(path);
        std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
        std::fs::write(&full, body).expect("write fixture");
    }
    let rs: Vec<String> = files
        .iter()
        .map(|(p, _)| (*p).to_string())
        .filter(|p| is_rs(p))
        .collect();
    resolve_workspace(dir.path(), &rs, &HashMap::new())
}

/// `#[cfg_attr(pred, path = "…")]` names another file of the same module.
/// The predicate is not evaluated, so both the default file and every
/// existing cfg_attr target are loaded, declared and searched for items;
/// a cfg_attr target that does not exist adds nothing.
const CFG_ATTR_FIXTURE: &[(&str, &str)] = &[
    (
        "Cargo.toml",
        "[package]\nname = \"plat\"\nversion = \"0.1.0\"\n",
    ),
    (
        "src/lib.rs",
        "#[cfg_attr(windows, path = \"platform/win.rs\")]\nmod platform;\n\
         #[cfg_attr(unix, cfg_attr(feature = \"x\", path = \"sys_x.rs\"))]\nmod sys;\n\
         #[path = \"chosen.rs\"]\n#[cfg_attr(test, path = \"chosen_test.rs\")]\nmod picked;\n\
         #[cfg_attr(test, path = \"missing.rs\")]\nmod gone;\n\
         mod user;\n",
    ),
    ("src/platform.rs", "pub struct Unix;\n"),
    ("src/platform/win.rs", "pub struct Native;\n"),
    ("src/sys.rs", "pub fn plain() {}\n"),
    ("src/sys_x.rs", "pub fn extra() {}\n"),
    ("src/chosen.rs", "pub fn chosen() {}\n"),
    ("src/chosen_test.rs", "pub fn under_test() {}\n"),
    ("src/gone.rs", "pub fn here() {}\n"),
    (
        "src/user.rs",
        "use crate::platform::Native;\nuse crate::platform::Unix;\n\
         use crate::sys::extra;\nuse crate::picked::under_test;\nuse crate::gone::here;\n",
    ),
];

#[test]
fn cfg_attr_path_targets_are_additional_module_files() {
    let graph = resolve_files(CFG_ATTR_FIXTURE);
    assert_eq!(
        graph.modules,
        pairs(&[
            ("src/lib.rs", "src/chosen.rs"),
            ("src/lib.rs", "src/chosen_test.rs"),
            ("src/lib.rs", "src/gone.rs"),
            ("src/lib.rs", "src/platform.rs"),
            ("src/lib.rs", "src/platform/win.rs"),
            ("src/lib.rs", "src/sys.rs"),
            ("src/lib.rs", "src/sys_x.rs"),
            ("src/lib.rs", "src/user.rs"),
        ])
    );
    assert_eq!(
        graph.imports,
        pairs(&[
            ("src/user.rs", "src/chosen_test.rs"),
            ("src/user.rs", "src/gone.rs"),
            ("src/user.rs", "src/platform.rs"),
            ("src/user.rs", "src/platform/win.rs"),
            ("src/user.rs", "src/sys_x.rs"),
        ])
    );
    for file in [
        "src/platform.rs",
        "src/platform/win.rs",
        "src/sys.rs",
        "src/sys_x.rs",
        "src/chosen.rs",
        "src/chosen_test.rs",
    ] {
        assert!(graph.mapped.contains(file), "{file} not mapped");
    }
    assert!(!graph.mapped.contains("src/missing.rs"));
}

#[test]
fn index_edges_carry_the_shared_kinds_and_weights() {
    let graph = resolve_fixture();
    let edges = graph.index_edges();
    assert_eq!(edges.len(), graph.imports.len() + graph.modules.len());
    let (imports, modules): (Vec<_>, Vec<_>) =
        edges.iter().partition(|e| e.kind == IMPORT_EDGE_KIND);
    assert!(
        imports
            .iter()
            .all(|e| (e.weight - IMPORT_EDGE_WEIGHT).abs() < f32::EPSILON)
    );
    assert!(modules.iter().all(
        |e| e.kind == MODULE_EDGE_KIND && (e.weight - MODULE_EDGE_WEIGHT).abs() < f32::EPSILON
    ));
    let import_pairs: Vec<(String, String)> = imports
        .iter()
        .map(|e| (e.from.clone(), e.to.clone()))
        .collect();
    assert_eq!(import_pairs, graph.imports);
    let module_pairs: Vec<(String, String)> = modules
        .iter()
        .map(|e| (e.from.clone(), e.to.clone()))
        .collect();
    assert_eq!(module_pairs, graph.modules);
}

#[test]
fn unresolved_dependents_reason_matches_module_tree_position() {
    assert_eq!(unresolved_dependents_reason(true, false), None);
    assert_eq!(unresolved_dependents_reason(true, true), None);
    assert!(unresolved_dependents_reason(false, true).is_some_and(|r| r.contains("crate root")));
    assert!(unresolved_dependents_reason(false, false).is_some_and(|r| r.contains("module tree")));
}

/// Windows: the graph index keys files with `\\`. The resolver must place
/// them exactly like `/`-separated keys and name every file by the caller's key.
#[test]
fn backslash_keys_resolve_like_slash_keys() {
    let dir = tempfile::tempdir().expect("tempdir");
    for (path, body) in FIXTURE {
        let full = dir.path().join(path);
        std::fs::create_dir_all(full.parent().expect("parent")).expect("mkdir");
        std::fs::write(&full, body).expect("write fixture");
    }
    let rs: Vec<&(&str, &str)> = FIXTURE.iter().filter(|(p, _)| is_rs(p)).collect();
    let files: Vec<String> = rs.iter().map(|(p, _)| p.replace('/', "\\")).collect();
    // Cached sources keyed like the files, as the index scan passes them.
    let contents: HashMap<String, String> = rs
        .iter()
        .map(|(p, body)| (p.replace('/', "\\"), (*body).to_string()))
        .collect();
    let graph = resolve_workspace(dir.path(), &files, &contents);
    let slash = resolve_fixture();
    let back = |list: &[(String, String)]| -> Vec<(String, String)> {
        let mut out: Vec<(String, String)> = list
            .iter()
            .map(|(a, b)| (a.replace('/', "\\"), b.replace('/', "\\")))
            .collect();
        out.sort();
        out
    };
    assert!(!slash.imports.is_empty() && !slash.modules.is_empty());
    assert_eq!(graph.imports, back(&slash.imports));
    assert_eq!(graph.modules, back(&slash.modules));
    let mapped = |set: &HashSet<String>| -> Vec<String> {
        let mut out: Vec<String> = set.iter().map(|f| f.replace('/', "\\")).collect();
        out.sort();
        out
    };
    assert_eq!(mapped(&graph.mapped), mapped(&slash.mapped));
    assert!(graph.mapped.contains("a-lib\\src\\config.rs"));
    assert_eq!(mapped(&graph.facades), mapped(&slash.facades));
}