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.outline_comments

Requirements index · View definition

evidence Valid

Requirement

Each documented profile defines which grammar nodes are comments; the Markdown profile’s comments are HTML comment blocks, so an inline HTML comment within a paragraph is text of its section. In every supported language, comments on consecutive lines with no other source between them MUST form one comment run. A comment that follows other source on the same line, including another comment, MUST form a run by itself and MUST belong to the innermost outline node containing that line. Any other run MUST belong to the next outline node that starts after it within the smallest node containing it; when that container has no such node, the run MUST belong to the container, which is the root node at top level. A profile MAY bind a comment kind to its container instead: such a run MUST belong to the smallest node containing it. The Rust profile MUST bind inner doc comments (//!, /*!) to their container, so a file-level inner doc comment belongs to the root node. A reference in a comment MUST count for the node its run belongs to under cite requirements.references.rust_item_coverage and cite requirements.references.authoring_inputs.

Rationale

The reviewed tests cover each obligation in requirements.references.outline_comments. I read the supplied test sources only. I did not request implementation source, because I found no specific question that needed it.

Obligations and the tests that check them

  • Profiles define comments, and Markdown comments are HTML comment blocks.
    • src/outline/tests.rs#fn[markdown_comments_are_html_comment_blocks_not_inline_comments] asserts that only the block comment is recorded.
    • It also asserts that an inline <!-- --> is paragraph text of section[H].
    • comment_runs_follow_the_same_rules_in_every_language runs the Markdown, Python, TS, TSX, CSS, TOML and YAML profiles through the same ownership rules.
  • Comments on consecutive lines form one run.
    • comment_between_two_fns_belongs_to_the_next checks that both // one and // two go to fn[b].
    • The Python case in comment_runs_follow_the_same_rules_in_every_language does the same for “lead one” and “lead two”.
    • src/fenced.rs#mod[tests]/fn[comment_fences_close_within_one_comment_run] checks that a blank line ends a run. A later run’s ::: does not close an earlier fence.
  • A trailing comment is its own run and belongs to the innermost node containing its line.
    • comment_after_code_on_a_line_belongs_to_that_lines_node covers fn a() {} // after a, a trailing comment inside fn b and one after its closing brace. It also covers a trailing comment after the closing brace of mod m.
    • comment_runs_belong_to_the_next_node_or_their_container shows that a trailing comment does not merge with the following // before third. That comment goes to fn[third].
    • a_comment_after_another_comment_on_its_line_forms_its_own_run covers the “including another comment” case. The second comment goes to the root, and the first goes to fn[b].
  • Any other run belongs to the next node starting after it within the smallest container.
    • The Rust, Python, TS, CSS, TOML, YAML and Markdown cases all test this.
    • yaml_comments_before_a_key_belong_to_that_key_not_the_previous_one and workflow_job_marks_belong_to_the_job_that_follows test it for YAML.
  • With no following node, the run belongs to the container, or to the root at top level.
    • trailing_comment_after_last_fn_in_mod_belongs_to_the_mod and top_level_comment_with_nothing_after_belongs_to_the_root cover the container and root cases.
    • The “after b” and “tail” cases in the multi-language test cover the same rules in other languages.
    • comment_runs_belong_to_the_next_node_or_their_container covers “alone in m”, “final” and “floating”.
  • The Rust profile binds inner doc comments to their container.
    • file_level_inner_doc_comments_and_unmapped_code_belong_to_the_root tests both //! and /*! at file level. They belong to the root even when a function follows directly.
    • comment_runs_belong_to_the_next_node_or_their_container shows “Module docs” belonging to mod[m], although fn inner follows.
  • A reference in a comment counts for the node its run belongs to.
    • src/rust_coverage.rs#mod[tests]/fn[finds_uncited_functions_without_using_enclosing_or_string_references] checks coverage ownership. It covers a run across a blank line, a trailing comment that does not cover the next item, and an inner doc comment that does not cover the following function.
    • src/authoring/inputs.rs#mod[tests]/fn[references_contribute_their_owning_outline_nodes] checks the contribution to mandatory inputs.
    • comment_fences_close_within_one_comment_run checks the owners of fenced references.
    • The tools and src/structural.rs tests show that comment matches are attributed to the comment’s owner.

The assertions compare against the expected owner selectors and are not just executed. I found no obligation without a test.

Inputs

Tests

Input 4: outline src/authoring/inputs.rs mod[tests]/fn[references_contribute_their_owning_outline_nodes]
    // {test}`requirements.references.authoring_inputs`
    // {test}`requirements.references.outline_comments`
    // {test}`requirements.references.anchors`
    // {test}`requirements.authoring.mandatory_inputs`
    // {test}`requirements.authoring.fixme_inputs`
    // {test}`requirements.references.roles`
    #[test]
    fn references_contribute_their_owning_outline_nodes() {
        let root = project();
        fs::create_dir_all(root.path().join("docs")).unwrap();
        fs::write(
            root.path().join("md/requirements.md"),
            ":::{req} ready\n:impl: src/lib.rs#mod[inner]\nThe project MUST be ready.\n:::\n",
        )
        .unwrap();
        // A `{fixme}` contributes metadata for the node its comment belongs to;
        // an unnamed one is not an acknowledgment edge.
        fs::write(
            root.path().join("src/lib.rs"),
            "mod inner {\n    fn unrelated() {}\n}\n\n// :::{fixme} requirements.ready\n// The gap.\n// :::\nfn gap() {}\n\n// :::{fixme}\n// :github: example/app#1\n// :::\nfn tracked() {}\n",
        )
        .unwrap();
        fs::write(
            root.path().join("docs/guide.md"),
            format!(
                "# Intro\n\nText.\n\n# Usage\n\nSee {}.\n",
                role("test", "requirements.ready")
            ),
        )
        .unwrap();
        fs::write(
            root.path().join("notes.txt"),
            format!("first\n{}\n", role("test", "requirements.ready")),
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let items = sources
            .mandatory_inputs()
            .iter()
            .filter(|input| input.get("item").is_some())
            .map(|input| {
                (
                    input["file"].as_str().unwrap(),
                    input["item"].as_str().unwrap(),
                )
            })
            .collect::<Vec<_>>();
        assert_eq!(
            items,
            [
                ("docs/guide.md", "section[Usage]"),
                // A plain-text file contributes the complete file.
                ("notes.txt", ""),
            ]
        );
        let acknowledgments = sources.model_acknowledgments();
        assert_eq!(acknowledgments.len(), 1, "{acknowledgments:#?}");
        assert_eq!(acknowledgments[0]["file"], "src/lib.rs");
        assert_eq!(acknowledgments[0]["item"], "fn[gap]");
        assert_eq!(acknowledgments[0]["body"], "The gap.");
    }
Input 5: outline src/authoring/tools.rs mod[tests]/fn[search_returns_innermost_nodes_and_comment_owners]
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.references.outline_comments`
    #[test]
    fn search_returns_innermost_nodes_and_comment_owners() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn outer() {\n    fn inner() {\n        needle();\n    }\n}\n\n// needle in a comment\nfn after() {}\n",
        )
        .unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let search = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"needle","path":"src/lib.rs","context":0}),
        )
        .unwrap();
        let items = matched(&search)
            .iter()
            .map(|input| input["item"].as_str().unwrap())
            .collect::<Vec<_>>();
        assert_eq!(items, ["fn[outer]/fn[inner]", "fn[after]"]);
        // A comment match belongs to its owner, and shows the matching line.
        assert_eq!(
            matched(&search)[1],
            json!({"file": "src/lib.rs", "item": "fn[after]", "kind": "fn", "tag":"2",
                "lines": [{"text": "// needle in a comment", "matched": true}]})
        );
        assert_eq!(
            matched(&search)[0]["lines"],
            json!([{"text": "        needle();", "matched": true}])
        );
        // Entries carry no hash: they are not evidence inputs.
        assert!(matched(&search)[0].get("hash").is_none());
    }
Input 6: outline src/authoring/tools.rs mod[tests]/fn[ast_grep_returns_innermost_nodes_of_the_language_and_reports_failures]
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.references.outline_comments`
    // {test}`requirements.authoring.redaction`
    // {test}`requirements.authoring.read_denial`
    #[test]
    fn ast_grep_returns_innermost_nodes_of_the_language_and_reports_failures() {
        let root = project();
        fs::write(
            root.path().join("md/terms.md"),
            ":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
        )
        .unwrap();
        let token = ["gh", "p_", "abcdefghijklmnopqrstuvwxyz0123456789"].concat();
        fs::write(
            root.path().join("src/lib.rs"),
            format!(
                "// {}\nfn first() {{\n    let x = value.unwrap();\n}}\n\n/// Calls unwrap in docs.\nfn second() {{\n    other(\"{token}\").unwrap();\n}}\n\nmod inner {{\n    fn third() {{\n        a.unwrap();\n        b.unwrap();\n    }}\n}}\n",
                role("term", "terms.value")
            ),
        )
        .unwrap();
        fs::write(
            root.path().join("src/a.rs"),
            "fn a() {\n    z.unwrap();\n}\n",
        )
        .unwrap();
        fs::write(root.path().join("src/tool.py"), "value.unwrap()\n").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        let rust = |rule: Value, path: &str| {
            dispatch(
                &sources,
                "ast_grep",
                &json!({"language":"rust","rule":rule,"path":path}),
            )
        };
        let search = rust(json!({"rule":{"pattern":"$X.unwrap()"}}), ".").unwrap();
        // Only Rust files are searched, ordered by path and then line, and
        // each node once.
        assert_eq!(
            found(&search),
            [
                "src/a.rs#fn[a]",
                "src/lib.rs#fn[first]",
                "src/lib.rs#fn[second]",
                "src/lib.rs#mod[inner]/fn[third]"
            ]
        );
        // Each entry shows the matched lines, redacted; no terminology is
        // supplied.
        let second = &matched(&search)[2]["lines"];
        assert_eq!(second[0]["matched"], true);
        assert!(second.to_string().contains("[REDACTED:"), "{second}");
        assert!(!second.to_string().contains(&token), "{second}");
        assert_eq!(
            matched(&search)[3]["lines"],
            json!([
                {"text": "        a.unwrap();", "matched": true},
                {"text": "        b.unwrap();", "matched": true},
            ])
        );
        assert!(search.result.get("definitions").is_none());
        // A match in a comment belongs to the comment's owner; utils and
        // constraints are accepted.
        let comment = rust(
            json!({
                "rule": {"matches": "doc"},
                "utils": {"doc": {"kind": "line_comment", "regex": "unwrap"}}
            }),
            "src/lib.rs",
        )
        .unwrap();
        assert_eq!(found(&comment), ["src/lib.rs#fn[second]"]);
        let constrained = rust(
            json!({
                "rule": {"pattern": "$X.unwrap()"},
                "constraints": {"X": {"regex": "^[ab]$"}}
            }),
            "src",
        )
        .unwrap();
        assert_eq!(found(&constrained), ["src/lib.rs#mod[inner]/fn[third]"]);
        let python = dispatch(
            &sources,
            "ast_grep",
            &json!({"language":"python","rule":{"rule":{"pattern":"$X.unwrap()"}}}),
        )
        .unwrap();
        assert_eq!(found(&python), ["src/tool.py#"]);
        let none = rust(json!({"rule":{"pattern":"missing()"}}), ".").unwrap();
        assert_eq!(none.result["matches"], json!([]));
        assert!(none.inputs.is_empty());
        for (arguments, message) in [
            (
                json!({"language":"cobol","rule":{"rule":{"kind":"x"}}}),
                "unknown structural search language",
            ),
            (
                json!({"rule":{"rule":{"kind":"x"}}}),
                "language must be a string",
            ),
            (
                json!({"language":"rust","rule":"x"}),
                "rule must be an object",
            ),
            (
                json!({"language":"rust","rule":{"rule":{"kind":"no_such_kind"}}}),
                "invalid ast-grep rule",
            ),
            (
                json!({"language":"rust","rule":{"pattern":"x"}}),
                "unexpected key \"pattern\"",
            ),
            (
                json!({"language":"rust","rule":{"rule":{"kind":"x"}},"extra":1}),
                "unexpected tool argument \"extra\"",
            ),
            (
                json!({"query":"x","language":"rust"}),
                "unexpected tool argument \"language\"",
            ),
            (
                json!({"query":"x"}),
                "must have the form <full-name>/<query-name>",
            ),
            (
                json!({"query":"requirements.none/sites"}),
                "names no declared requirement",
            ),
            (
                json!({"query":"requirements.ready/sites"}),
                "declares no query named \"sites\"",
            ),
        ] {
            let error = dispatch(&sources, "ast_grep", &arguments).err().unwrap();
            assert!(error.to_string().contains(message), "{arguments}: {error}");
        }
        // A matched file that cannot be parsed fails the search.
        fs::write(
            root.path().join("src/broken.rs"),
            "fn broken() {\n    q.unwrap();\n}\n}\n",
        )
        .unwrap();
        let error = rust(json!({"rule":{"pattern":"$X.unwrap()"}}), "src")
            .err()
            .unwrap();
        assert!(error.to_string().contains("syntax error"), "{error}");
        assert!(sources.recorded_inputs().is_empty());
    }
Input 7: outline src/evidence.rs mod[tests]/fn[reference_set_digest_tracks_impl_and_test_edges_by_node]
  • File: src/evidence.rs
  • Selector: mod[tests]/fn[reference_set_digest_tracks_impl_and_test_edges_by_node]
  • Kind: fn
  • src/evidence.rs:3980–4107
    // {test}`requirements.ci.reference_set`
    // {test}`requirements.references.outline_comments`
    #[test]
    fn reference_set_digest_tracks_impl_and_test_edges_by_node() {
        let temp = fixture();
        let root = temp.path();
        let role = |kind: &str| format!("{{{kind}}}`requirements.ready`");
        let declaration = |options: &str| {
            format!(
                ":::{{req}} ready\n{options}Ready MUST hold.\n:::\n\n:::{{req}} other\nOther MUST hold.\n:::\n"
            )
        };
        fs::write(root.join("md/requirements.md"), declaration("")).unwrap();
        let digest = |lib: &str, notes: &str, guide: &str| {
            fs::write(root.join("src/lib.rs"), lib).unwrap();
            fs::write(root.join("notes.txt"), notes).unwrap();
            fs::write(root.join("md/guide.md"), guide).unwrap();
            super::reference_set_digest_for(root, "requirements.ready").unwrap()
        };
        let lib = format!(
            "// {}\nfn run() {{\n    work();\n}}\n\nfn other() {{}}\n",
            role("impl")
        );
        let notes = format!("{}\n", role("test"));
        let guide = format!("# Guide\n\nIntro.\n\n## Usage\n\nSee {}.\n", role("impl"));
        let base = digest(&lib, &notes, &guide);
        assert_eq!(base.len(), 64);
        assert!(super::is_sha256_hex(&base));
        assert_eq!(
            digest(&lib, &notes, &guide),
            base,
            "the digest is deterministic"
        );

        // Line moves within the reference's node, unrelated lines, and
        // `{cite}` references leave the digest unchanged.
        for (lib, notes, guide) in [
            (
                format!("// unrelated\n\n{lib}"),
                notes.clone(),
                guide.clone(),
            ),
            (
                format!(
                    "fn run() {{\n    // {}\n    work();\n}}\n\nfn other() {{}}\n",
                    role("impl")
                ),
                notes.clone(),
                guide.clone(),
            ),
            (
                lib.clone(),
                format!("first\n\nsecond\n{notes}"),
                guide.clone(),
            ),
            (
                lib.clone(),
                notes.clone(),
                guide.replace("See ", "Intro line.\n\nSee "),
            ),
            (
                format!("{lib}// {}\nfn cited() {{}}\n", role("cite")),
                format!("{notes}{}\n", role("cite")),
                guide.clone(),
            ),
        ] {
            assert_eq!(
                digest(&lib, &notes, &guide),
                base,
                "{lib}\n{notes}\n{guide}"
            );
        }

        // Adding, removing, re-roling, or moving a reference to another node
        // changes it.
        let mut seen = std::collections::BTreeSet::from([base.clone()]);
        for (lib, notes, guide) in [
            (
                format!("{lib}// {}\nfn more() {{}}\n", role("impl")),
                notes.clone(),
                guide.clone(),
            ),
            (
                format!(
                    "fn run() {{\n    // {}\n    // {}\n    work();\n}}\n\nfn other() {{}}\n",
                    role("impl"),
                    role("impl")
                ),
                notes.clone(),
                guide.clone(),
            ),
            (
                lib.replace(&role("impl"), "removed"),
                notes.clone(),
                guide.clone(),
            ),
            (lib.replace("impl", "test"), notes.clone(), guide.clone()),
            (
                format!(
                    "fn run() {{\n    work();\n}}\n\n// {}\nfn other() {{}}\n",
                    role("impl")
                ),
                notes.clone(),
                guide.clone(),
            ),
            (lib.clone(), String::new(), guide.clone()),
            (
                lib.clone(),
                notes.clone(),
                guide.replace("Intro.", &format!("Intro {}.", role("impl"))),
            ),
        ] {
            let changed = digest(&lib, &notes, &guide);
            assert!(seen.insert(changed), "{lib}\n{notes}\n{guide}");
        }

        // Adding an anchor changes it, as does changing the anchored node.
        digest(&lib, &notes, &guide);
        for options in [
            ":impl: notes.txt\n",
            ":test: notes.txt\n",
            ":impl: src/lib.rs#fn[run]\n",
        ] {
            fs::write(root.join("md/requirements.md"), declaration(options)).unwrap();
            let changed = super::reference_set_digest_for(root, "requirements.ready").unwrap();
            assert!(seen.insert(changed), "{options}");
        }
    }
Input 8: outline src/fenced.rs mod[tests]/fn[comment_fences_close_within_one_comment_run]
  • File: src/fenced.rs
  • Selector: mod[tests]/fn[comment_fences_close_within_one_comment_run]
  • Kind: fn
  • src/fenced.rs:393–410
    // {test}`requirements.references.roles`
    // {test}`requirements.references.outline_comments`
    #[test]
    fn comment_fences_close_within_one_comment_run() {
        let source = "// :::{cite} habeas:util\n// Exists for its caller.\n// :::\nfn a() {}\n\n// :::{cite} habeas:util\n// never closed here\n\n// :::\nfn b() {}\n/*\n * :::{impl} requirements.ready\n * Checks it.\n * :::\n */\nfn c() {}\n".to_owned();
        let outline = crate::outline::parse(std::path::Path::new("lib.rs"), &source).unwrap();
        let fences = comment_fences(&source, &outline);
        assert_eq!(fences.len(), 3, "{fences:?}");
        assert_eq!(fences[0].body, "Exists for its caller.");
        assert!(fences[0].closed);
        assert_eq!(fences[0].line, 1);
        assert_eq!(outline.nodes[fences[0].owner.unwrap()].selector, "fn[a]");
        assert!(!fences[1].closed, "a later run's fence does not close it");
        assert_eq!(fences[1].line, 6);
        assert_eq!(fences[2].kind, ReferenceKind::Impl);
        assert_eq!(fences[2].body, "Checks it.");
        assert_eq!(outline.nodes[fences[2].owner.unwrap()].selector, "fn[c]");
    }
Input 9: outline src/outline/tests.rs fn[comment_runs_belong_to_the_next_node_or_their_container]
// {test}`requirements.references.outline_comments`
#[test]
fn comment_runs_belong_to_the_next_node_or_their_container() {
    let source = "\
//! Crate docs.
fn first() {}
// between first and second
fn second() {} // trailing second
// before third

fn third() {
    // inside third
}

// floating

mod m {
    //! Module docs.
    // above inner
    fn inner() {}

    // alone in m
}
// final
";
    let outline = outline("src/lib.rs", source);
    let owner = |needle: &str| comment_owner(&outline, source, needle);
    assert_eq!(owner("Crate docs"), "");
    assert_eq!(owner("between first"), "fn[second]");
    assert_eq!(owner("trailing second"), "fn[second]");
    assert_eq!(owner("before third"), "fn[third]");
    assert_eq!(owner("inside third"), "fn[third]");
    assert_eq!(owner("floating"), "mod[m]");
    assert_eq!(owner("Module docs"), "mod[m]");
    assert_eq!(owner("above inner"), "mod[m]/fn[inner]");
    assert_eq!(owner("alone in m"), "mod[m]");
    assert_eq!(owner("final"), "");
    let second = &outline.nodes[outline.resolve("fn[second]").unwrap()];
    assert_eq!((second.line_start, second.line_end), (3, 4));
    let third = &outline.nodes[outline.resolve("fn[third]").unwrap()];
    assert_eq!((third.line_start, third.line_end), (5, 9));
    assert_eq!(
        outline
            .innermost_at_line(3)
            .into_iter()
            .map(|index| outline.nodes[index].selector.clone())
            .collect::<Vec<_>>(),
        ["fn[second]"]
    );
}
Input 10: outline src/outline/tests.rs fn[comment_between_two_fns_belongs_to_the_next]
// {test}`requirements.references.outline_comments`
#[test]
fn comment_between_two_fns_belongs_to_the_next() {
    let source = "fn a() {}\n// one\n// two\nfn b() {}\n";
    let outline = outline("src/lib.rs", source);
    assert_eq!(comment_owner(&outline, source, "one"), "fn[b]");
    assert_eq!(comment_owner(&outline, source, "two"), "fn[b]");
}
Input 11: outline src/outline/tests.rs fn[trailing_comment_after_last_fn_in_mod_belongs_to_the_mod]
// {test}`requirements.references.outline_comments`
#[test]
fn trailing_comment_after_last_fn_in_mod_belongs_to_the_mod() {
    let source = "mod m {\n    fn a() {}\n    // tail\n}\nfn b() {}\n";
    let outline = outline("src/lib.rs", source);
    assert_eq!(comment_owner(&outline, source, "tail"), "mod[m]");
}
Input 12: outline src/outline/tests.rs fn[top_level_comment_with_nothing_after_belongs_to_the_root]
// {test}`requirements.references.outline_comments`
#[test]
fn top_level_comment_with_nothing_after_belongs_to_the_root() {
    let source = "fn a() {}\n// tail\n";
    let outline = outline("src/lib.rs", source);
    assert_eq!(comment_owner(&outline, source, "tail"), "");
    let a = &outline.nodes[outline.resolve("fn[a]").unwrap()];
    assert_eq!((a.line_start, a.line_end), (1, 1));
}
Input 13: outline src/outline/tests.rs fn[comment_after_code_on_a_line_belongs_to_that_lines_node]
// {test}`requirements.references.outline_comments`
#[test]
fn comment_after_code_on_a_line_belongs_to_that_lines_node() {
    let source = "\
mod m {
    fn a() {} // after a
    // before b
    fn b() {
        let x = 1; // inside b
    } // closing b
} // closing m
fn c() {}
";
    let outline = outline("src/lib.rs", source);
    let owner = |needle: &str| comment_owner(&outline, source, needle);
    assert_eq!(owner("after a"), "mod[m]/fn[a]");
    assert_eq!(owner("before b"), "mod[m]/fn[b]");
    assert_eq!(owner("inside b"), "mod[m]/fn[b]");
    assert_eq!(owner("closing b"), "mod[m]/fn[b]");
    assert_eq!(owner("closing m"), "mod[m]");
}
Input 14: 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 15: outline src/outline/tests.rs fn[comment_runs_follow_the_same_rules_in_every_language]
// {test}`requirements.references.outline_comments`
#[test]
fn comment_runs_follow_the_same_rules_in_every_language() {
    // Each case: path, source, and (needle, expected owner selector) pairs.
    // Every language has a run before a node, a trailing comment, a comment
    // after its container's last node, and a top-level tail comment that
    // belongs to the root.
    type Case = (
        &'static str,
        &'static str,
        &'static [(&'static str, &'static str)],
    );
    let cases: &[Case] = &[
        (
            "a.py",
            "# lead one\n# lead two\ndef f():\n    pass  # trailing f\nclass C:\n    def m(self):\n        pass\n    # before n\n    def n(self):\n        pass\n# tail\n",
            &[
                ("lead one", "def[f]"),
                ("lead two", "def[f]"),
                ("trailing f", "def[f]"),
                ("before n", "class[C]/def[n]"),
                ("tail", ""),
            ],
        ),
        (
            "a.ts",
            "// lead\nfunction f() {} // trailing f\nclass C {\n  m() {}\n  // after m\n}\n/* tail */\n",
            &[
                ("lead", "function[f]"),
                ("trailing f", "function[f]"),
                ("after m", "class[C]"),
                ("tail", ""),
            ],
        ),
        (
            "a.tsx",
            "// lead\nfunction App() { return <div/>; } // trailing\n// tail\n",
            &[
                ("lead", "function[App]"),
                ("trailing", "function[App]"),
                ("tail", ""),
            ],
        ),
        (
            "a.css",
            "/* lead */\na { color: red; } /* trailing a */\n@media print {\n  b { x: y }\n  /* after b */\n}\n/* tail */\n",
            &[
                ("lead", "rule[a]"),
                ("trailing a", "rule[a]"),
                ("after b", "media[print]"),
                ("tail", ""),
            ],
        ),
        (
            "a.toml",
            "# lead\na = 1 # trailing a\n[t]\nb = 2\n# after b\n",
            &[
                ("lead", "pair[a]"),
                ("trailing a", "pair[a]"),
                ("after b", "table[t]"),
            ],
        ),
        (
            "a.yml",
            "# lead\na: 1 # trailing a\n# before b\nb:\n  c: 1\n  # inner\n  d: 2\n",
            &[
                ("lead", "pair[a]"),
                ("trailing a", "pair[a]"),
                ("before b", "pair[b]"),
                ("inner", "pair[b]/pair[d]"),
            ],
        ),
        (
            "a.md",
            "# H\npara\n<!-- before Sub -->\n## Sub\ntext\n\n<!-- end of Sub -->\n",
            &[
                ("before Sub", "section[H]/section[Sub]"),
                ("end of Sub", "section[H]/section[Sub]"),
            ],
        ),
    ];
    for (path, source, expected) in cases {
        let outline = outline(path, source);
        for (needle, owner) in *expected {
            assert_eq!(
                comment_owner(&outline, source, needle),
                *owner,
                "{path}: owner of {needle:?}"
            );
        }
    }
}
Input 16: outline src/outline/tests.rs fn[markdown_comments_are_html_comment_blocks_not_inline_comments]
// {test}`requirements.references.outline_comments`
#[test]
fn markdown_comments_are_html_comment_blocks_not_inline_comments() {
    let source = "# H\nText <!-- inline --> more.\n\n<!-- block -->\n## Sub\n";
    let outline = outline("a.md", source);
    assert_eq!(outline.comments.len(), 1, "only the block is a comment");
    assert_eq!(
        comment_owner(&outline, source, "block"),
        "section[H]/section[Sub]"
    );
    let inline = source.find("inline").unwrap();
    assert!(
        outline
            .comments
            .iter()
            .all(|comment| !(comment.byte_start <= inline && inline < comment.byte_end))
    );
    assert_eq!(
        outline.nodes[outline.owner_at_line(2)].selector,
        "section[H]",
        "an inline HTML comment is paragraph text of its section"
    );
}
Input 17: outline src/outline/tests.rs fn[a_comment_after_another_comment_on_its_line_forms_its_own_run]
// {test}`requirements.references.outline_comments`
#[test]
fn a_comment_after_another_comment_on_its_line_forms_its_own_run() {
    let source = "fn a() {}\n/* first */ /* second */\nfn b() {}\n";
    let outline = outline("src/lib.rs", source);
    assert_eq!(comment_owner(&outline, source, "first"), "fn[b]");
    // The second comment follows other text on its line, so it forms a run
    // by itself and belongs to the innermost node containing that line; no
    // item contains line 2, so that is the root.
    assert_eq!(comment_owner(&outline, source, "second"), "");
}
Input 18: outline src/outline/tests.rs fn[yaml_comments_before_a_key_belong_to_that_key_not_the_previous_one]
// {test}`requirements.references.outline_comments`
#[test]
fn yaml_comments_before_a_key_belong_to_that_key_not_the_previous_one() {
    let source = "jobs:\n  first:\n    steps:\n      - run: a\n  # note for second\n  second:\n    steps:\n      - run: b\n";
    let outline = parse(std::path::Path::new("ci.yml"), source).unwrap();
    let owners = outline.comment_owners_at_line(5);
    assert_eq!(owners.len(), 1, "{owners:?}");
    assert_eq!(outline.nodes[owners[0]].selector, "pair[jobs]/pair[second]");
}
Input 19: outline src/outline/tests.rs fn[workflow_job_marks_belong_to_the_job_that_follows]
// {test}`requirements.references.outline_comments`
#[test]
fn workflow_job_marks_belong_to_the_job_that_follows() {
    for path in [
        ".github/workflows/ci.yml",
        ".github/workflows/release-plz.yml",
    ] {
        let file = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(path);
        let source = std::fs::read_to_string(&file).unwrap();
        let outline = parse(&file, &source).unwrap();
        for (index, line) in source.lines().enumerate() {
            let Some(job) = source.lines().nth(index + 1) else {
                continue;
            };
            if line.trim_start().starts_with("# {")
                && line.starts_with("  #")
                && job.starts_with("  ")
                && job.trim_end().ends_with(':')
            {
                let owners = outline.comment_owners_at_line(index + 1);
                let name = job.trim().trim_end_matches(':');
                assert_eq!(owners.len(), 1, "{path}:{}", index + 1);
                assert_eq!(
                    outline.nodes[owners[0]].selector,
                    format!("pair[jobs]/pair[{name}]"),
                    "{path}:{}",
                    index + 1
                );
            }
        }
    }
}
Input 20: outline src/rust_coverage.rs mod[tests]/fn[finds_uncited_functions_without_using_enclosing_or_string_references]
  • File: src/rust_coverage.rs
  • Selector: mod[tests]/fn[finds_uncited_functions_without_using_enclosing_or_string_references]
  • Kind: fn
  • src/rust_coverage.rs:848–913
    // {test}`requirements.references.rust_item_coverage`
    // {test}`requirements.references.outline_comments`
    #[test]
    fn finds_uncited_functions_without_using_enclosing_or_string_references() {
        let source = r##"
// {impl}`requirements.example`
mod feature {
    // {impl}`requirements.example`
    impl Widget {
        fn missing_method() {}
    }

    struct Widget;
    impl Widget {
        // {impl}`requirements.example`
        fn cited_method() {}
    }

    fn containing_string() {
        let _ = "// {impl}`requirements.example`";
        let _ = r#"/* {impl}`requirements.example` */"#;
        let _ = '/';
    }

    fn unknown_reference() {
        // {impl}`requirements.unknown`
    }

    fn body_reference() {
        /* {impl}`requirements.example` */
    }

    // A comment run belongs to the next item even across a blank line.
    // {impl}`requirements.example`

    fn after_blank_line() {}

    // {impl}`requirements.example`
    fn previous() {} // {impl}`requirements.example`
    fn after_trailing_comment() {}
}

mod inner_docs {
    //! {impl}`requirements.example`
    fn after_inner_doc() {}
}

/// {impl}`requirements.example`
fn cited_by_outer_doc() {}
"##;
        let missing = missing_function_references(source, &definitions()).unwrap();
        assert_eq!(
            missing
                .into_iter()
                .map(|(_, _, name)| name)
                .collect::<Vec<_>>(),
            [
                "missing_method",
                "Widget",
                "containing_string",
                "unknown_reference",
                "after_trailing_comment",
                "after_inner_doc"
            ]
        );
    }
Input 21: outline src/structural.rs mod[tests]/fn[matches_belong_to_the_innermost_node_or_comment_owner]
  • File: src/structural.rs
  • Selector: mod[tests]/fn[matches_belong_to_the_innermost_node_or_comment_owner]
  • Kind: fn
  • src/structural.rs:756–773
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.references.distributed`
    // {test}`requirements.references.outline_comments`
    #[test]
    fn matches_belong_to_the_innermost_node_or_comment_owner() {
        let source = "mod outer {\n    /// Uses foo.\n    #[inline]\n    fn inner() {\n        foo(1);\n    }\n}\n";
        let outline = crate::outline::parse(Path::new("lib.rs"), source).unwrap();
        let item = |text: &str| {
            let start = source.find(text).unwrap();
            let index = innermost_node(&outline, source, &(start..start + text.len()));
            outline.nodes[index].selector.clone()
        };
        assert_eq!(item("foo(1)"), "mod[outer]/fn[inner]");
        assert_eq!(item("/// Uses foo.\n"), "mod[outer]/fn[inner]");
        assert_eq!(item("#[inline]"), "mod[outer]/fn[inner]");
        assert_eq!(item("mod outer"), "mod[outer]");
        assert_eq!(item(source), "");
    }

Referenced definitions

Input 2: requirements selection requirements.references.rust_item_coverage
:::{req} rust_item_coverage
During repository validation, Habeas MUST parse every first-party Rust source file: every `.rs` file among the sources reference discovery considers under {cite}`requirements.references.discovery`, except those under the project-root `vendor` directory. Each explicitly declared function or method, including trait methods and test helpers, and each struct, enum, and union is an item that can be covered. An item is covered when it has a valid `{impl}`, `{cite}`, or `{test}` reference to a defined requirement or named example, or a valid citation of the built-in `habeas:util` under {cite}`requirements.references.util`, in a Rust comment attached to it or within its body; or when its outline node, or an outline node containing it, is recorded with its current hash as an outline input of an evidence record, a citation review, or a site review. Outline inputs recorded from selected search snippets under {cite}`requirements.authoring.finish_search.inputs` MUST count alongside mandatory inputs and additional reads. Comments belong to items under {cite}`requirements.references.outline_comments`; a comment before a field, variant, or attribute inside an item belongs to that item. A named example MUST reference a requirement under {cite}`requirements.examples.definition`. A reference in a string literal, on an enclosing module or impl block, or only in an evidence input MUST NOT count for the items it encloses. Habeas MUST report a Rust parse failure instead of silently skipping the file. Only {cite}`requirements.references.coverage.tests` and {cite}`requirements.references.coverage.examples` make an uncovered item a validation error; other items without recent coverage are warned about under {cite}`requirements.references.coverage.report`.
:::
Input 3: requirements selection requirements.references.authoring_inputs
:::{req} authoring_inputs
When authoring evidence, the edges defined by
{cite}`requirements.references.roles` MUST determine the reference
contributions to the mandatory input set defined by
{cite}`requirements.authoring.mandatory_inputs`. A `{cite}` made by the subject
MUST contribute the cited definition's complete fenced declaration. A requirement
or example declaration that references the subject with `{impl}` or `{test}`
MUST contribute that complete declaration. For sources outside such declarations,
an `{impl}` reference or `:impl:` anchor alone MUST NOT contribute source text;
those sources MUST remain discoverable under
{cite}`requirements.authoring.reference_index` and MAY be requested under
{cite}`requirements.authoring.source_tools`. Sources with only edges into the subject
MUST NOT contribute and remain discoverable under
{cite}`requirements.authoring.reference_index`. A `:test:` anchor under
{cite}`requirements.references.anchors` MUST contribute the complete anchored file,
or for a `path#selector` anchor the anchored node.
An in-source `{test}` reference to the subject MUST contribute the source
containing it: for a reference in a supported language, the smallest enclosing
outline node under {cite}`requirements.references.outline_comments`; for a reference in a Markdown requirement, example, or
terminology declaration, that complete declaration; for other references, the
complete containing source file. Literal references, evidence copies, and
generated output MUST remain excluded under the existing reference-discovery
rules.

An in-source `{fixme}` reference alone MUST NOT contribute the containing source
to the mandatory input set. Its acknowledgment MUST instead be supplied under
{cite}`requirements.authoring.fixme_inputs`.

These contribution rules MUST apply only to the assessed subject's direct
references. Including another declaration or source MUST NOT by itself recursively
expand that source's own edges. Reference links MUST NOT be described as proof
that all substantively relevant sources have been found.
:::

Other sources

Input 1: requirements selection requirements.references.outline_comments
:::{req} outline_comments
Each documented profile defines which grammar nodes are comments; the Markdown
profile's comments are HTML comment blocks, so an inline HTML comment within a
paragraph is text of its section. In every supported language, comments on consecutive lines with no other source
between them MUST form one comment run. A comment that follows other source on
the same line, including another comment, MUST form a run by itself and MUST belong to the innermost outline node
containing that line. Any other run MUST belong to the next outline node that
starts after it within the smallest node containing it; when that container has
no such node, the run MUST belong to the container, which is the root node at top
level. A profile MAY bind a comment kind to its container
instead: such a run MUST belong to the smallest node containing it. The Rust
profile MUST bind inner doc comments (`//!`, `/*!`) to their container, so a
file-level inner doc comment belongs to the root node. A reference in a comment MUST count for the node its run belongs to under
{cite}`requirements.references.rust_item_coverage` and
{cite}`requirements.references.authoring_inputs`.
:::