requirements.authoring.search_accounting.excerpts
Requirements index · View definition
Requirement
Every
ripgreporast_grepexcerpt, including matching and context text, MUST be clipped to the source span of the outline item identified by theirfileanditem, including that item’s attached source under. 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
- Both
ripgrepandast_grepexcerpts, matching and context text alike, are clipped to the span of the item named byfileanditem. - That span includes the item’s attached comments and attributes, per
requirements.references.outline_comments. - 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 tofn target,fn after, and a shared line holdingfn left, a trailing block comment,#[inline] fn rightandfn last. - It runs both tools:
ripgrepwithcontext99, andast_grepwith a rule that matchesneedle()or a block comment containing “needle”. - Each tool must return exactly three matches, with items
fn[target],fn[left]andfn[right], in that order. - Neighbouring items’ content never leaks into any excerpt. The assertions rule out
unwanted_before,unwanted_after,unwanted_lastandfn lastin the whole result. They also rule outfn rightin left’s excerpt andfn leftin right’s excerpt. Context of 99 lines forripgrepwould pull in neighbours if clipping failed. - Attached source is included. For
ripgrepthefn[target]excerpt must contain “needle docs” and#[inline]. For both tools,fn[left]must contain “needle attached” andfn[right]must contain “#[inline] fn right”. - The comment that follows code on the same line is attributed to
fn[left]and kept out offn[right]. - Clipping on a shared line is tested for both tools.
- Multi-byte “café” in
fn targetexercises byte-boundary slicing, and the redaction marker is checked. - Two more
ripgrepruns withcontext0 check match attribution. One searchescaféand must return onlyfn[target]. The other searchesinlineand must return thefn[target]andfn[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
context10, anchored and case-insensitive patterns must yield exactly one line,fn exact() { needle(); }, fromfn[exact]. The followingfn last() {}line is not included, so context is clipped at the item end. - An assertion on the full
linesJSON fixes the clipped text and thematchedflag.
Considered but not a gap
- The attached-comment and attribute assertions for
fn[target]run only forripgrep. In the implementation,impl[SearchNodes]/fn[entries]handles both tools through one shared function. Theast_greppath 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]
- File:
src/authoring/tools.rs - Selector:
impl[SearchNodes]/fn[entries] - Kind:
fn src/authoring/tools.rs:763–834
/// 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
requirements.references.outline_comments:md/requirements/references.md:415–430
:::{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
requirements.authoring.search_accounting.excerpts:md/requirements/authoring.md:959–966
:::{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.
:::