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.authoring.search_accounting.excerpts

Requirements index · View definition

evidence Valid

Requirement

Every ripgrep or ast_grep excerpt, including matching and context text, MUST be clipped to the source span of the outline item identified by their file and item, including that item’s attached source under cite requirements.references.outline_comments. Clipping MUST apply within a line shared by different items.

Rationale

The two marked tests in src/authoring/tools.rs cover each clause of requirements.authoring.search_accounting.excerpts. I found no gap.

Obligations derived from the text

  1. Both ripgrep and ast_grep excerpts, matching and context text alike, are clipped to the span of the item named by file and item.
  2. That span includes the item’s attached comments and attributes, per requirements.references.outline_comments.
  3. Clipping applies inside a line that different items share.

Coverage in mod[tests]/fn[search_excerpts_stop_at_byte_boundaries_including_attached_comments_and_attributes]

  • The source file has fn before, a doc comment and #[inline] attached to fn target, fn after, and a shared line holding fn left, a trailing block comment, #[inline] fn right and fn last.
  • It runs both tools: ripgrep with context 99, and ast_grep with a rule that matches needle() or a block comment containing “needle”.
  • Each tool must return exactly three matches, with items fn[target], fn[left] and fn[right], in that order.
  • Neighbouring items’ content never leaks into any excerpt. The assertions rule out unwanted_before, unwanted_after, unwanted_last and fn last in the whole result. They also rule out fn right in left’s excerpt and fn left in right’s excerpt. Context of 99 lines for ripgrep would pull in neighbours if clipping failed.
  • Attached source is included. For ripgrep the fn[target] excerpt must contain “needle docs” and #[inline]. For both tools, fn[left] must contain “needle attached” and fn[right] must contain “#[inline] fn right”.
  • The comment that follows code on the same line is attributed to fn[left] and kept out of fn[right].
  • Clipping on a shared line is tested for both tools.
  • Multi-byte “café” in fn target exercises byte-boundary slicing, and the redaction marker is checked.
  • Two more ripgrep runs with context 0 check match attribution. One searches café and must return only fn[target]. The other searches inline and must return the fn[target] and fn[right] items, which are the two attribute owners.

Coverage in mod[tests]/fn[exact_match_ranges_preserve_regex_anchors_and_skip_unmatched_or_binary_sources]

  • With context 10, anchored and case-insensitive patterns must yield exactly one line, fn exact() { needle(); }, from fn[exact]. The following fn last() {} line is not included, so context is clipped at the item end.
  • An assertion on the full lines JSON fixes the clipped text and the matched flag.

Considered but not a gap

  • The attached-comment and attribute assertions for fn[target] run only for ripgrep. In the implementation, impl[SearchNodes]/fn[entries] handles both tools through one shared function. The ast_grep path is still tested for exclusion of neighbours and for shared-line clipping.

Inputs

Implementation

Input 5: outline src/authoring/tools.rs impl[SearchNodes]/fn[entries]
    /// The entries in source order: each node's file, selector, and kind,
    /// and its lines' redacted text, each marked as matching or not, with an
    /// elision line between separate windows and no line numbers. Context
    /// is clipped to each item, including boundaries within a physical line.
    // {impl}`requirements.authoring.redaction`
    // {impl}`requirements.references.outline_selectors`
    // {impl}`requirements.authoring.text_search`
    // {impl}`requirements.authoring.no_line_numbers`
    // {impl}`requirements.authoring.search_accounting.excerpts`
    fn entries(self, file: &str, parsed: &crate::inputs::ParsedSource) -> Vec<Value> {
        let redaction = crate::redaction::Redaction::of_file(&parsed.path, &parsed.source);
        let mut offset = 0;
        let text = parsed
            .source
            .split_inclusive('\n')
            .map(|line| {
                let start = offset;
                offset += line.len();
                let body = line.trim_end_matches('\n').trim_end_matches('\r');
                (start, start + body.len())
            })
            .collect::<Vec<_>>();
        let mut nodes = self.0.into_iter().collect::<Vec<_>>();
        nodes.sort_by_key(|(index, _)| {
            let node = &parsed.outline.nodes[*index];
            (node.line_start, node.byte_start, *index)
        });
        nodes
            .into_iter()
            .map(|(index, (matched, around))| {
                let node = &parsed.outline.nodes[index];
                let mut first = node.source_start;
                let mut last = node.byte_end;
                for comment in parsed
                    .outline
                    .comments
                    .iter()
                    .filter(|comment| comment.owner == index)
                {
                    first = first.min(comment.byte_start);
                    last = last.max(comment.byte_end);
                }
                let lines = matched.union(&around);
                let mut shown_lines = Vec::new();
                let mut previous = None;
                for line in lines {
                    let Some(&(start, end)) = line.checked_sub(1).and_then(|line| text.get(line))
                    else {
                        continue;
                    };
                    let (start, end) = (start.max(first), end.min(last));
                    if start > end || end < first || start > last {
                        continue;
                    }
                    if previous.is_some_and(|previous: usize| previous + 1 < *line) {
                        shown_lines.push(json!({"text": ELISION, "matched": false}));
                    }
                    previous = Some(*line);
                    shown_lines.push(json!({
                        "text": redaction.slice(&parsed.source, start..end),
                        "matched": matched.contains(line),
                    }));
                }
                json!({
                    "file": file,
                    "item": node.selector,
                    "kind": if index == 0 { "file" } else { node.kind },
                    "lines": shown_lines,
                })
            })
            .collect()
    }

Tests

Input 3: outline src/authoring/tools.rs mod[tests]/fn[search_excerpts_stop_at_byte_boundaries_including_attached_comments_and_attributes]
  • File: src/authoring/tools.rs
  • Selector: mod[tests]/fn[search_excerpts_stop_at_byte_boundaries_including_attached_comments_and_attributes]
  • Kind: fn
  • src/authoring/tools.rs:3587–3668
    // {test}`requirements.authoring.search_accounting.excerpts`
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.structural_search`
    // {test}`requirements.authoring.redaction`
    #[test]
    fn search_excerpts_stop_at_byte_boundaries_including_attached_comments_and_attributes() {
        let root = project();
        let token = format!("ghp_{}", "S".repeat(36));
        fs::write(root.path().join("src/lib.rs"), format!(
            "fn before() {{ unwanted_before(); }}\n\
             /// needle docs\n\
             #[inline]\n\
             fn target() {{\n    let café = \"{token}\";\n    needle();\n}}\n\
             fn after() {{ unwanted_after(); }}\n\
             fn left() {{ unwanted_left(); }} /* needle attached */ #[inline] fn right() {{ needle(); }} fn last() {{ unwanted_last(); }}\n"
        )).unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for (tool, args) in [
            (
                "ripgrep",
                json!({"pattern":"needle","path":"src/lib.rs","context":99}),
            ),
            (
                "ast_grep",
                json!({"language":"rust","path":"src/lib.rs",
                "rule":{"rule":{"any":[{"pattern":"needle()"},{"kind":"block_comment","regex":"needle"}]}}}),
            ),
        ] {
            let result = dispatch(&sources, tool, &args).unwrap().result;
            let matches = result["matches"].as_array().unwrap();
            assert_eq!(matches.len(), 3, "{tool}: {matches:?}");
            assert_eq!(matches[0]["item"], "fn[target]");
            assert_eq!(matches[1]["item"], "fn[left]");
            assert_eq!(matches[2]["item"], "fn[right]");
            assert!(!matches[1]["lines"].to_string().contains("fn right"));
            assert!(!matches[2]["lines"].to_string().contains("fn left"));
            assert!(!matches[2]["lines"].to_string().contains("needle attached"));
            let text = result.to_string();
            for unwanted in [
                "unwanted_before",
                "unwanted_after",
                "unwanted_last",
                "fn last",
            ] {
                assert!(!text.contains(unwanted), "{tool}: {text}");
            }
            assert!(!text.contains(&token), "{text}");
            if tool == "ripgrep" {
                let lines = &matches[0]["lines"];
                assert!(lines.to_string().contains("needle docs"));
                assert!(lines.to_string().contains("#[inline]"));
                assert!(lines.to_string().contains("café"));
                assert!(lines.to_string().contains("[REDACTED:"));
            }
            assert!(matches[1]["lines"].to_string().contains("needle attached"));
            assert!(
                matches[2]["lines"]
                    .to_string()
                    .contains("#[inline] fn right")
            );
        }
        let only = dispatch(
            &sources,
            "ripgrep",
            &json!({"pattern":"café","path":"src/lib.rs","context":0}),
        )
        .unwrap();
        assert_eq!(only.result["matches"].as_array().unwrap().len(), 1);
        assert_eq!(only.result["matches"][0]["item"], "fn[target]");
        let attributes = dispatch(
            &sources,
            "ripgrep",
            &json!({
                "pattern":"inline","path":"src/lib.rs","context":0
            }),
        )
        .unwrap();
        assert_eq!(
            found(&attributes),
            ["src/lib.rs#fn[target]", "src/lib.rs#fn[right]"]
        );
    }
Input 4: outline src/authoring/tools.rs mod[tests]/fn[exact_match_ranges_preserve_regex_anchors_and_skip_unmatched_or_binary_sources]
  • File: src/authoring/tools.rs
  • Selector: mod[tests]/fn[exact_match_ranges_preserve_regex_anchors_and_skip_unmatched_or_binary_sources]
  • Kind: fn
  • src/authoring/tools.rs:3670–3708
    // {test}`requirements.authoring.text_search`
    // {test}`requirements.authoring.search_accounting.excerpts`
    #[test]
    fn exact_match_ranges_preserve_regex_anchors_and_skip_unmatched_or_binary_sources() {
        let root = project();
        fs::write(
            root.path().join("src/lib.rs"),
            "fn exact() { needle(); }\nfn last() {}\n",
        )
        .unwrap();
        fs::write(root.path().join("src/broken.rs"), "fn incomplete( {\n").unwrap();
        fs::write(root.path().join("image.bin"), b"\0needle\xff").unwrap();
        let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
        for pattern in [
            r"^fn exact",
            r"needle\(\); \}$",
            r"(?i)EXACT",
            r"^fn exact.*$",
        ] {
            let result = dispatch(
                &sources,
                "ripgrep",
                &json!({"pattern":pattern,"context":10}),
            )
            .unwrap();
            assert_eq!(
                found(&result),
                ["src/lib.rs#fn[exact]"],
                "{pattern}: {}",
                result.result
            );
            assert_eq!(
                result.result["matches"][0]["lines"],
                json!([
                    {"text":"fn exact() { needle(); }","matched":true}
                ])
            );
        }
    }

Referenced definitions

Input 2: 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`.
:::

Other sources

Input 1: requirements selection requirements.authoring.search_accounting.excerpts
:::{req} search_accounting.excerpts
Every `ripgrep` or `ast_grep` excerpt, including matching and context text,
MUST be clipped to
the source span of the outline item identified by their `file` and `item`,
including that item's attached source under
{cite}`requirements.references.outline_comments`.
Clipping MUST apply within a line shared by different items.
:::