requirements.references.distributed
Requirements index · View definition
Requirement
A requirement MAY be distributed: it states obligations that each of many sites in the sources must uphold on its own, such as a convention every validation function follows, and MAY also state obligations that particular code carries out, which that code implements with
{impl}. A{req}body declares a distributed requirement by containing one or more nested query directives::::{sites} <name>for a site query, which finds the places the obligation applies, or:::{violations} <name>for a violation query, which finds constructs likely to break it. A requirement with a violation query MUST also have a site query. Query names MUST be single identifier segments under, unique within the requirement. A query directive outside a
{req}body MUST be a validation error. Each query body MUST be one fencedyamlcode block containing a mapping with only these keys:
language, required: the name of an outline profile with a grammar under:
rust,python,typescript,tsx,css,markdown,toml, oryaml.paths, optional: project-relative files or directories. Only sources at or under one of them are searched; without it, every source of the language is.exclude, optional: project-relative files or directories whose sources are not searched, even underpaths.rule, required, with optionalutilsandconstraints: an ast-grep rule core in the syntax of Habeas’s pinnedast-grep-configversion, matched against the language’s pinned grammar.within, required for violation queries and not allowed for site queries: the name of a site query in the same requirement.matchandno_match, required: nonempty lists of source snippets in the query’s language. Eachmatchsnippet MUST contain at least one match of the query, and eachno_matchsnippet none, where a violation query counts only matches inside a site of itswithinquery in the same snippet.Validation MUST report a query whose body is not such a mapping, whose rule does not compile, whose
withinnames no site query of the requirement, a violation query withoutwithin, or one of whose snippets fails to parse or has the wrong match result, and a site query that matches nothing in the project. Queries MUST search exactly the sources reference discovery considers under, in their original text.
A match’s site MUST be the innermost outline node, under
, whose range contains the match; for a violation query, it MUST instead be the innermost site of its
withinquery that contains the match, and a match inside none of that query’s sites MUST be discarded. A requirement’s sites MUST be the distinct sites of all its queries’ matches. Each site MUST have a site review under, and needs no reference to the requirement; being a site MUST NOT count as a reference for
, because a distributed requirement concerns a cross-cutting obligation, not why the item exists. Upgrading
ast-grep-configMAY change matches and MUST be treated as a deliberate change. The book MUST render each query directive as a badge naming its kind and name, followed by its code block.
Rationale
The reviewed tests adequately check requirements.references.distributed. I found no unacknowledged gap. Each obligation maps to a test with assertions, as follows.
Query declaration and validation (all in src/sites.rs tests unless noted)
- Names are single identifier segments.
mod[tests]/fn[malformed_queries_are_reported_each_on_its_own]usesbad.nameand expects “single identifier segment”. - Names are unique. The same test declares
twicetwice and expects the duplicate-name error. It also checks that only the firsttwiceruns. - A violation query needs a site query.
fn[a_violation_query_needs_a_site_query]asserts the “must also have a site query” error. - Query directive outside a
{req}body is an error. Theoutsidequery in the malformed-queries test expects the error. A{sites}line inside a```textfence is asserted to produce no error. - Body must be exactly one fenced yaml block.
src/structural.rs#mod[tests]/fn[query_bodies_require_exactly_one_yaml_fence_and_no_other_content]accepts```and~~~fences with surrounding blank lines. It rejects json, text and yml fences, two blocks, prose before or after the block, mismatched fences, and a bare body.src/authoring/tools.rs#mod[tests]/fn[ast_grep_queries_run_declared_queries_and_return_their_sites]also covers the prose-only body. - Only the listed keys are allowed. The malformed-queries test expects “unknown field
fix”.src/structural.rs#mod[tests]/fn[rules_compile_for_every_grammar_and_report_invalid_input]expects “unexpected key” forfixin the rule core and “missing key rule” whenruleis absent. languagemust be a supported profile. The same structural test compiles rules for rust, python, typescript, tsx, css, markdown, toml and yaml. It rejectscobolandplain-text.rule,utilsandconstraints.fn[declared_queries_apply_their_utils_and_constraints]uses a rule that compiles only withutilsand selects the right functions only withconstraints. Itsno_matchsnippets,fn otherandstruct check_one;, also exercise the rule. The malformed-queries test expects “invalid ast-grep rule” for an unknown kind, and the structural test expects the same for a bogus rule key.pathsandexclude.ast_grep_queries_run_declared_queries_and_return_their_sitessetspaths: [src]andexclude: [src/skip.rs]. It asserts thatsrc/skip.rsandtests/outside.rsare not sites.withinrules. The malformed-queries test covers a violation withoutwithin(“must have within”), awithinnaming a missing query (“within names no site query”), and a site query withwithin(“must not have within”).matchandno_matchlists. The malformed-queries test covers an emptyno_match(“must be a nonempty list”), a non-matchingmatchsnippet, ano_matchsnippet that fails to parse, and a snippet matched when it should not be.fn[snippets_must_have_the_expected_matches_counting_violations_within_sites]asserts that violation snippets count only matches inside a site of thewithinquery, in both directions.- A site query that matches nothing is reported. The malformed-queries test covers the
nothingandtwicequeries. The firsttwicequery matches nothing and is expected to be reported. - Queries search the sources reference discovery considers. The tool test and the sites tests run queries over the project’s discovered files.
declared_queryuses the shareddiscovered_files. The git-index and exclusion rules belong torequirements.references.discoveryand are tested there.
Sites
- Site is the innermost outline node.
fn[sites_are_the_innermost_nodes_of_site_matches_and_violations_within_them]checks the innermost-site selectors, including the nestedmod[inner]/fn[check_three].src/structural.rs#mod[tests]/fn[matches_belong_to_the_innermost_node_or_comment_owner]checks the innermost owner, including attached doc comments, attributes and the root. - Violation matches go to the innermost containing site, and others are discarded. The sites test checks this for the nested function.
ast_grep_queries_run_declared_queries_and_return_their_sitesasserts thatreturninhelperis discarded and that onlyfn[check]is reported. - A requirement’s sites are the distinct sites of all its queries. The sites test asserts that
check_oneappears once, withqueries["checkers", "panics"]. - Every site needs a site review. The sites test asserts a “missing site review” error for each of the three sites.
- Being a site is not a reference for Rust item coverage. The sites test asserts that
check_two, a site with no reference, still reports “has no recent coverage”.
Rendering
src/lib.rs#mod[tests]/fn[query_directives_render_as_badges_followed_by_their_code_blocks]asserts the badge naming kind and name, followed by the code block, for bothsitesandviolations. It also asserts that directives in a code example stay literal.
Delegated or not testable here
- Review content and staleness belong to
requirements.references.site_review. - “Upgrading
ast-grep-configMUST be treated as a deliberate change” is a process obligation, not behavior a test can check.
Minor boundary, not a gap
fn[a_violation_query_needs_a_site_query]uses a violation query whosewithinnames itself, but it asserts only the “must also have a site query” error. It does not assert that “within names no site query” fires whenwithinnames a violation query. I do not treat this as an adequacy gap. The test’s scenario does exercise the case, and the “within names no site query” error is asserted for awithinthat names no query at all.
Inputs
Implementation
Input 17: outline src/sites.rs fn[requirement_sites]
- File:
src/sites.rs - Selector:
fn[requirement_sites] - Kind:
fn src/sites.rs:175–193
/// The sites of one distributed requirement's well-formed queries, without
/// validating the queries; a requirement without queries has none.
// {impl}`requirements.references.distributed`
pub(crate) fn requirement_sites(
root: &Path,
name: &str,
declaration: &Declaration,
files: &[PathBuf],
outlines: &OutlineCache,
) -> Result<Vec<SiteItem>, String> {
let (queries, _) = crate::structural::parse_queries(declaration);
let mut matches = Vec::new();
for query in &queries {
let found = crate::structural::query_matches(root, files, outlines, &queries, &query.name)
.map_err(|error| format!("{name}: query {}: {error}", query.name))?;
matches.push((query, found));
}
Ok(collect_sites(root, name, outlines, matches))
}
Input 23: outline src/authoring/tools.rs fn[declared_query]
- File:
src/authoring/tools.rs - Selector:
fn[declared_query] - Kind:
fn src/authoring/tools.rs:1189–1250
/// Runs a query a distributed requirement declares, named
/// `<full-name>/<query-name>`, as validation runs it, returning each match's
/// site as a search entry with the matched lines.
// {impl}`requirements.references.distributed`
fn declared_query(sources: &AssessmentSources, query: &str) -> io::Result<Listing> {
let (requirement, name) = query.rsplit_once('/').ok_or_else(|| {
io::Error::other(format!(
"query {query:?} must have the form <full-name>/<query-name>"
))
})?;
let definitions = crate::evidence::load_definitions(&sources.root)?;
let declaration = definitions
.get(requirement)
.filter(|definition| definition.kind == crate::DefinitionKind::Requirement)
.ok_or_else(|| {
io::Error::other(format!("query {query:?} names no declared requirement"))
})?;
let queries = crate::structural::declared_queries(declaration).map_err(io::Error::other)?;
if !queries.iter().any(|declared| declared.name == name) {
return Err(io::Error::other(format!(
"requirement {requirement} declares no query named {name:?}"
)));
}
let mut errors = Vec::new();
let files = crate::evidence::discovered_files(&sources.root, &mut errors);
if !errors.is_empty() {
return Err(io::Error::other(format!(
"cannot run query {query} because reference discovery failed:\n{}",
errors.join("\n")
)));
}
let found =
crate::structural::query_matches(&sources.root, &files, &sources.outlines, &queries, name)
.map_err(|error| io::Error::other(format!("query {query}: {error}")))?;
// Matches arrive in path and source order; each site is one entry.
let mut by_file = BTreeMap::<String, BTreeMap<String, SearchMatchLines>>::new();
for found in found {
by_file
.entry(found.site.file)
.or_default()
.entry(found.site.item)
.or_default()
.push(found.line_start..=found.line_end);
}
let mut entries = Vec::new();
for (file, items) in by_file {
let parsed = sources.parse_file(&file)?;
let parsed = parsed
.as_ref()
.as_ref()
.map_err(|error| io::Error::other(error.clone()))?;
let mut nodes = SearchNodes::default();
for (item, lines) in items {
let index = parsed.resolve(&file, &item).map_err(io::Error::other)?;
for lines in lines {
nodes.add(index, lines.clone(), lines);
}
}
entries.extend(nodes.entries(&file, parsed));
}
Ok(Listing::object(&["matches"], vec![entries]))
}
Tests
Input 7: outline src/authoring/tools.rs mod[tests]/fn[ast_grep_queries_run_declared_queries_and_return_their_sites]
- File:
src/authoring/tools.rs - Selector:
mod[tests]/fn[ast_grep_queries_run_declared_queries_and_return_their_sites] - Kind:
fn src/authoring/tools.rs:4872–4957
// {test}`requirements.authoring.structural_search`
// {test}`requirements.references.distributed`
#[test]
fn ast_grep_queries_run_declared_queries_and_return_their_sites() {
let root = project();
fs::write(
root.path().join("md/requirements.md"),
concat!(
":::{req} ready\nThe project MUST be ready.\n:::\n\n",
"::::{req} errors\nAccumulating functions MUST keep going.\n\n",
":::{sites} accumulators\n```yaml\nlanguage: rust\npaths: [src]\nexclude: [src/skip.rs]\n",
"rule:\n kind: function_item\n has:\n stopBy: end\n kind: identifier\n regex: \"^errors$\"\n",
"match: [\"fn f(errors: u8) {}\"]\nno_match: [\"fn f() {}\"]\n```\n:::\n\n",
":::{violations} exits\n```yaml\nlanguage: rust\nwithin: accumulators\n",
"rule:\n kind: return_expression\n",
"match: [\"fn f(errors: u8) { return; }\"]\nno_match: [\"fn f() { return; }\"]\n```\n:::\n",
"::::\n\n",
"::::{req} broken\nBroken.\n\n:::{sites} bad\nNo code block.\n:::\n::::\n",
),
)
.unwrap();
fs::write(
root.path().join("md/terms.md"),
":::{definition} value\n:phrase: value\nA useful value.\n:::\n",
)
.unwrap();
fs::write(
root.path().join("src/lib.rs"),
format!(
"fn check(errors: &mut Vec<String>) {{\n // {}\n if errors.is_empty() {{\n return;\n }}\n}}\n\nfn helper() {{\n return;\n}}\n\nmod inner {{\n fn nested(errors: u8) {{}}\n}}\n",
role("term", "terms.value")
),
)
.unwrap();
fs::write(
root.path().join("src/skip.rs"),
"fn skipped(errors: u8) {}\n",
)
.unwrap();
fs::create_dir_all(root.path().join("tests")).unwrap();
fs::write(
root.path().join("tests/outside.rs"),
"fn outside(errors: u8) {}\n",
)
.unwrap();
let sources = AssessmentSources::prepare(root.path(), "requirements.ready").unwrap();
let query = |name: &str| dispatch(&sources, "ast_grep", &json!({"query": name}));
// Site queries honour paths and exclude.
let sites = query("requirements.errors/accumulators").unwrap();
assert_eq!(
found(&sites),
["src/lib.rs#fn[check]", "src/lib.rs#mod[inner]/fn[nested]"]
);
// Each site shows its matched lines, without terminology.
let lines = |delivery: &ToolDelivery, entry: usize| {
matched(delivery)[entry]["lines"]
.as_array()
.unwrap()
.iter()
.map(|line| line["matched"].as_bool().unwrap())
.collect::<Vec<_>>()
};
assert_eq!(lines(&sites, 0), [true; 6]);
assert!(sites.result.get("definitions").is_none());
// Violation matches belong to the innermost containing site; matches
// inside no site are discarded.
let violations = query("requirements.errors/exits").unwrap();
assert_eq!(found(&violations), ["src/lib.rs#fn[check]"]);
assert_eq!(
matched(&violations)[0]["lines"],
json!([{"text": " return;", "matched": true}])
);
for (name, message) in [
(
"requirements.errors/missing",
"declares no query named \"missing\"",
),
(
"requirements.broken/bad",
"exactly one fenced yaml code block",
),
] {
let error = query(name).err().unwrap();
assert!(error.to_string().contains(message), "{name}: {error}");
}
}
Input 8: outline src/lib.rs mod[tests]/fn[query_directives_render_as_badges_followed_by_their_code_blocks]
- File:
src/lib.rs - Selector:
mod[tests]/fn[query_directives_render_as_badges_followed_by_their_code_blocks] - Kind:
fn src/lib.rs:1860–1876
// {test}`requirements.references.distributed`
#[test]
fn query_directives_render_as_badges_followed_by_their_code_blocks() {
let source = "::::{req} spread\nEach site MUST hold.\n\n:::{sites} checks\n```yaml\nlanguage: rust\n```\n:::\n\n:::{violations} risky\n```yaml\nwithin: checks\n```\n:::\n\n```text\n:::{sites} literal\n```\n::::\n";
let rendered = replace_definitions(source, "requirements", None, None);
assert!(
rendered.contains("<span class=\"habeas-query-badge\"><img class=\"habeas-shield\" src=\"https://img.shields.io/badge/sites-checks-6c4f8a?style=flat-square&labelColor=555\" alt=\"sites checks\" loading=\"lazy\"></span>\n\n```yaml\nlanguage: rust\n```\n\n<span class=\"habeas-query-badge\">"),
"{rendered}"
);
assert!(rendered.contains("alt=\"violations risky\""), "{rendered}");
assert!(!rendered.contains(":::{sites} checks"), "{rendered}");
assert!(!rendered.contains("\n:::\n"), "{rendered}");
assert!(
rendered.contains("```text\n:::{sites} literal\n```"),
"{rendered}"
);
}
Input 9: outline src/sites.rs mod[tests]/fn[sites_are_the_innermost_nodes_of_site_matches_and_violations_within_them]
- File:
src/sites.rs - Selector:
mod[tests]/fn[sites_are_the_innermost_nodes_of_site_matches_and_violations_within_them] - Kind:
fn src/sites.rs:914–979
// {test}`requirements.references.distributed`
#[test]
// {test}`requirements.authoring.no_line_numbers`
fn sites_are_the_innermost_nodes_of_site_matches_and_violations_within_them() {
let temp = project(RULE, SOURCE);
let (errors, sites) = inspect(temp.path());
let sites = &sites["requirements.rule"];
let found = sites
.iter()
.map(|site| (site.item.as_str(), site.queries()))
.collect::<Vec<_>>();
assert_eq!(
found,
[
(
"fn[check_one]",
vec!["checkers".to_owned(), "panics".to_owned()]
),
("fn[check_two]", vec!["checkers".to_owned()]),
(
"mod[inner]/fn[check_three]",
vec!["checkers".to_owned(), "panics".to_owned()]
),
]
);
let nested = &sites[2];
assert_eq!((nested.line_start, nested.line_end), (5, 7));
let violation = nested
.matches
.iter()
.find(|found| found.kind == QueryKind::Violations)
.unwrap();
assert_eq!(violation.text, "panic!(\"z\")");
assert_eq!(violation.line_start, 6);
assert_eq!(
nested.matches_value()[1],
json!({"kind": "violations", "query": "panics", "item": "mod[inner]/fn[check_three]/fn[nested]", "text": "panic!(\"z\")"})
);
// No query problems; each site lacks a review, and being a site is
// not a reference for Rust item coverage.
assert!(
!errors.iter().any(|error| error.contains("query")),
"{errors:?}"
);
for item in [
"fn[check_one]",
"fn[check_two]",
"mod[inner]/fn[check_three]",
] {
let path = review_path("requirements.rule", "src/lib.rs", item);
assert!(
errors
.iter()
.any(|error| error.starts_with(&format!("{path}: missing site review"))),
"{item}: {errors:?}"
);
}
let inspection = crate::evidence::inspect_repository(temp.path()).unwrap();
assert!(
inspection.uncovered.iter().any(|item| item
.error
.contains("function check_two has no recent coverage")),
"{:?}",
inspection.uncovered
);
}
Input 10: outline src/sites.rs mod[tests]/fn[declared_queries_apply_their_utils_and_constraints]
- File:
src/sites.rs - Selector:
mod[tests]/fn[declared_queries_apply_their_utils_and_constraints] - Kind:
fn src/sites.rs:1002–1050
// {test}`requirements.references.distributed`
#[test]
fn declared_queries_apply_their_utils_and_constraints() {
// Without `utils` the rule cannot compile, and without `constraints`
// it would also select `other` and fail its `no_match` snippet.
let chapter = r#":::::{req} rule
Each checker MUST report problems instead of panicking.
::::{sites} checkers
```yaml
language: rust
rule:
all:
- pattern: "fn $NAME() { $$$BODY }"
- matches: function
utils:
function: { kind: function_item }
constraints:
NAME: { regex: "^check_" }
match:
- "fn check_one() {}"
no_match:
- "fn other() {}"
- "struct check_one;"
```
::::
:::::
"#;
let temp = project(chapter, SOURCE);
let (errors, sites) = inspect(temp.path());
assert!(
!errors
.iter()
.any(|error| error.contains("query") || error.contains("snippet")),
"{errors:#?}"
);
let found = sites["requirements.rule"]
.iter()
.map(|site| site.item.as_str())
.collect::<Vec<_>>();
assert_eq!(
found,
[
"fn[check_one]",
"fn[check_two]",
"mod[inner]/fn[check_three]"
]
);
}
Input 11: outline src/sites.rs mod[tests]/fn[malformed_queries_are_reported_each_on_its_own]
- File:
src/sites.rs - Selector:
mod[tests]/fn[malformed_queries_are_reported_each_on_its_own] - Kind:
fn src/sites.rs:1052–1207
// {test}`requirements.references.distributed`
#[test]
fn malformed_queries_are_reported_each_on_its_own() {
let chapter = r#":::::{req} rule
Text.
::::{sites} bad.name
```yaml
language: rust
rule: { kind: function_item }
match: ["fn a() {}"]
no_match: ["fn a() {}"]
```
::::
::::{sites} nothing
```yaml
language: rust
rule: { kind: function_item, regex: "^fn never_defined" }
match: ["struct S;"]
no_match: ["fn"]
```
::::
::::{sites} uncompiled
```yaml
language: rust
rule: { kind: no_such_kind }
match: ["fn a() {}"]
no_match: ["fn b() {}"]
```
::::
::::{violations} loose
```yaml
language: rust
rule: { kind: function_item }
match: ["fn a() {}"]
no_match: ["fn b() {}"]
```
::::
::::{violations} astray
```yaml
language: rust
within: missing
rule: { kind: function_item }
match: ["fn a() {}"]
no_match: []
```
::::
::::{sites} keyed
```yaml
language: rust
within: nothing
rule: { kind: function_item }
match: ["fn a() {}"]
no_match: ["struct S;"]
```
::::
::::{sites} extra
```yaml
language: rust
rule: { kind: function_item }
fix: ""
match: ["fn a() {}"]
no_match: ["struct S;"]
```
::::
::::{sites} twice
```yaml
language: rust
rule: { kind: struct_item }
match: ["struct S;"]
no_match: ["fn a() {}"]
```
::::
::::{sites} twice
```yaml
language: rust
rule: { kind: struct_item }
match: ["struct S;"]
no_match: ["fn a() {}"]
```
::::
::::{sites} prose
Not a code block.
::::
:::::
::::{sites} outside
```yaml
language: rust
rule: { kind: function_item }
match: ["fn a() {}"]
no_match: ["struct S;"]
```
::::
```text
::::{sites} literal
```
"#;
let temp = project(chapter, "fn run() {}\n");
let (errors, sites) = inspect(temp.path());
let errors = errors
.into_iter()
.filter(|error| error.starts_with("md/"))
.collect::<Vec<_>>();
let expect = |line: usize, text: &str| {
assert!(
errors.iter().any(|error| {
error.starts_with(&format!("md/requirements.md:{line}:"))
&& error.contains(text)
}),
"{line}: {text}: {errors:#?}"
);
};
expect(4, "single identifier segment");
// The first matching snippet has no match, the no_match snippet does
// not parse, and nothing in the project matches.
expect(13, "match[0] snippet contains no match");
expect(13, "no_match[0] snippet does not parse as rust");
expect(
13,
"site query nothing of requirements.rule matches nothing in the project",
);
expect(22, "invalid ast-grep rule");
expect(31, "violation query loose must have within");
expect(40, "within names no site query \"missing\"");
expect(40, "no_match must be a nonempty list");
expect(50, "site query keyed must not have within");
expect(60, "unknown field `fix`");
expect(79, "query name twice is declared more than once");
expect(70, "site query twice of requirements.rule matches nothing");
assert!(
!errors
.iter()
.any(|error| error.starts_with("md/requirements.md:79:")
&& error.contains("matches nothing")),
"{errors:#?}"
);
expect(88, "must contain exactly one fenced yaml code block");
expect(93, "{sites} query outside must appear inside a {req} body");
assert!(
!errors.iter().any(|error| error.contains("literal")),
"{errors:#?}"
);
// Only the first `twice` runs, and it selects nothing.
assert!(sites["requirements.rule"].is_empty());
}
Input 12: outline src/sites.rs mod[tests]/fn[snippets_must_have_the_expected_matches_counting_violations_within_sites]
- File:
src/sites.rs - Selector:
mod[tests]/fn[snippets_must_have_the_expected_matches_counting_violations_within_sites] - Kind:
fn src/sites.rs:1209–1232
// {test}`requirements.references.distributed`
#[test]
fn snippets_must_have_the_expected_matches_counting_violations_within_sites() {
let chapter = RULE
.replace(
" - \"fn other() { panic!(); }\"",
" - \"fn check_other() { panic!(); }\"",
)
.replace(
" - \"fn check_one() { panic!(); }\"",
" - \"fn one() { panic!(); }\"",
);
let temp = project(&chapter, SOURCE);
let (errors, _) = inspect(temp.path());
for text in [
"query panics of requirements.rule: match[0] snippet contains no match of the query",
"query panics of requirements.rule: no_match[0] snippet contains 1 matches of the query",
] {
assert!(
errors.iter().any(|error| error.contains(text)),
"{text}: {errors:#?}"
);
}
}
Input 13: outline src/sites.rs mod[tests]/fn[a_violation_query_needs_a_site_query]
- File:
src/sites.rs - Selector:
mod[tests]/fn[a_violation_query_needs_a_site_query] - Kind:
fn src/sites.rs:1234–1248
// {test}`requirements.references.distributed`
#[test]
fn a_violation_query_needs_a_site_query() {
let chapter = ":::{req} rule\nText.\n\n::::{violations} only\n```yaml\nlanguage: rust\nwithin: only\nrule: { kind: function_item }\nmatch: [\"fn a() {}\"]\nno_match: [\"struct S;\"]\n```\n::::\n:::\n"
.replace(":::{req}", ":::::{req}")
.replace("\n:::\n", "\n:::::\n");
let temp = project(&chapter, "fn run() {}\n");
let (errors, _) = inspect(temp.path());
assert!(
errors.iter().any(|error| error.contains(
"requirements.rule has a violation query, so it must also have a site query"
)),
"{errors:#?}"
);
}
Input 14: outline src/structural.rs mod[tests]/fn[query_bodies_require_exactly_one_yaml_fence_and_no_other_content]
- File:
src/structural.rs - Selector:
mod[tests]/fn[query_bodies_require_exactly_one_yaml_fence_and_no_other_content] - Kind:
fn src/structural.rs:608–655
// {test}`requirements.references.distributed`
#[test]
fn query_bodies_require_exactly_one_yaml_fence_and_no_other_content() {
let yaml = "language: rust\nrule:\n kind: function_item\nmatch: ['fn f() {}']\nno_match: ['struct S;']";
let declaration = |body: &str| {
let text = format!(":::{{req}} example\n:::{{sites}} functions\n{body}\n:::\n:::");
Declaration {
kind: crate::DefinitionKind::Requirement,
source: "md/requirements.md:1".to_owned(),
file: "md/requirements.md".to_owned(),
line_start: 1,
line_end: text.lines().count(),
raw_lines: text.lines().map(str::to_owned).collect(),
anchors: vec![],
text,
}
};
for body in [
format!("```yaml\n{yaml}\n```"),
format!("\n\n~~~yaml\n{yaml}\n~~~\n\n"),
] {
let (queries, errors) = parse_queries(&declaration(&body));
assert!(errors.is_empty(), "{body}: {errors:?}");
assert_eq!(queries.len(), 1);
assert_eq!(queries[0].name, "functions");
assert_eq!(queries[0].body.language, "rust");
}
for body in [
format!("```json\n{yaml}\n```"),
format!("```text\n{yaml}\n```"),
format!("```yml\n{yaml}\n```"),
format!("```yaml\n{yaml}\n```\n```yaml\n{yaml}\n```"),
format!("prose\n```yaml\n{yaml}\n```"),
format!("```yaml\n{yaml}\n```\nprose"),
format!("```yaml\n{yaml}\n~~~"),
format!("``yaml\n{yaml}\n``"),
yaml.to_owned(),
] {
let (queries, errors) = parse_queries(&declaration(&body));
assert!(queries.is_empty(), "accepted {body:?}");
assert_eq!(errors.len(), 1, "{body}: {errors:?}");
assert!(
errors[0]
.contains("query functions must contain exactly one fenced yaml code block"),
"{body}: {errors:?}"
);
}
}
Input 15: outline src/structural.rs mod[tests]/fn[rules_compile_for_every_grammar_and_report_invalid_input]
- File:
src/structural.rs - Selector:
mod[tests]/fn[rules_compile_for_every_grammar_and_report_invalid_input] - Kind:
fn src/structural.rs:657–754
// {test}`requirements.authoring.structural_search`
// {test}`requirements.references.distributed`
#[test]
fn rules_compile_for_every_grammar_and_report_invalid_input() {
for (language, rule, source, expected) in [
(
"rust",
json!({"pattern": "foo($A)"}),
"fn f() { foo(1); }\n",
"foo(1)",
),
(
"python",
json!({"pattern": "foo($A)"}),
"foo(1)\n",
"foo(1)",
),
(
"typescript",
json!({"pattern": "foo($A)"}),
"foo(1);\n",
"foo(1)",
),
(
"tsx",
json!({"pattern": "<a>{$X}</a>"}),
"const x = <a>{y}</a>;\n",
"<a>{y}</a>",
),
(
"css",
json!({"kind": "class_selector"}),
".a { color: red; }\n",
".a",
),
(
"markdown",
json!({"kind": "atx_heading"}),
"# Title\n\nText.\n",
"# Title\n",
),
(
"toml",
json!({"pattern": "name = $V"}),
"name = 'x'\n",
"name = 'x'",
),
(
"yaml",
json!({"kind": "block_mapping_pair"}),
"key: value\n",
"key: value",
),
] {
let rule =
StructuralRule::compile(language, json!({"rule": rule}).as_object().unwrap())
.unwrap_or_else(|error| panic!("{language}: {error}"));
let found = rule
.matches(source)
.into_iter()
.map(|range| &source[range])
.collect::<Vec<_>>();
assert_eq!(found, [expected], "{language}");
}
for (language, rule, message) in [
(
"cobol",
json!({"rule": {"kind": "x"}}),
"unknown structural search language",
),
(
"plain-text",
json!({"rule": {"kind": "x"}}),
"unknown structural search language",
),
("rust", json!({}), "missing key \"rule\""),
(
"rust",
json!({"rule": {"kind": "x"}, "fix": "y"}),
"unexpected key \"fix\"",
),
(
"rust",
json!({"rule": {"kind": "no_such_kind"}}),
"invalid ast-grep rule",
),
(
"rust",
json!({"rule": {"bogus": 1}}),
"invalid ast-grep rule",
),
] {
let error = StructuralRule::compile(language, rule.as_object().unwrap())
.err()
.unwrap();
assert!(error.contains(message), "{rule}: {error}");
}
}
Input 16: 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.ci.identifiers
requirements.ci.identifiers:md/requirements/ci.md:329–331
:::{req} identifiers
Requirement and reference names MUST have nonempty dot-separated segments containing only ASCII letters, digits, underscores, or hyphens. A `{req}` directive whose full name is invalid, including one whose chapter path gives an invalid namespace, and a role with an invalid name MUST remain literal and MUST NOT define or reference a requirement. For nested chapter paths, a leading `reqs/` and a final `index` or `README` segment MUST be omitted from the requirement namespace.
:::
Input 3: requirements selection requirements.references.outlines
requirements.references.outlines:md/requirements/references.md:358–378
:::{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 4: requirements selection requirements.references.discovery
requirements.references.discovery:md/requirements/references.md:99–112
:::{req} discovery
Habeas MUST find the references of {cite}`requirements.references.roles`
in project source files, where {cite}`requirements.references.reference_contexts`
says they count, and MUST fail with the source file and line if a
name has no matching `{req}` or `{example}` definition. In Markdown, escaped
roles and roles in code examples MUST remain literal. Reference discovery MUST
consider exactly the project sources that source-access policy permits under
{cite}`requirements.authoring.source_tools`: in a Git worktree, files present in
the Git index, including staged new files; outside Git, all project files; in
both cases excluding the project-root `book` and `evidence` directories, `.git`
and `target` directories at any depth, and paths disallowed by
{cite}`requirements.configuration.evidence_paths`. Evidence snapshots and
generated build output MUST therefore not be counted as source references.
:::
Input 5: requirements selection requirements.references.site_review
requirements.references.site_review:md/requirements/references.md:521–559
:::{req} site_review
Every site of a distributed requirement under
{cite}`requirements.references.distributed` MUST have a site review: an
assessment of whether that site upholds the requirement, recorded at
`evidence/sites/<full-name>/<file>/<selector>.json`, where `<file>` and
`<selector>` are encoded as under
{cite}`requirements.references.citation_review`. The review MUST use the prompt
defined by {cite}`requirements.authoring.site_prompt`. Mandatory inputs, under
{cite}`requirements.authoring.mandatory_inputs`, MUST be the site's outline
node, the requirement's complete declaration, and each declaration the
requirement cites. The record MUST contain the requirement's full name, the
site's file and selector, `queries`, the sorted names of the queries with a
match at the site, `applies`, `determination`, `rationale`, and `inputs`, with
determinations under {cite}`requirements.ci.outcomes`. `applies` MUST be a
Boolean recording whether the requirement applies to the site. A site to which
the requirement does not apply MUST be judged `true`, and the rationale MUST
explain why it does not apply. `habeas info` MUST report, for each selected
distributed requirement, how many of its sites the requirement does not apply
to.
Validation MUST require a current, accepted review for every site, MUST report a
false review with its rationale, and MUST report stale, missing, or orphaned
reviews; a review is orphaned when its file and selector no longer name a site
of the requirement. A `{fixme}` naming the requirement inside a site
acknowledges a gap at that site only: it MUST be an input to that site's review
and MUST NOT contribute to the requirement's own review, coverage, or reference
set. A review MUST become stale when the site's hash, the requirement's
declaration, a cited declaration, its `queries`, or the `{fixme}` references
naming the requirement inside the site, with the words of their bodies, change.
Each site review's determination MUST be checked on its own, independently of
the requirement's evidence. Authoring with `--all` MUST include site reviews,
`habeas author sites:<full-name>` MUST author the site reviews of the named
requirement, and `habeas author sites:<full-name>/<file>#<selector>` MUST author
the review of the one site it names, under
{cite}`requirements.authoring.refresh`, where omitting `#<selector>` names the
file's root node. `habeas status` MUST report missing, stale, invalid, and false
site reviews with their requirement, file, and selector, and `habeas info` MUST
list each selected requirement's sites with their determinations.
:::
Input 6: requirements selection requirements.references.rust_item_coverage
requirements.references.rust_item_coverage:md/requirements/references.md:224–226
:::{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`.
:::
Other sources
Input 1: requirements selection requirements.references.distributed
requirements.references.distributed:md/requirements/references.md:472–519
:::{req} distributed
A requirement MAY be distributed: it states obligations that each of many sites
in the sources must uphold on its own, such as a convention every validation
function follows, and MAY also state obligations that particular code carries
out, which that code implements with `{impl}`. A `{req}` body declares a distributed requirement
by containing one or more nested query directives: `:::{sites} <name>` for a
site query, which finds the places the obligation applies, or
`:::{violations} <name>` for a violation query, which finds constructs likely to
break it. A requirement with a violation query MUST also have a site query.
Query names MUST be single identifier segments under
{cite}`requirements.ci.identifiers`, unique within the requirement. A query
directive outside a `{req}` body MUST be a validation error. Each query body
MUST be one fenced `yaml` code block containing a mapping with only these keys:
- `language`, required: the name of an outline profile with a grammar under
{cite}`requirements.references.outlines`: `rust`, `python`, `typescript`,
`tsx`, `css`, `markdown`, `toml`, or `yaml`.
- `paths`, optional: project-relative files or directories. Only sources at or
under one of them are searched; without it, every source of the language is.
- `exclude`, optional: project-relative files or directories whose sources are
not searched, even under `paths`.
- `rule`, required, with optional `utils` and `constraints`: an ast-grep rule
core in the syntax of Habeas's pinned `ast-grep-config` version, matched
against the language's pinned grammar.
- `within`, required for violation queries and not allowed for site queries:
the name of a site query in the same requirement.
- `match` and `no_match`, required: nonempty lists of source snippets in the
query's language. Each `match` snippet MUST contain at least one match of the
query, and each `no_match` snippet none, where a violation query counts only matches inside a site of its `within` query in the same snippet.
Validation MUST report a query whose body is not such a mapping, whose rule does
not compile, whose `within` names no site query of the requirement, a violation query without `within`, or one of whose snippets fails to parse or has the wrong match result, and a site query
that matches nothing in the project. Queries MUST search exactly the sources
reference discovery considers under {cite}`requirements.references.discovery`, in
their original text.
A match's site MUST be the innermost outline node, under
{cite}`requirements.references.outlines`, whose range contains the match; for a violation query, it MUST instead be the innermost site of its `within` query that contains the match, and a match inside none of that query's
sites MUST be discarded. A requirement's sites MUST be the distinct sites of all
its queries' matches. Each site MUST have a site review under
{cite}`requirements.references.site_review`, and needs no reference to the
requirement; being a site MUST NOT count as a reference for
{cite}`requirements.references.rust_item_coverage`, because a distributed
requirement concerns a cross-cutting obligation, not why the item exists.
Upgrading `ast-grep-config` MAY change matches and MUST be treated as a
deliberate change. The book MUST render each query directive as a badge
naming its kind and name, followed by its code block.
:::
Input 18: outline src/structural.rs impl[QueryBody]
- File:
src/structural.rs - Selector:
impl[QueryBody] - Kind:
impl src/structural.rs:248–271
impl QueryBody {
/// The body's rule core: its `rule`, `utils`, and `constraints`.
pub(crate) fn rule_core(&self) -> Map<String, Value> {
let mut core = Map::new();
core.insert("rule".to_owned(), self.rule.clone());
if let Some(utils) = &self.utils {
core.insert("utils".to_owned(), utils.clone());
}
if let Some(constraints) = &self.constraints {
core.insert("constraints".to_owned(), constraints.clone());
}
core
}
/// Whether a project-relative source is searched under `paths` and
/// `exclude`.
pub(crate) fn searches(&self, file: &Path) -> bool {
let under = |entry: &String| file.starts_with(Path::new(entry.trim_end_matches('/')));
self.paths
.as_ref()
.is_none_or(|paths| paths.iter().any(under))
&& !self.exclude.iter().any(under)
}
}
Input 19: outline src/structural.rs fn[query_matches]
- File:
src/structural.rs - Selector:
fn[query_matches] - Kind:
fn src/structural.rs:452–530
/// Every match of a declared query, with its site, in path and source
/// order, as [`query_sites`] finds them.
pub(crate) fn query_matches(
root: &Path,
files: &[PathBuf],
outlines: &OutlineCache,
queries: &[DeclaredQuery],
name: &str,
) -> Result<Vec<QueryMatch>, String> {
let query = queries
.iter()
.find(|query| query.name == name)
.ok_or_else(|| format!("no query named {name:?}"))?;
let within = match within_query(queries, query)? {
None => None,
Some(target) => {
let mut sites = BTreeMap::<String, Vec<String>>::new();
for site in query_sites(root, files, outlines, queries, &target.name)? {
sites.entry(site.file).or_default().push(site.item);
}
Some(sites)
}
};
let rule = StructuralRule::compile(&query.body.language, &query.body.rule_core())
.map_err(|error| format!("{name}: {error}"))?;
let canonical = fs::canonicalize(root).unwrap_or_else(|_| root.to_owned());
let mut sources = files
.iter()
.filter_map(|file| {
let relative = file
.strip_prefix(&canonical)
.or_else(|_| file.strip_prefix(root))
.unwrap_or(file);
(rule.language().covers(file) && query.body.searches(relative))
.then(|| (relative.to_string_lossy().into_owned(), file))
})
.collect::<Vec<_>>();
sources.sort();
let mut found = Vec::new();
for (relative, file) in sources {
if within
.as_ref()
.is_some_and(|within| !within.contains_key(&relative))
{
continue;
}
let text =
fs::read_to_string(file).map_err(|error| format!("cannot read {relative}: {error}"))?;
let ranges = rule.matches(&text);
if ranges.is_empty() {
continue;
}
let parsed = outlines.parse(root, &relative);
let parsed = parsed.as_ref().as_ref().map_err(Clone::clone)?;
let within_nodes = within.as_ref().map(|within| {
let selected = &within[&relative];
(0..parsed.outline.nodes.len())
.filter(|index| selected.contains(&parsed.outline.nodes[*index].selector))
.collect::<Vec<_>>()
});
let line_of = |byte: usize| text[..byte].matches('\n').count() + 1;
for range in ranges {
let Some(index) = owning_site(&parsed.outline, &text, &range, within_nodes.as_deref())
else {
continue;
};
found.push(QueryMatch {
site: Site {
file: relative.clone(),
item: parsed.outline.nodes[index].selector.clone(),
},
line_start: line_of(range.start),
line_end: line_of(range.end.saturating_sub(1).max(range.start)),
text: text[range].to_owned(),
});
}
}
Ok(found)
}
Input 20: outline src/structural.rs fn[parse_queries]
- File:
src/structural.rs - Selector:
fn[parse_queries] - Kind:
fn src/structural.rs:305–359
/// The well-formed queries a requirement declaration contains, in
/// declaration order, and a problem for each malformed one.
// {impl}`requirements.ci.errors`
pub(crate) fn parse_queries(declaration: &Declaration) -> (Vec<DeclaredQuery>, Vec<String>) {
let lines = &declaration.raw_lines;
let mut queries = Vec::new();
let mut errors = Vec::new();
let mut index = 1;
while index < lines.len() {
let Some((fence, kind, name)) = query_fence(&lines[index]) else {
index += 1;
continue;
};
let line = declaration.line_start + index;
let Some(close) = lines[index + 1..]
.iter()
.position(|candidate| candidate.trim_end() == fence)
.map(|offset| index + 1 + offset)
else {
errors.push(format!(
"{}:{line}: query {name} is not closed",
declaration.file
));
// The rest of the declaration lies inside the unclosed directive,
// so no later query can be found in it.
break;
};
let body = lines[index + 1..close]
.iter()
.map(String::as_str)
.collect::<Vec<_>>();
index = close + 1;
let Some(yaml) = yaml_block(&body) else {
errors.push(format!(
"{}:{line}: query {name} must contain exactly one fenced yaml code block",
declaration.file
));
// Decoding the body needs its yaml block.
continue;
};
match serde_saphyr::from_str::<QueryBody>(&yaml) {
Ok(body) => queries.push(DeclaredQuery {
name: name.to_owned(),
kind,
body,
line,
}),
Err(error) => errors.push(format!(
"{}:{line}: query {name}: the yaml block must be a mapping of language, paths, exclude, rule, utils, constraints, within, match, and no_match: {error}",
declaration.file
)),
}
}
(queries, errors)
}
Input 21: outline src/structural.rs struct[QueryBody]
- File:
src/structural.rs - Selector:
struct[QueryBody] - Kind:
struct src/structural.rs:226–246
/// A query body: one `yaml` block of a `{sites}` or `{violations}`
/// directive.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct QueryBody {
pub(crate) language: String,
#[serde(default)]
pub(crate) paths: Option<Vec<String>>,
#[serde(default)]
pub(crate) exclude: Vec<String>,
pub(crate) rule: Value,
#[serde(default)]
pub(crate) utils: Option<Value>,
#[serde(default)]
pub(crate) constraints: Option<Value>,
#[serde(default)]
pub(crate) within: Option<String>,
#[serde(rename = "match")]
pub(crate) matches: Vec<String>,
pub(crate) no_match: Vec<String>,
}
Input 22: outline src/structural.rs fn[within_query]
- File:
src/structural.rs - Selector:
fn[within_query] - Kind:
fn src/structural.rs:532–550
/// The site query a query's matches must lie within: none for a site
/// query, and the `within` target, which must be a site query of the same
/// requirement, for a violation query.
pub(crate) fn within_query<'a>(
queries: &'a [DeclaredQuery],
query: &DeclaredQuery,
) -> Result<Option<&'a DeclaredQuery>, String> {
let name = &query.name;
match (query.kind, &query.body.within) {
(QueryKind::Sites, None) => Ok(None),
(QueryKind::Sites, Some(_)) => Err(format!("site query {name} must not have within")),
(QueryKind::Violations, None) => Err(format!("violation query {name} must have within")),
(QueryKind::Violations, Some(within)) => queries
.iter()
.find(|query| &query.name == within && query.kind == QueryKind::Sites)
.map(Some)
.ok_or_else(|| format!("{name}: within names no site query {within:?}")),
}
}
Input 24: outline src/sites.rs fn[validate_queries]
- File:
src/sites.rs - Selector:
fn[validate_queries] - Kind:
fn src/sites.rs:300–397
/// Reports the problems of a requirement's well-formed queries and returns
/// the names of those that can run: each name must be a unique identifier
/// segment, a violation query needs a site query to lie `within`, each rule
/// must compile, and each `match` snippet must contain a match and each
/// `no_match` snippet none.
// {impl}`requirements.ci.errors`
fn validate_queries<'a>(
name: &str,
declaration: &Declaration,
queries: &'a [DeclaredQuery],
errors: &mut Vec<String>,
) -> Vec<&'a DeclaredQuery> {
let mut valid = BTreeSet::new();
let mut seen = BTreeSet::new();
let mut runnable = Vec::new();
let has_sites = queries.iter().any(|query| query.kind == QueryKind::Sites);
for query in queries {
let location = format!("{}:{}", declaration.file, query.line);
let mut problems = Vec::new();
if !crate::valid_name(&query.name) || query.name.contains('.') {
problems.push(format!(
"query name {:?} must be a single identifier segment of ASCII letters, digits, underscores, or hyphens",
query.name
));
}
if !seen.insert(query.name.clone()) {
problems.push(format!(
"query name {} is declared more than once in {name}",
query.name
));
}
if query.kind == QueryKind::Violations && !has_sites {
problems.push(format!(
"{name} has a violation query, so it must also have a site query"
));
}
if let Err(error) = crate::structural::within_query(queries, query) {
problems.push(error);
}
if let Err(error) = crate::structural::StructuralRule::compile(
&query.body.language,
&query.body.rule_core(),
) {
problems.push(error);
}
for (field, snippets) in [
("match", &query.body.matches),
("no_match", &query.body.no_match),
] {
if snippets.is_empty() {
problems.push(format!("{field} must be a nonempty list of snippets"));
}
}
for problem in &problems {
errors.push(format!(
"{location}: query {} of {name}: {problem}",
query.name
));
}
if problems.is_empty() {
valid.insert(query.name.clone());
runnable.push(query);
}
}
// A violation query runs only when the site query it lies within does.
runnable.retain(|query| {
query
.body
.within
.as_ref()
.is_none_or(|within| valid.contains(within))
});
for query in &runnable {
let location = format!("{}:{}", declaration.file, query.line);
for (field, snippets, expect_match) in [
("match", &query.body.matches, true),
("no_match", &query.body.no_match, false),
] {
for (index, snippet) in snippets.iter().enumerate() {
let problem = match crate::structural::snippet_matches(queries, query, snippet) {
Err(error) => Some(error),
Ok(0) if expect_match => Some("contains no match of the query".to_owned()),
Ok(count) if !expect_match && count > 0 => {
Some(format!("contains {count} matches of the query"))
}
Ok(_) => None,
};
if let Some(problem) = problem {
errors.push(format!(
"{location}: query {} of {name}: {field}[{index}] snippet {problem}",
query.name
));
}
}
}
}
runnable
}