Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

requirements.references.outlines

Requirements index · View definition

evidence Valid

Requirement

Habeas MUST parse Rust, Python, TypeScript, CSS, Markdown, TOML, and YAML sources with pinned tree-sitter grammars, selected by file extension compared case-insensitively. A source with any syntax error MUST fail to parse, reporting the line of its first error. Every other text file MUST use a plain-text profile in which each line that is not blank is an anonymous outline node of kind line. Each supported language MUST have an outline profile that maps grammar node kinds to short outline kind names and, for each mapped kind, states whether a node is named, and by which fields or children, or anonymous. Only mapped kinds MUST appear in the outline; other nodes MUST be transparent, so their outline descendants appear under the nearest outline ancestor. A profile MAY attach grammar siblings to an outline node, such as Rust attributes and doc comments preceding an item, so the outline tree need not match the grammar tree exactly; attached siblings are part of that node for its line range and hash. Every file’s outline MUST have a root node for the whole file, independent of language. Source in no other outline node, such as top-level statements no profile maps, MUST belong to the root node; profiles MUST NOT invent fallback kinds for it. Comments MUST NOT be outline nodes. Profiles MUST be documented. Upgrading a grammar or profile MAY change outlines and MUST be treated as a deliberate change.

Rationale

The reviewed tests cover each obligation in requirements.references.outlines.

  • Languages and extension selection.
    • profiles_are_selected_by_extension_case_insensitively checks uppercase and mixed-case extensions. These map to rust, python, tsx, markdown and toml. It also checks that notes and notes.rs.txt fall back to plain text.
    • every_profile_mapping_is_documented iterates every profile’s extensions.
    • The per-language profile tests parse Rust, Python, TypeScript and TSX, CSS, Markdown, TOML and YAML.
  • Pinned grammars. grammar_dependencies_are_pinned_to_exact_versions asserts that every tree-sitter-* dependency in Cargo.toml uses an exact =x.y.z pin.
  • Syntax errors. reports_parse_failures_with_lines covers Rust, Python and TOML. The Rust case asserts that the error line is 2. The TOML case has several errors and asserts that the first one (line 3) is reported, with the line 3: message prefix. That is the “first error” obligation. I read check_errors, which handles both error nodes and missing nodes in one generic path. So the tests don’t need a case per language or error kind.
  • Plain text. plain_text_lines_are_interchangeable_anonymous_nodes asserts that blank lines are skipped and that each non-blank line is a line@… node. outline_lists_nested_nodes_without_text_or_inputs asserts that every plain-text entry has kind line and a null name.
  • Profile kind mapping. The Rust, Python, TypeScript, CSS, Markdown, TOML and YAML tests assert the mapped kinds, names and anonymity (section@, item@, use@, macro@). profile_rules_map_only_matching_contexts_and_keep_other_nodes_transparent shows that unmapped kinds are not emitted. In that test, descendants of an unmapped node are reparented to the nearest mapped ancestor, here the root. item_macros_are_anonymous_nodes_and_expression_macros_are_not covers the same point from the other side.
  • Attached siblings. hashes_skip_whitespace_and_plain_comments_but_not_doc_comments asserts that a node’s line range spans its doc comment and attribute (1 to 4). It also asserts that these siblings change the node’s hash. identity_hashes_include_own_attached_siblings_but_not_descendants covers the identity hash.
  • Root node.
    • outline.resolve("") returns 0 in rust_selectors_follow_syntactic_ancestry.
    • file_level_inner_doc_comments_and_unmapped_code_belong_to_the_root and python_profile_outlines_defs_classes_and_statements check that unmapped top-level code, file-level doc comments and front matter belong to the root.
    • line_queries_find_innermost_nodes maps a blank line to the root.
  • No fallback kinds. no_profile_invents_fallback_kinds runs every language with unmapped top-level statements. It asserts that no stmt, block, node or item fallback kinds appear and that only the root exists where nothing is mapped.
  • Comments are not nodes. The Rust, Python, CSS, TOML, YAML and Markdown tests contain comments. Their exact selector and summary assertions would fail if a comment became a node.
  • Documentation. every_profile_mapping_is_documented checks every profile’s extensions and every kind rule against the “Outline profiles” table in md/reference.md. It also checks the plain-text row.
  • Grammar upgrades. This is a process obligation with a MAY. It is not testable and imposes nothing.

I found no requirement-violating behavior that these assertions would accept.

Inputs

Tests

Input 2: outline src/authoring/tools.rs mod[tests]/fn[outline_lists_nested_nodes_without_text_or_inputs]
    // {test}`requirements.authoring.outline_tool`
    // {test}`requirements.references.outlines`
    // {test}`requirements.authoring.no_line_numbers`
    // {test}`requirements.authoring.read_denial`
    #[test]
    fn outline_lists_nested_nodes_without_text_or_inputs() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "/// Docs.\nstruct Thing;\n\nimpl Thing {\n    fn run(&self) {}\n}\n",
        )
        .unwrap();
        fs::write(root.path().join("notes.txt"), "alpha\n\nbeta\n").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let outline = dispatch(&sources, "outline", &json!({"file":"src/lib.rs"})).unwrap();
        assert!(outline.inputs.is_empty());
        assert_eq!(
            outline.result,
            json!([
                {"item": "struct[Thing]", "kind": "struct", "name": "Thing", "children": []},
                {"item": "impl[Thing]", "kind": "impl", "name": "Thing", "children": [
                    {"item": "impl[Thing]/fn[run]", "kind": "fn", "name": "run", "children": []},
                ]},
            ])
        );
        assert!(!outline.result.to_string().contains("Docs"));
        let plain = dispatch(&sources, "outline", &json!({"file":"notes.txt"})).unwrap();
        let entries = plain.result.as_array().unwrap();
        assert_eq!(entries.len(), 2);
        assert!(entries.iter().all(|entry| entry["kind"] == "line"
            && entry["name"].is_null()
            && entry["item"].as_str().unwrap().starts_with("line@")));
        assert!(entries[1].get("line_start").is_none());
        for (arguments, message) in [
            (json!({"file":"missing.rs"}), "missing.rs"),
            (json!({}), "file"),
            (json!({"file":1}), "file"),
            (json!({"file":"src/lib.rs", "extra":true}), "extra"),
        ] {
            let error = dispatch(&sources, "outline", &arguments).err().unwrap();
            assert!(error.to_string().contains(message), "{arguments}: {error}");
        }
        let error = dispatch(&sources, "outline", &json!({})).err().unwrap();
        assert!(
            error.to_string().contains("file must be a string"),
            "{error}"
        );

        fs::write(
            root.path().join("habeas.toml"),
            "version = 1\n[evidence]\ndisallow = ['notes.txt']\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let error = dispatch(&sources, "outline", &json!({"file":"notes.txt"}))
            .err()
            .unwrap();
        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
        assert!(error.to_string().contains("notes.txt"), "{error}");
        assert!(error.to_string().contains("disallowed"), "{error}");
    }
Input 3: outline src/outline/tests.rs fn[profile_rules_map_only_matching_contexts_and_keep_other_nodes_transparent]
  • File: src/outline/tests.rs
  • Selector: fn[profile_rules_map_only_matching_contexts_and_keep_other_nodes_transparent]
  • Kind: fn
  • src/outline/tests.rs:16–53
// {test}`requirements.references.outlines`
// {test}`requirements.references.outline_selectors`
#[test]
fn profile_rules_map_only_matching_contexts_and_keep_other_nodes_transparent() {
    use super::profile::{KindRule, NameRule, Profile};

    let rules = vec![
        KindRule::new("function_item", "fn", NameRule::Field("name")).when(|node| {
            node.child_by_field_name("name")
                .is_some_and(|name| name.start_position().column == 3)
        }),
        KindRule::new("struct_item", "struct", NameRule::Field("name")),
    ];
    let profile = Box::leak(Box::new(Profile {
        kinds: Box::leak(rules.into_boxed_slice()),
        ..super::rust::PROFILE
    }));
    // A function indented by two spaces is not mapped, but its descendants
    // still appear under the nearest mapped ancestor, here the file root.
    let source = "fn selected() {}\n  fn skipped() {\nfn nested() {}\n}\nstruct Packet;\n";
    let outline = super::parse_with(profile, source).unwrap();
    assert_eq!(
        selectors(&outline),
        ["fn[selected]", "fn[nested]", "struct[Packet]"]
    );
    assert!(outline.nodes[1..].iter().all(|node| node.parent == Some(0)));
    assert_eq!(format!("{outline:?}").matches("profile: rust").count(), 1);
    let missing = outline.resolve("fn[skipped]").unwrap_err();
    assert_eq!(
        missing.to_string(),
        "no outline node matches \"fn[skipped]\""
    );
    let malformed = outline.resolve("fn[bad%ZZ]").unwrap_err();
    assert!(matches!(malformed, super::ResolveError::Invalid(_)));
    let message = malformed.to_string();
    assert!(message.contains("invalid outline selector"), "{message}");
    assert!(message.contains("malformed percent escape"), "{message}");
}
Input 4: outline src/outline/tests.rs fn[every_profile_mapping_is_documented]
// {test}`requirements.references.outlines`
#[test]
fn every_profile_mapping_is_documented() {
    let reference = include_str!("../../md/reference.md");
    let table = reference
        .split_once("### Outline profiles\n")
        .unwrap()
        .1
        .split_once("\nProfile details:")
        .unwrap()
        .0;
    let mut group = "";
    let mut rows = Vec::new();
    for line in table.lines().filter(|line| line.starts_with('|')) {
        let cells: Vec<_> = line.split('|').map(str::trim).collect();
        if !cells[1].is_empty() {
            group = cells[1];
        }
        rows.push((group, cells));
    }
    for profile in super::profile::profiles() {
        let name = match profile.name {
            "rust" => "Rust",
            "python" => "Python",
            "typescript" | "tsx" => "TypeScript",
            "css" => "CSS",
            "markdown" => "Markdown",
            "toml" => "TOML",
            "yaml" => "YAML",
            name => panic!("undocumented profile {name}"),
        };
        for extension in profile.extensions {
            assert!(
                rows.iter().any(|(group, cells)| *group == name
                    && cells[2].contains(&format!("`.{extension}`"))),
                "{name}: .{extension}"
            );
        }
        for rule in profile.kinds {
            assert!(
                rows.iter().any(|(group, cells)| {
                    *group == name
                        && cells[3].contains(&format!("`{}`", rule.kind))
                        && cells[4].contains(&format!("`{}`", rule.grammar))
                        && !cells[5].is_empty()
                }),
                "{name}: {} -> {}",
                rule.grammar,
                rule.kind
            );
        }
    }
    assert!(rows.iter().any(|(group, cells)| *group == "Plain text"
        && cells[3] == "`line`"
        && cells[4] == "each non-blank line"
        && cells[5] == "anonymous"));
}
Input 5: outline src/outline/tests.rs fn[grammar_dependencies_are_pinned_to_exact_versions]
// {test}`requirements.references.outlines`
#[test]
fn grammar_dependencies_are_pinned_to_exact_versions() {
    let manifest: toml::Table = toml::from_str(include_str!("../../Cargo.toml")).unwrap();
    let dependencies = manifest["dependencies"].as_table().unwrap();
    let version = regex::Regex::new(r"^=\d+\.\d+\.\d+$").unwrap();
    let grammars: Vec<_> = dependencies
        .iter()
        .filter(|(name, _)| name.starts_with("tree-sitter-"))
        .collect();
    assert!(!grammars.is_empty());
    for (name, dependency) in grammars {
        let pin = dependency
            .as_str()
            .or_else(|| dependency.get("version").and_then(toml::Value::as_str))
            .unwrap();
        assert!(version.is_match(pin), "{name}: {pin}");
    }
}
Input 6: outline src/outline/tests.rs fn[rust_selectors_follow_syntactic_ancestry]
// {test}`requirements.references.outline_selectors`
// {test}`requirements.references.rust_item_selectors`
// {test}`requirements.references.selector_nested`
// {test}`requirements.references.selector_impl_and_trait`
// {test}`requirements.references.selector_inline_and_foreign`
// {test}`requirements.references.selector_duplicate_names`
// {test}`requirements.references.outlines`
#[test]
fn rust_selectors_follow_syntactic_ancestry() {
    let source = r#"
mod local { fn run() {} }
mod external;
struct Thing;
impl Thing { fn run() {} }
impl Trait for Thing { fn run() {} }
impl [u8; 4] { fn edge() {} }
trait Trait { fn read(&self); type Item; }
extern "C" { fn puts(); }
extern { fn other(); }
fn outer() { fn inner() {} }
#[cfg(a)] fn repeated() {}
#[cfg(b)] fn repeated() {}
macro_rules! make { () => {} }
union U { a: u8 }
enum E { A }
const C: u8 = 1;
static S: u8 = 1;
type Alias = u8;
extern crate core;
"#;
    let outline = outline("src/lib.rs", source);
    let selectors = selectors(&outline);
    for selector in [
        "mod[local]/fn[run]",
        "mod[external]",
        "struct[Thing]",
        "impl[Thing]/fn[run]",
        "impl[Thing/Trait]/fn[run]",
        "impl[%5Bu8;%204%5D]/fn[edge]",
        "trait[Trait]/fn[read]",
        "trait[Trait]/type[Item]",
        "extern[C]/fn[puts]",
        "extern[Rust]/fn[other]",
        "fn[outer]/fn[inner]",
        "fn[repeated]#1",
        "fn[repeated]#2",
        "macro[make]",
        "union[U]",
        "enum[E]",
        "const[C]",
        "static[S]",
        "type[Alias]",
        "extern-crate[core]",
    ] {
        assert!(
            selectors.contains(&selector.to_owned()),
            "{selector}: {selectors:?}"
        );
        assert_eq!(
            outline.nodes[outline.resolve(selector).unwrap()].selector,
            selector
        );
    }
    assert_eq!(outline.resolve("").unwrap(), 0);
    assert!(outline.resolve("fn[repeated]").is_err());
    assert!(outline.resolve("fn[missing]").is_err());
}
Input 7: outline src/outline/tests.rs fn[identity_hashes_include_own_attached_siblings_but_not_descendants]
// {test}`requirements.references.structural_hash`
// {test}`requirements.references.outlines`
#[test]
fn identity_hashes_include_own_attached_siblings_but_not_descendants() {
    let hashes = |source: &str, selector: &str| {
        let outline = outline("src/lib.rs", source);
        let node = &outline.nodes[outline
            .resolve(selector)
            .unwrap_or_else(|error| panic!("{selector}: {error:?}"))];
        (node.structural_hash.clone(), node.identity_hash.clone())
    };

    // A descendant's attached doc comment and attribute are outside its
    // ancestor's identity hash, though inside its structural hash.
    let base = "mod m {\n    /// Doc.\n    #[inline]\n    fn a() {}\n}\n";
    let (structural, identity) = hashes(base, "mod[m]");
    for edited in [
        base.replace("Doc.", "Changed doc."),
        base.replace("inline", "cold"),
        base.replace("    /// Doc.\n", ""),
    ] {
        let (edited_structural, edited_identity) = hashes(&edited, "mod[m]");
        assert_ne!(edited_structural, structural, "{edited}");
        assert_eq!(edited_identity, identity, "{edited}");
    }

    // A node's own attached doc comment and attribute are part of its identity
    // hash, so they distinguish otherwise identical anonymous nodes.
    let own = |source: &str| {
        let outline = outline("src/lib.rs", source);
        outline.nodes[1].identity_hash.clone()
    };
    let plain = own("use a::A;\n");
    let documented = own("/// Doc.\nuse a::A;\n");
    let attributed = own("#[cfg(test)]\nuse a::A;\n");
    assert_ne!(plain, documented);
    assert_ne!(plain, attributed);
    assert_ne!(own("/// Other.\nuse a::A;\n"), documented);
    assert_ne!(own("#[cfg(not(test))]\nuse a::A;\n"), attributed);
    // The identity hash of a node without descendants is its structural hash.
    let (structural, identity) = hashes("#[cfg(test)]\nfn b() {}\n", "fn[b]");
    assert_eq!(structural, identity);
}
Input 8: outline src/outline/tests.rs fn[hashes_skip_whitespace_and_plain_comments_but_not_doc_comments]
// {test}`requirements.references.structural_hash`
// {test}`requirements.references.selector_raw_lines`
// {test}`requirements.references.outlines`
#[test]
fn hashes_skip_whitespace_and_plain_comments_but_not_doc_comments() {
    let base = concat!(
        "/// Doc.\n#[inline]\n// {cite}",
        "`a.b`\nfn run() { let x = 1; }\n"
    );
    let hash = |source: &str| {
        let outline = outline("src/lib.rs", source);
        let node = &outline.nodes[outline.resolve("fn[run]").unwrap()];
        (node.structural_hash.clone(), node.line_start, node.line_end)
    };
    let (original, start, end) = hash(base);
    assert_eq!((start, end), (1, 4));
    let (moved, start, _) = hash(&format!("\n\n{base}"));
    assert_eq!((moved.as_str(), start), (original.as_str(), 3));
    assert_eq!(
        hash(concat!(
            "/// Doc.\n#[inline]\n// {cite}",
            "`c.d`\nfn run() {\n    let x  =  1;\n}\n"
        ))
        .0,
        original
    );
    assert_ne!(hash(&base.replace("Doc.", "Docs.")).0, original);
    assert_ne!(hash(&base.replace("inline", "cold")).0, original);
    assert_ne!(hash(&base.replace("= 1", "= 2")).0, original);

    let parent = |source: &str| {
        let outline = outline("src/lib.rs", source);
        let node = &outline.nodes[outline.resolve("mod[m]").unwrap()];
        (node.structural_hash.clone(), node.identity_hash.clone())
    };
    let (structural, identity) = parent("mod m { fn a() {} }");
    let (edited_structural, edited_identity) = parent("mod m { fn a() { 1; } }");
    assert_ne!(structural, edited_structural);
    assert_eq!(identity, edited_identity);
}
Input 9: outline src/outline/tests.rs fn[line_queries_find_innermost_nodes]
// {test}`requirements.references.outlines`
#[test]
fn line_queries_find_innermost_nodes() {
    let source = "impl Thing { fn run() {} }\n\nfn a() {} fn b() {}\nfn outer() {\n    let x = 1;\n    fn inner() {}\n}\n";
    let outline = outline("src/lib.rs", source);
    let names = |indices: Vec<usize>| {
        indices
            .into_iter()
            .map(|index| outline.nodes[index].selector.clone())
            .collect::<Vec<_>>()
    };
    assert_eq!(names(outline.innermost_at_line(1)), ["impl[Thing]/fn[run]"]);
    assert_eq!(names(outline.innermost_at_line(2)), [""]);
    assert_eq!(names(outline.innermost_at_line(3)), ["fn[a]", "fn[b]"]);
    assert_eq!(names(outline.innermost_at_line(5)), ["fn[outer]"]);
    assert_eq!(names(outline.nodes_for_lines(4..=7, false)), ["fn[outer]"]);
    assert_eq!(
        names(outline.nodes_for_lines(5..=6, false)),
        ["fn[outer]"],
        "an ancestor absorbs its selected descendants"
    );
    assert!(outline.innermost_at_line(99).is_empty());
}
Input 10: outline src/outline/tests.rs fn[plain_text_lines_are_interchangeable_anonymous_nodes]
// {test}`requirements.references.outlines`
// {test}`requirements.references.outline_selectors`
#[test]
fn plain_text_lines_are_interchangeable_anonymous_nodes() {
    let outline = outline("notes.txt", "alpha\n\n  beta  \nalpha\n");
    let selectors = selectors(&outline);
    assert_eq!(selectors.len(), 3);
    assert!(
        selectors
            .iter()
            .all(|selector| selector.starts_with("line@"))
    );
    assert_eq!(selectors[0], selectors[2]);
    assert_eq!(outline.resolve(&selectors[0]).unwrap(), 1);
    assert_eq!(outline.nodes[2].structural_hash, super::hash::line("beta"));
    let spaced = super::parse(Path::new("notes.txt"), "two  words\n").unwrap();
    let single = super::parse(Path::new("notes.txt"), "two words\n").unwrap();
    let joined = super::parse(Path::new("notes.txt"), "twowords\n").unwrap();
    assert_eq!(spaced.nodes[1].selector, single.nodes[1].selector);
    assert_ne!(single.nodes[1].selector, joined.nodes[1].selector);
    assert_eq!(outline.innermost_at_line(2), [0]);
    assert_eq!(outline.innermost_at_line(3), [2]);
}
Input 11: outline src/outline/tests.rs fn[reports_parse_failures_with_lines]
// {test}`requirements.references.outlines`
#[test]
fn reports_parse_failures_with_lines() {
    let error = parse(Path::new("src/lib.rs"), "fn ok() {}\nfn broken( {\n").unwrap_err();
    assert_eq!(error.line, 2, "{error}");
    assert!(parse(Path::new("a.py"), "def f(:\n").is_err());
    let late = parse(Path::new("a.toml"), "a = 1\nb = 2\nc = = 3\nd = [\n").unwrap_err();
    assert_eq!(late.line, 3, "the first error is reported: {late}");
    assert!(late.to_string().starts_with("line 3: "), "{late}");
}
Input 12: outline src/outline/tests.rs fn[profiles_are_selected_by_extension_case_insensitively]
// {test}`requirements.references.outlines`
#[test]
fn profiles_are_selected_by_extension_case_insensitively() {
    for (path, profile) in [
        ("src/LIB.RS", "rust"),
        ("a.Py", "python"),
        ("a.TSX", "tsx"),
        ("README.MD", "markdown"),
        ("Cargo.TOML", "toml"),
        ("notes", "plain-text"),
        ("notes.rs.txt", "plain-text"),
    ] {
        assert_eq!(
            super::profile_for_path(Path::new(path)).name,
            profile,
            "{path}"
        );
    }
}
Input 13: outline src/outline/tests.rs fn[python_profile_outlines_defs_classes_and_statements]
// {test}`requirements.references.outlines`
#[test]
fn python_profile_outlines_defs_classes_and_statements() {
    let source = "import os\n# lead\n@dec\ndef f(x):\n    return x\nclass C(B):\n    def m(self):\n        pass\nif __name__ == \"__main__\":\n    f(1)\n";
    let outline = outline("a.py", source);
    assert_eq!(
        summary(&outline),
        ["def[f] 2-5", "class[C] 6-8", "class[C]/def[m] 7-8",]
    );
    assert_eq!(
        outline.owner_at_line(1),
        0,
        "a top-level import maps to the root"
    );
    assert_eq!(
        outline.owner_at_line(10),
        0,
        "a top-level `if` maps to the root"
    );
    assert_eq!(outline.innermost_at_line(9), [0]);
    assert_eq!(outline.nodes_for_lines(9..=10, false), [0]);
}
Input 14: outline src/outline/tests.rs fn[typescript_profile_outlines_declarations]
// {test}`requirements.references.outlines`
#[test]
fn typescript_profile_outlines_declarations() {
    let source = "export function f(a: number): void {}\nclass C { m(): void {} x = 1; }\ninterface I { m(): void; }\ntype T = string;\nenum E { A }\nnamespace N { function g() {} }\nconst h = () => 1;\n";
    let outline = outline("a.ts", source);
    assert_eq!(
        selectors(&outline)
            .into_iter()
            .map(|selector| selector.split('@').next().unwrap().to_owned())
            .collect::<Vec<_>>(),
        [
            "function[f]",
            "class[C]",
            "class[C]/method[m]",
            "interface[I]",
            "interface[I]/method[m]",
            "type[T]",
            "enum[E]",
            "namespace[N]",
            "namespace[N]/function[g]",
        ]
    );
    let tsx = super::parse(Path::new("a.tsx"), "function App() { return <div/>; }\n").unwrap();
    assert_eq!(selectors(&tsx), ["function[App]"]);
}
Input 15: outline src/outline/tests.rs fn[css_profile_names_rules_by_normalized_selectors]
// {test}`requirements.references.outlines`
#[test]
fn css_profile_names_rules_by_normalized_selectors() {
    let source = "/* c */\na  >  b,\n.x { color: red; }\n@media (max-width: 600px) { a { b: c } }\n@keyframes spin { from { x: y } }\n@import \"x.css\";\n";
    let outline = outline("a.css", source);
    assert_eq!(
        summary(&outline),
        [
            "rule[a%20>%20b,%20.x] 1-3",
            "media[(max-width:%20600px)] 4-4",
            "media[(max-width:%20600px)]/rule[a] 4-4",
            "keyframes[spin] 5-5",
        ]
    );
}
Input 16: outline src/outline/tests.rs fn[markdown_profile_nests_sections_by_heading]
// {test}`requirements.references.outlines`
#[test]
fn markdown_profile_nests_sections_by_heading() {
    let source = "---\ntitle: x\n---\nintro\n\n# Head  *one*\npara\n<!-- note -->\n## Sub\ntext\n";
    let outline = outline("a.md", source);
    assert_eq!(
        summary(&outline),
        [
            "section@ 4-5",
            "section[Head%20*one*] 6-10",
            "section[Head%20*one*]/section[Sub] 8-10"
        ]
    );
    assert_eq!(outline.comments.len(), 1);
    let reflowed = super::parse(
        Path::new("a.md"),
        &source.replace("Head  *one*\npara", "Head *one*\n\npara"),
    )
    .unwrap();
    let selector = "section[Head%20*one*]";
    assert_eq!(
        outline.nodes[outline.resolve(selector).unwrap()].structural_hash,
        reflowed.nodes[reflowed.resolve(selector).unwrap()].structural_hash
    );
}
Input 17: outline src/outline/tests.rs fn[toml_and_yaml_profiles_name_keys]
// {test}`requirements.references.outlines`
#[test]
fn toml_and_yaml_profiles_name_keys() {
    let toml = outline(
        "a.toml",
        "# c\na = 1\n[t.u]\n\"q\" = { x = 1 }\n[[arr]]\nb = 2\n[[arr]]\nb = 3\n",
    );
    assert_eq!(
        selectors(&toml),
        [
            "pair[a]",
            "table[t.u]",
            "table[t.u]/pair[\"q\"]",
            "table[t.u]/pair[\"q\"]/pair[x]",
            "table[arr]#1",
            "table[arr]#1/pair[b]",
            "table[arr]#2",
            "table[arr]#2/pair[b]",
        ]
    );
    let yaml = outline(
        "a.yml",
        "# c\na: 1\n\"b\":\n  c: {d: 1}\n  e:\n    - f: 1\n    - 2\n",
    );
    assert_eq!(
        summary(&yaml),
        [
            "pair[a] 1-2",
            "pair[\"b\"] 3-7",
            "pair[\"b\"]/pair[c] 4-4",
            "pair[\"b\"]/pair[c]/pair[d] 4-4",
            "pair[\"b\"]/pair[e] 5-7",
            "pair[\"b\"]/pair[e]/item@ 6-6",
            "pair[\"b\"]/pair[e]/item@/pair[f] 6-6",
            "pair[\"b\"]/pair[e]/item@ 7-7",
        ]
    );
}
Input 18: outline src/outline/tests.rs fn[selectors_name_syntactic_ancestry_and_duplicates]
// {test}`requirements.references.rust_item_selectors`
// {test}`requirements.references.selector_nested`
// {test}`requirements.references.selector_impl_and_trait`
// {test}`requirements.references.selector_inline_and_foreign`
// {test}`requirements.references.selector_duplicate_names`
// {test}`requirements.references.selector_use`
// {test}`requirements.references.outlines`
#[test]
fn selectors_name_syntactic_ancestry_and_duplicates() {
    let source = r#"
use alpha::A;
use beta::B;
mod local { fn run() {} }
mod external;
struct Thing;
impl Thing { fn run() {} }
impl Trait for Thing { fn run() {} }
impl [u8; 4] { fn edge() {} }
trait Trait { fn read(&self); }
extern "C" { fn puts(); }
fn outer() { fn inner() {} }
#[cfg(a)] fn repeated() {}
#[cfg(b)] fn repeated() {}
"#;
    let selectors = selectors(&outline("lib.rs", source));
    assert!(selectors[0].starts_with("use@") && selectors[1].starts_with("use@"));
    assert_ne!(selectors[0], selectors[1]);
    for selector in [
        "mod[local]/fn[run]",
        "mod[external]",
        "struct[Thing]",
        "impl[Thing]/fn[run]",
        "impl[Thing/Trait]/fn[run]",
        "impl[%5Bu8;%204%5D]/fn[edge]",
        "trait[Trait]/fn[read]",
        "extern[C]/fn[puts]",
        "fn[outer]/fn[inner]",
        "fn[repeated]#1",
        "fn[repeated]#2",
    ] {
        assert!(
            selectors.contains(&selector.to_owned()),
            "{selector}: {selectors:?}"
        );
    }
}
Input 19: outline src/outline/tests.rs fn[file_level_inner_doc_comments_and_unmapped_code_belong_to_the_root]
// {test}`requirements.references.outlines`
// {test}`requirements.references.outline_comments`
#[test]
fn file_level_inner_doc_comments_and_unmapped_code_belong_to_the_root() {
    let source = "//! Crate docs.\n//! More.\nfn a() {}\n";
    let lines = outline("src/lib.rs", source);
    assert_eq!(comment_owner(&lines, source, "Crate docs"), "");
    assert_eq!(comment_owner(&lines, source, "More"), "");
    assert_eq!(lines.owner_at_line(1), 0);
    let a = &lines.nodes[lines.resolve("fn[a]").unwrap()];
    assert_eq!((a.line_start, a.line_end), (3, 3));
    let source = "/*! Crate docs. */\nfn a() {}\n";
    let block = outline("src/lib.rs", source);
    assert_eq!(comment_owner(&block, source, "Crate docs"), "");
    let markdown = outline("a.md", "---\ntitle: x\n---\n# H\n");
    assert_eq!(
        markdown.owner_at_line(2),
        0,
        "front matter maps to the root"
    );
}
Input 20: outline src/outline/tests.rs fn[no_profile_invents_fallback_kinds]
// {test}`requirements.references.outlines`
#[test]
fn no_profile_invents_fallback_kinds() {
    let sources = [
        ("src/lib.rs", "use a::b;\nfn f() {}\n"),
        ("a.py", "import os\nx = 1\nif x:\n    pass\n"),
        ("a.ts", "const h = () => 1;\nimport x from \"y\";\n"),
        ("a.css", "@import \"x.css\";\n@charset \"utf-8\";\n"),
        ("a.md", "---\ntitle: x\n---\n"),
        ("a.toml", "a = 1\n"),
        ("a.yml", "- 1\n- 2\n"),
        ("a.yml", "plain scalar\n"),
    ];
    for (path, source) in sources {
        let outline = outline(path, source);
        for node in &outline.nodes[1..] {
            assert!(
                !matches!(node.kind, "stmt" | "block" | "node")
                    && !(node.kind == "item" && !path.ends_with(".yml")),
                "{path}: fallback kind {:?}",
                node.selector
            );
        }
    }
    assert_eq!(outline("a.py", "x = 1\n").nodes.len(), 1);
    assert_eq!(outline("a.ts", "const h = 1;\n").nodes.len(), 1);
    assert_eq!(outline("a.yml", "plain scalar\n").nodes.len(), 1);
}
Input 21: outline src/outline/tests.rs fn[duplicate_names_are_numbered_in_source_order_without_line_numbers]
// {test}`requirements.references.selector_duplicate_names`
// {test}`requirements.references.outlines`
#[test]
fn duplicate_names_are_numbered_in_source_order_without_line_numbers() {
    let source = "#[cfg(a)]\nfn run() { a() }\n#[cfg(b)]\nfn run() { b() }\n";
    let first = outline("src/lib.rs", source);
    assert_eq!(selectors(&first), ["fn[run]#1", "fn[run]#2"]);
    let node = |outline: &Outline, selector: &str| {
        outline.nodes[outline.resolve(selector).unwrap()].clone()
    };
    assert_eq!(node(&first, "fn[run]#1").line_start, 1);
    assert_eq!(node(&first, "fn[run]#2").line_start, 3);
    assert!(
        source[node(&first, "fn[run]#1").byte_start..].starts_with("fn run() { a() }"),
        "#1 is the first declaration in the file"
    );
    let swapped = outline(
        "src/lib.rs",
        "#[cfg(b)]\nfn run() { b() }\n#[cfg(a)]\nfn run() { a() }\n",
    );
    assert_eq!(
        node(&swapped, "fn[run]#1").structural_hash,
        node(&first, "fn[run]#2").structural_hash,
        "swapping the declarations swaps their ordinals"
    );
    let moved = outline("src/lib.rs", &format!("\n\n\n{source}"));
    assert_eq!(selectors(&moved), ["fn[run]#1", "fn[run]#2"]);
    assert_eq!(node(&moved, "fn[run]#1").line_start, 4);
    assert_eq!(
        node(&moved, "fn[run]#1").structural_hash,
        node(&first, "fn[run]#1").structural_hash,
        "moving the declarations changes neither selector"
    );
}
Input 22: outline src/outline/tests.rs fn[item_macros_are_anonymous_nodes_and_expression_macros_are_not]
// {test}`requirements.references.rust_item_selectors`
// {test}`requirements.references.outlines`
#[test]
fn item_macros_are_anonymous_nodes_and_expression_macros_are_not() {
    let source = "\
thread_local! { static X: u8 = 1; }
println!();
impl<T> Trait for Wrapper<T> {
    m!();
    fn run() { inner!(); let x = vec![1]; }
}
mod local { other! {} }
";
    let outline = outline("src/lib.rs", source);
    let selectors = selectors(&outline);
    let anonymous = regex::Regex::new("^macro@[0-9a-f]{12}$").unwrap();
    assert!(anonymous.is_match(&selectors[0]), "{selectors:?}");
    assert!(anonymous.is_match(&selectors[1]), "{selectors:?}");
    assert_ne!(selectors[0], selectors[1]);
    assert_eq!(selectors[2], "impl[Wrapper<T>/Trait]");
    assert!(
        selectors[3].starts_with("impl[Wrapper<T>/Trait]/macro@"),
        "{selectors:?}"
    );
    assert_eq!(selectors[4], "impl[Wrapper<T>/Trait]/fn[run]");
    assert!(
        selectors[5].starts_with("mod[local]") && selectors[6].starts_with("mod[local]/macro@"),
        "{selectors:?}"
    );
    assert_eq!(
        selectors.len(),
        7,
        "macros inside a function body are expressions, not nodes: {selectors:?}"
    );
}
Input 23: outline src/redaction/tests.rs fn[redaction_never_changes_an_outline]
// {test}`requirements.authoring.redaction`
// {test}`requirements.references.outlines`
#[test]
fn redaction_never_changes_an_outline() {
    let token = github_token();
    let cases = [
        // A YAML plain scalar: its redacted text would parse as a flow sequence.
        ("config.yaml", format!("service:\n  token: {token}\n  retries: 3\n")),
        ("src/lib.rs", format!("const KEY: &str = r\"{}\";\nfn after() {{}}\n", private_key())),
        (
            "habeas.toml",
            "version = 1\n[authoring.configs.local]\nbackend = 'ollama'\nmodel = 'm'\napi_key = '''\nkey\n'''\n".to_owned(),
        ),
        ("notes.md", format!("# Notes\n\nUse `{token}`.\n\n## Next\n\nText.\n")),
        ("notes.txt", format!("{}\nafter\n", private_key())),
    ];
    for (path, source) in cases {
        let redaction = Redaction::of_file(Path::new(path), &source);
        assert!(!redaction.is_empty(), "{path}");
        let original = outline(path, &source, &Redaction::default());
        let redacted = outline(path, &source, &redaction);
        assert_eq!(structure(&original), structure(&redacted), "{path}");
        assert_eq!(
            redaction.apply(&source).lines().count(),
            source.lines().count(),
            "{path}"
        );
    }
    // Parsing the redacted YAML text itself would change the outline.
    let yaml = format!("service:\n  token: {token}\n  retries: 3\n");
    let redacted = Redaction::of_text(&yaml).apply(&yaml).into_owned();
    assert_eq!(
        redacted,
        "service:\n  token: [REDACTED:GitHub Token]\n  retries: 3\n"
    );
    assert_ne!(
        structure(&outline("config.yaml", &yaml, &Redaction::default())),
        structure(&outline("config.yaml", &redacted, &Redaction::default()))
    );
}

Other sources

Input 1: requirements selection requirements.references.outlines
:::{req} outlines
Habeas MUST parse Rust, Python, TypeScript, CSS, Markdown, TOML, and YAML
sources with pinned tree-sitter grammars, selected by file extension compared
case-insensitively. A source with any syntax error MUST fail to parse, reporting
the line of its first error. Every
other text file MUST use a plain-text profile in which each line that is not
blank is an anonymous outline node of kind `line`. Each supported language MUST
have an outline profile that maps grammar node kinds to short outline kind names
and, for each mapped kind, states whether a node is named, and by which fields
or children, or anonymous. Only mapped kinds MUST appear in the outline; other
nodes MUST be transparent, so their outline descendants appear under the
nearest outline ancestor. A profile MAY attach grammar siblings to an outline
node, such as Rust attributes and doc comments preceding an item, so the outline
tree need not match the grammar tree exactly; attached siblings are part of that
node for its line range and hash. Every file's outline MUST have a root node
for the whole file, independent of language. Source in no other outline node,
such as top-level statements no profile maps, MUST belong to the root node;
profiles MUST NOT invent fallback kinds for it. Comments MUST NOT be outline nodes. Profiles MUST be
documented. Upgrading a grammar or profile MAY change outlines and MUST be
treated as a deliberate change.
:::
Input 24: outline src/outline/mod.rs fn[check_errors]
/// Reports the first syntax error in a tree.
fn check_errors(tree: &Tree, lines: &LineIndex) -> Result<(), OutlineError> {
    let root = tree.root_node();
    if !root.has_error() {
        return Ok(());
    }
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if node.is_error() || node.is_missing() {
            return Err(OutlineError {
                line: lines.line(node.start_byte()),
                message: if node.is_missing() {
                    format!("syntax error: missing {}", node.kind())
                } else {
                    "syntax error".to_owned()
                },
            });
        }
        let mut cursor = node.walk();
        let children = node
            .children(&mut cursor)
            .filter(Node::has_error)
            .collect::<Vec<_>>();
        stack.extend(children.into_iter().rev());
    }
    Err(OutlineError {
        line: 1,
        message: "syntax error".to_owned(),
    })
}