From a5c3c0a9c4002cb2577ef9b4a97547eea9ed80c2 Mon Sep 17 00:00:00 2001 From: Peter Krenesky Date: Fri, 4 Dec 2026 10:46:17 -0800 Subject: [PATCH 1/2] [PLAT-1901] Present tag-check findings by kind with symbol and reason chain Co-Authored-By: Claude Sonnet 5.5 --- docs/how-to-analyze-change-impact.md | 2 +- src/commands/impact.rs | 31 +-- src/commands/impact_tags.rs | 280 +++++++++++++++++++++++++++ src/commands/mod.rs | 1 + tests/cli_impact.rs | 194 +++++++++++++++++++ 5 files changed, 494 insertions(+), 14 deletions(-) create mode 100644 src/commands/impact_tags.rs diff --git a/docs/how-to-analyze-change-impact.md b/docs/how-to-analyze-change-impact.md index 4847a8b..a483089 100644 --- a/docs/how-to-analyze-change-impact.md +++ b/docs/how-to-analyze-change-impact.md @@ -36,7 +36,7 @@ HEAD=$(git -C "$REPO" rev-parse HEAD) --format json --check-tags ``` - The report then includes missing, invalid, unavailable, and non-binding link findings. To make any such finding fail the command, add `--fail-on-tag-findings`. That option requires `--check-tags`. + The report then includes missing, invalid, unavailable, and non-binding link findings. In JSON they are listed in `tag_check.entries`, each with its `kind` (`missing_link`, `invalid_id`, `unverifiable_id` or `non_binding_attribute`), path, the changed symbol and source line when they can be told, and a `reason_chain`. The human report prints one block per finding under the same four names. The check covers Rust sources only; a clean result says nothing about other languages. To make any such finding fail the command, add `--fail-on-tag-findings`. That option requires `--check-tags`. 3. **Compare a dependency move.** Pass the local upstream repository and the old and new revisions for each dependency move: diff --git a/src/commands/impact.rs b/src/commands/impact.rs index 2b34656..bb02c0c 100644 --- a/src/commands/impact.rs +++ b/src/commands/impact.rs @@ -10,13 +10,14 @@ use anyhow::{anyhow, Context, Result}; use clap::Parser; use ix_trace_rs::implements; use quire_rs::impact::{ - self, DependencyMoveInput, FileChange, ImpactFinding, ImpactInput, LineRange, SourceSnapshot, + self, DependencyMoveInput, FileChange, ImpactInput, LineRange, SourceSnapshot, }; #[cfg(test)] use quire_rs::Registry; use quire_rs::{Diagnostic, Spec}; use serde_json::Value; +use crate::commands::impact_tags::{self, is_tag_finding}; use crate::commands::Ctx; #[derive(Debug, Parser)] @@ -128,6 +129,9 @@ pub fn run(ctx: &Ctx, args: Args) -> Result<()> { caller_search_depth: args.caller_depth, })?; let tag_findings = report.findings.iter().any(is_tag_finding); + let tag_check = args + .check_tags + .then(|| impact_tags::tag_check(&report, &head)); if !args.check_tags { report.findings.retain(|finding| !is_tag_finding(finding)); } @@ -139,6 +143,9 @@ pub fn run(ctx: &Ctx, args: Args) -> Result<()> { if let Some(v) = object.remove("caller_searches") { object.insert("caller_search".into(), v); } + if let Some(check) = &tag_check { + object.insert("tag_check".into(), check.clone()); + } if !dependency_moves.is_empty() { object.insert( "dependency_moves".into(), @@ -188,9 +195,18 @@ pub fn run(ctx: &Ctx, args: Args) -> Result<()> { related.reason ); } - for finding in &report.findings { + for finding in report + .findings + .iter() + .filter(|finding| !is_tag_finding(finding)) + { primary_line!("Finding: {:?}\n", finding); } + if let Some(check) = &tag_check { + for line in impact_tags::render_human(check) { + primary_line!("{line}\n"); + } + } for unmapped in &report.unmapped_changes { primary_line!( "Unmapped {} {:?} lines {}-{}\n", @@ -275,17 +291,6 @@ pub fn run(ctx: &Ctx, args: Args) -> Result<()> { Ok(()) } -#[implements("FR-049-AC-5")] -fn is_tag_finding(finding: &ImpactFinding) -> bool { - matches!( - finding, - ImpactFinding::UnlinkedSymbol { .. } - | ImpactFinding::UnresolvedId { .. } - | ImpactFinding::UnavailableSpecification { .. } - | ImpactFinding::NonBindingMarker { .. } - ) -} - #[implements("FR-049-AC-5")] fn unavailable_spec_ids(spec: &Spec) -> BTreeSet { spec.diagnostics() diff --git a/src/commands/impact_tags.rs b/src/commands/impact_tags.rs new file mode 100644 index 0000000..dbe7f75 --- /dev/null +++ b/src/commands/impact_tags.rs @@ -0,0 +1,280 @@ +//! Presentation of the requirement-link findings that quire-rs FR-099 returns for +//! `quire impact --check-tags` (FR-049-AC-5). +//! +//! The engine decides what each finding is. This module only separates the four +//! kinds, names the changed symbol a finding concerns and writes the reason chain +//! in words. It does not bind attributes or resolve specification ids. + +use ix_trace_rs::implements; +use quire_rs::impact::{ChangedSymbol, ImpactFinding, ImpactReport, RevisionSide, SourceSnapshot}; +use serde_json::{json, Value}; + +/// What the tag check covers, shown so a clean result is not read as wider than it is. +pub const COVERAGE: &str = "Rust sources only; changes to other languages are reported as unsupported findings and are not tag-checked"; + +/// The distinct kinds of requirement-link finding, in the order they are shown. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] +enum Kind { + MissingLink, + InvalidId, + UnverifiableId, + NonBindingAttribute, +} + +impl Kind { + fn name(self) -> &'static str { + match self { + Kind::MissingLink => "missing_link", + Kind::InvalidId => "invalid_id", + Kind::UnverifiableId => "unverifiable_id", + Kind::NonBindingAttribute => "non_binding_attribute", + } + } + + fn label(self) -> &'static str { + match self { + Kind::MissingLink => "Missing link", + Kind::InvalidId => "Invalid id", + Kind::UnverifiableId => "Unverifiable id", + Kind::NonBindingAttribute => "Non-binding attribute", + } + } +} + +/// Whether an engine finding belongs to the tag check. +#[implements("FR-049-AC-5")] +pub fn is_tag_finding(finding: &ImpactFinding) -> bool { + kind_of(finding).is_some() +} + +fn kind_of(finding: &ImpactFinding) -> Option { + match finding { + ImpactFinding::UnlinkedSymbol { .. } => Some(Kind::MissingLink), + ImpactFinding::UnresolvedId { .. } => Some(Kind::InvalidId), + ImpactFinding::UnavailableSpecification { .. } => Some(Kind::UnverifiableId), + ImpactFinding::NonBindingMarker { .. } => Some(Kind::NonBindingAttribute), + _ => None, + } +} + +/// The `tag_check` section of the machine-readable report: one entry per finding, +/// ordered by kind, path, id and line. +#[implements("FR-049-AC-5")] +pub fn tag_check(report: &ImpactReport, head: &SourceSnapshot) -> Value { + let mut entries: Vec<(Kind, Value)> = report + .findings + .iter() + .filter_map(|finding| entry(finding, &report.changed_symbols, head)) + .collect(); + entries.sort_by(|(a_kind, a), (b_kind, b)| { + let key = |kind: &Kind, value: &Value| { + ( + *kind, + value["path"].as_str().unwrap_or_default().to_owned(), + value["trace_id"].as_str().unwrap_or_default().to_owned(), + value["line"].as_u64().unwrap_or_default(), + value["symbol"].as_str().unwrap_or_default().to_owned(), + ) + }; + key(a_kind, a).cmp(&key(b_kind, b)) + }); + json!({ + "coverage": COVERAGE, + "entries": entries.into_iter().map(|(_, value)| value).collect::>(), + }) +} + +fn entry( + finding: &ImpactFinding, + changed: &[ChangedSymbol], + head: &SourceSnapshot, +) -> Option<(Kind, Value)> { + let kind = kind_of(finding)?; + let value = match finding { + ImpactFinding::UnlinkedSymbol { + path, + symbol, + changed_lines, + } => json!({ + "kind": kind.name(), + "path": path, + "symbol": symbol, + "lines": {"start": changed_lines.start, "end": changed_lines.end}, + "reason_chain": [ + format!("{path}#{symbol} changed on lines {}-{}", changed_lines.start, changed_lines.end), + "the symbol has no requirement link bound by the declared implements markers".to_owned(), + ], + }), + ImpactFinding::UnresolvedId { path, trace_id } => { + let place = locate(head, changed, path, trace_id, None); + with_place( + json!({ + "kind": kind.name(), + "path": path, + "trace_id": trace_id, + "reason_chain": [ + format!("{path} names {trace_id}"), + format!("no specification artifact has the id {trace_id}"), + ], + }), + place, + ) + } + ImpactFinding::UnavailableSpecification { path, trace_id } => { + let place = locate(head, changed, path, trace_id, None); + with_place( + json!({ + "kind": kind.name(), + "path": path, + "trace_id": trace_id, + "reason_chain": [ + format!("{path} names {trace_id}"), + format!("the specification that holds {trace_id} could not be read, so the id cannot be verified"), + ], + }), + place, + ) + } + ImpactFinding::NonBindingMarker { + path, + trace_id, + line, + } => { + let place = locate(head, changed, path, trace_id, Some(*line)); + let mut value = with_place( + json!({ + "kind": kind.name(), + "path": path, + "trace_id": trace_id, + "reason_chain": [ + format!("{path} line {line} carries {trace_id} in an attribute"), + "the attribute binds no implementation relation to a changed symbol (for example a path-qualified attribute or one the declared grammar does not bind)".to_owned(), + ], + }), + place, + ); + value["line"] = json!(line); + value + } + _ => return None, + }; + Some((kind, value)) +} + +/// Adds the located symbol and source line, when found. +fn with_place(mut value: Value, place: Option) -> Value { + if let Some(place) = place { + value["line"] = json!(place.line); + value["source_line"] = json!(place.source_line); + if let Some(symbol) = place.symbol { + value["symbol"] = json!(symbol); + } + } + value +} + +struct Place { + line: usize, + source_line: String, + symbol: Option, +} + +/// Finds the head-side source line that names `trace_id` (the engine's `line` when +/// it gave one) and the changed head symbol that contains it or starts next. +fn locate( + head: &SourceSnapshot, + changed: &[ChangedSymbol], + path: &str, + trace_id: &str, + engine_line: Option, +) -> Option { + let text = head.files.get(path)?; + let mut symbols: Vec<&ChangedSymbol> = changed + .iter() + .filter(|symbol| symbol.side == RevisionSide::Head && symbol.path == path) + .collect(); + symbols.sort_by_key(|symbol| (symbol.lines.start, symbol.name.clone())); + let symbol_at = |line: usize| { + symbols + .iter() + .find(|symbol| symbol.lines.start <= line && line <= symbol.lines.end) + .or_else(|| symbols.iter().find(|symbol| symbol.lines.start >= line)) + .map(|symbol| symbol.name.clone()) + }; + let quoted = format!("\"{trace_id}\""); + let candidates = text + .lines() + .enumerate() + .map(|(index, text)| (index + 1, text)) + .filter(|(line, text)| match engine_line { + Some(wanted) => *line == wanted, + None => text.contains("ed) || text.contains(trace_id), + }); + let mut first = None; + for (line, source) in candidates { + let symbol = symbol_at(line); + let place = Place { + line, + source_line: source.trim().to_owned(), + symbol, + }; + if place.symbol.is_some() { + return Some(place); + } + first.get_or_insert(place); + } + first +} + +/// Writes the human-readable tag check section. +#[implements("FR-049-AC-5")] +pub fn render_human(check: &Value) -> Vec { + let mut lines = Vec::new(); + lines.push(format!("Tag check scope: {COVERAGE}")); + let entries = check["entries"] + .as_array() + .map(Vec::as_slice) + .unwrap_or(&[]); + if entries.is_empty() { + lines.push("Tag check: no findings".to_owned()); + return lines; + } + for entry in entries { + let text = |key: &str| entry[key].as_str().unwrap_or(""); + let kind = match text("kind") { + "missing_link" => Kind::MissingLink, + "invalid_id" => Kind::InvalidId, + "unverifiable_id" => Kind::UnverifiableId, + _ => Kind::NonBindingAttribute, + }; + let head = match kind { + Kind::MissingLink => format!("{}: {}#{}", kind.label(), text("path"), text("symbol")), + Kind::InvalidId | Kind::UnverifiableId => { + format!("{}: {} in {}", kind.label(), text("trace_id"), text("path")) + } + Kind::NonBindingAttribute => format!( + "{}: {} at {}:{}", + kind.label(), + text("trace_id"), + text("path"), + entry["line"] + ), + }; + lines.push(head); + if kind != Kind::MissingLink { + if let Some(symbol) = entry["symbol"].as_str() { + lines.push(format!(" Affected changed symbol: {symbol}")); + } + if let Some(source) = entry["source_line"].as_str() { + lines.push(format!(" Source: {source}")); + } + } + for reason in entry["reason_chain"].as_array().into_iter().flatten() { + lines.push(format!( + " Because: {}", + reason.as_str().unwrap_or("") + )); + } + } + lines +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index 9be0cad..747ead5 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -46,6 +46,7 @@ pub mod export; pub mod extract; pub mod fix; pub mod impact; +mod impact_tags; pub mod lint; pub mod lookup; pub mod matrix; diff --git a/tests/cli_impact.rs b/tests/cli_impact.rs index 8b309cd..a55c3a0 100644 --- a/tests/cli_impact.rs +++ b/tests/cli_impact.rs @@ -649,3 +649,197 @@ fn it_impact_reports_dependency_move_chain_and_unavailable_upstream() { .contains("base")); assert!(movement["upstream_changes"].as_array().unwrap().is_empty()); } + +/// Commits `source` as `src/lib.rs` on top of the fixture and returns the repository +/// with that commit as its head. +fn with_head_source(mut repo: Repo, source: &str) -> Repo { + let root = repo.dir.path(); + write(root, "src/lib.rs", source); + git(root, &["add", "-A"]); + git(root, &["commit", "-q", "-m", "tag fixture"]); + repo.head = git(root, &["rev-parse", "HEAD"]); + repo +} + +const LINKED_TARGET: &str = "#[implements(\"FR-900-AC-1\")]\npub fn target() { let _value = 2; }\n\ + #[implements(\"FR-900-AC-1\")]\npub fn sibling() {}\n"; + +/// Runs the tag check and returns its `tag_check` entries and the whole process output. +fn tag_check(repo: &Repo, extra: &[&str]) -> (Vec, std::process::Output) { + let mut args = vec!["--check-tags"]; + args.extend_from_slice(extra); + let output = run(repo, "json", &args); + let report: Value = serde_json::from_slice(&output.stdout).expect("impact JSON"); + let entries = report["tag_check"]["entries"] + .as_array() + .unwrap_or_else(|| panic!("tag_check.entries missing: {report}")) + .clone(); + (entries, output) +} + +fn only_kind(entries: &[Value], kind: &str) -> Value { + assert_eq!(entries.len(), 1, "exactly one entry expected: {entries:?}"); + assert_eq!(entries[0]["kind"], kind, "{entries:?}"); + entries[0].clone() +} + +fn one_of_kind(entries: &[Value], kind: &str) -> Value { + let matching: Vec<&Value> = entries + .iter() + .filter(|entry| entry["kind"] == kind) + .collect(); + assert_eq!( + matching.len(), + 1, + "exactly one {kind} entry expected: {entries:?}" + ); + matching[0].clone() +} + +#[test] +#[trace("FR-049-AC-5")] +fn it_impact_tag_check_presents_a_missing_link_with_its_symbol_and_reason() { + let repo = with_head_source( + repository(false), + &format!("{LINKED_TARGET}pub fn missing_link() {{ let _value = 4; }}\n"), + ); + let (entries, _) = tag_check(&repo, &[]); + let entry = only_kind(&entries, "missing_link"); + assert_eq!(entry["path"], "src/lib.rs"); + assert_eq!(entry["symbol"], "missing_link"); + assert!(entry["reason_chain"] + .to_string() + .contains("no requirement link")); + + let human = run(&repo, "human", &["--check-tags"]); + let human = String::from_utf8_lossy(&human.stdout); + assert!( + human.contains("Missing link: src/lib.rs#missing_link"), + "{human}" + ); + assert!(human.contains("Rust sources only"), "{human}"); +} + +#[test] +#[trace("FR-049-AC-5")] +fn it_impact_tag_check_presents_an_invalid_id() { + let repo = with_head_source( + repository(false), + &format!("{LINKED_TARGET}#[implements(\"FR-999-AC-1\")]\npub fn invalid_link() {{ let _value = 5; }}\n"), + ); + let (entries, _) = tag_check(&repo, &[]); + let entry = only_kind(&entries, "invalid_id"); + assert_eq!(entry["trace_id"], "FR-999-AC-1"); + assert_eq!(entry["path"], "src/lib.rs"); + assert!(entry["reason_chain"] + .to_string() + .contains("no specification artifact")); + + let human = run(&repo, "human", &["--check-tags"]); + let human = String::from_utf8_lossy(&human.stdout); + assert!( + human.contains("Invalid id: FR-999-AC-1 in src/lib.rs"), + "{human}" + ); +} + +#[test] +#[trace("FR-049-AC-5")] +fn it_impact_tag_check_presents_an_unverifiable_id() { + let repo = repository(false); + write( + repo.dir.path(), + "spec/FR-901-AC-1.md", + "This document has no frontmatter.\n", + ); + let repo = with_head_source( + repo, + &format!("{LINKED_TARGET}#[implements(\"FR-901-AC-1\")]\npub fn unavailable_link() {{ let _value = 6; }}\n"), + ); + let (entries, _) = tag_check(&repo, &[]); + let entry = only_kind(&entries, "unverifiable_id"); + assert_eq!(entry["trace_id"], "FR-901-AC-1"); + assert!(entry["reason_chain"] + .to_string() + .contains("could not be read")); + + let human = run(&repo, "human", &["--check-tags"]); + let human = String::from_utf8_lossy(&human.stdout); + assert!( + human.contains("Unverifiable id: FR-901-AC-1 in src/lib.rs"), + "{human}" + ); +} + +#[test] +#[trace("FR-049-AC-5")] +fn it_impact_tag_check_presents_non_binding_attributes_including_path_qualified() { + let repo = with_head_source( + repository(false), + &format!( + "{LINKED_TARGET}#[trace(\"FR-900-AC-1\")]\npub fn nonbinding_link() {{ let _value = 7; }}\n" + ), + ); + let (entries, _) = tag_check(&repo, &[]); + let entry = one_of_kind(&entries, "non_binding_attribute"); + assert_eq!( + one_of_kind(&entries, "missing_link")["symbol"], + "nonbinding_link" + ); + assert_eq!(entry["trace_id"], "FR-900-AC-1"); + assert_eq!(entry["symbol"], "nonbinding_link"); + assert_eq!(entry["source_line"], "#[trace(\"FR-900-AC-1\")]"); + + let human = run(&repo, "human", &["--check-tags"]); + let human = String::from_utf8_lossy(&human.stdout); + assert!( + human.contains("Non-binding attribute: FR-900-AC-1 at src/lib.rs:"), + "{human}" + ); + + let qualified = with_head_source( + repository(false), + &format!( + "{LINKED_TARGET}#[ix_trace_rs::implements(\"FR-900-AC-1\")]\npub fn qualified_link() {{ let _value = 8; }}\n" + ), + ); + let (entries, _) = tag_check(&qualified, &[]); + let entry = one_of_kind(&entries, "non_binding_attribute"); + assert_eq!( + one_of_kind(&entries, "missing_link")["symbol"], + "qualified_link" + ); + assert_eq!(entry["symbol"], "qualified_link"); + assert_eq!( + entry["source_line"], + "#[ix_trace_rs::implements(\"FR-900-AC-1\")]" + ); +} + +#[test] +#[trace("FR-049-AC-5")] +fn it_impact_tag_check_clean_fixture_has_no_entries_and_passes_the_failing_option() { + let repo = with_head_source( + repository(false), + &LINKED_TARGET.replace("_value = 2", "_value = 3"), + ); + let (entries, output) = tag_check(&repo, &["--fail-on-tag-findings"]); + assert!(entries.is_empty(), "{entries:?}"); + assert!(output.status.success()); + + let human = run(&repo, "human", &["--check-tags"]); + let human = String::from_utf8_lossy(&human.stdout); + assert!(human.contains("Tag check: no findings"), "{human}"); +} + +#[test] +#[trace("FR-049-AC-5")] +fn it_impact_tag_check_output_is_absent_without_the_option() { + let repo = with_head_source( + repository(false), + &format!("{LINKED_TARGET}pub fn missing_link() {{ let _value = 4; }}\n"), + ); + let output = run(&repo, "json", &[]); + let report: Value = serde_json::from_slice(&output.stdout).expect("impact JSON"); + assert!(report.get("tag_check").is_none()); +} From a7986458b90845ce53ca3043398335aba4cd2e8f Mon Sep 17 00:00:00 2001 From: Peter Krenesky Date: Fri, 4 Dec 2026 11:22:26 -0800 Subject: [PATCH 2/2] fix(impact): locate tag findings on head symbols only, dedupe entries Co-Authored-By: Claude Sonnet 5.5 --- src/commands/impact_tags.rs | 291 ++++++++++++++++++++++++------------ tests/cli_impact.rs | 113 ++++++++++++++ 2 files changed, 305 insertions(+), 99 deletions(-) diff --git a/src/commands/impact_tags.rs b/src/commands/impact_tags.rs index dbe7f75..eb84198 100644 --- a/src/commands/impact_tags.rs +++ b/src/commands/impact_tags.rs @@ -57,15 +57,19 @@ fn kind_of(finding: &ImpactFinding) -> Option { } } -/// The `tag_check` section of the machine-readable report: one entry per finding, -/// ordered by kind, path, id and line. +/// The `tag_check` section of the machine-readable report: one entry per distinct +/// finding, ordered by kind, path, id and line. #[implements("FR-049-AC-5")] pub fn tag_check(report: &ImpactReport, head: &SourceSnapshot) -> Value { - let mut entries: Vec<(Kind, Value)> = report - .findings - .iter() - .filter_map(|finding| entry(finding, &report.changed_symbols, head)) - .collect(); + let mut entries: Vec<(Kind, Value)> = Vec::new(); + for finding in &report.findings { + for found in entry(finding, &report.changed_symbols, head) { + // The engine reports both revision sides, so identical entries are shown once. + if !entries.contains(&found) { + entries.push(found); + } + } + } entries.sort_by(|(a_kind, a), (b_kind, b)| { let key = |kind: &Kind, value: &Value| { ( @@ -84,18 +88,23 @@ pub fn tag_check(report: &ImpactReport, head: &SourceSnapshot) -> Value { }) } +/// The entries for one engine finding. An id named by several changed symbols gives +/// one entry per symbol rather than a silent pick of the first. fn entry( finding: &ImpactFinding, changed: &[ChangedSymbol], head: &SourceSnapshot, -) -> Option<(Kind, Value)> { - let kind = kind_of(finding)?; - let value = match finding { +) -> Vec<(Kind, Value)> { + let Some(kind) = kind_of(finding) else { + return Vec::new(); + }; + let with_kind = |value: Value| (kind, value); + match finding { ImpactFinding::UnlinkedSymbol { path, symbol, changed_lines, - } => json!({ + } => vec![with_kind(json!({ "kind": kind.name(), "path": path, "symbol": symbol, @@ -104,61 +113,59 @@ fn entry( format!("{path}#{symbol} changed on lines {}-{}", changed_lines.start, changed_lines.end), "the symbol has no requirement link bound by the declared implements markers".to_owned(), ], - }), + }))], ImpactFinding::UnresolvedId { path, trace_id } => { - let place = locate(head, changed, path, trace_id, None); - with_place( - json!({ - "kind": kind.name(), - "path": path, - "trace_id": trace_id, - "reason_chain": [ - format!("{path} names {trace_id}"), - format!("no specification artifact has the id {trace_id}"), - ], - }), - place, - ) + let base = json!({ + "kind": kind.name(), + "path": path, + "trace_id": trace_id, + "reason_chain": [ + format!("{path} names {trace_id}"), + format!("no specification artifact has the id {trace_id}"), + ], + }); + places_for_id(head, changed, path, trace_id) + .into_iter() + .map(|place| with_kind(with_place(base.clone(), place))) + .collect() } ImpactFinding::UnavailableSpecification { path, trace_id } => { - let place = locate(head, changed, path, trace_id, None); - with_place( - json!({ - "kind": kind.name(), - "path": path, - "trace_id": trace_id, - "reason_chain": [ - format!("{path} names {trace_id}"), - format!("the specification that holds {trace_id} could not be read, so the id cannot be verified"), - ], - }), - place, - ) + let base = json!({ + "kind": kind.name(), + "path": path, + "trace_id": trace_id, + "reason_chain": [ + format!("{path} names {trace_id}"), + format!("the specification that holds {trace_id} could not be read, so the id cannot be verified"), + ], + }); + places_for_id(head, changed, path, trace_id) + .into_iter() + .map(|place| with_kind(with_place(base.clone(), place))) + .collect() } ImpactFinding::NonBindingMarker { path, trace_id, line, } => { - let place = locate(head, changed, path, trace_id, Some(*line)); - let mut value = with_place( - json!({ - "kind": kind.name(), - "path": path, - "trace_id": trace_id, - "reason_chain": [ - format!("{path} line {line} carries {trace_id} in an attribute"), - "the attribute binds no implementation relation to a changed symbol (for example a path-qualified attribute or one the declared grammar does not bind)".to_owned(), - ], - }), - place, - ); - value["line"] = json!(line); - value + let place = locate_marker(head, changed, path, trace_id, *line); + let value = json!({ + "kind": kind.name(), + "path": path, + "trace_id": trace_id, + "reason_chain": [ + match &place { + Some(place) => format!("{path} line {} carries {trace_id} in an attribute", place.line), + None => format!("{path} carries {trace_id} in an attribute"), + }, + "the attribute binds no implementation relation to a changed symbol (for example a path-qualified attribute or one the declared grammar does not bind)".to_owned(), + ], + }); + vec![with_kind(with_place(value, place))] } - _ => return None, - }; - Some((kind, value)) + _ => Vec::new(), + } } /// Adds the located symbol and source line, when found. @@ -179,51 +186,131 @@ struct Place { symbol: Option, } -/// Finds the head-side source line that names `trace_id` (the engine's `line` when -/// it gave one) and the changed head symbol that contains it or starts next. -fn locate( +/// Changed head symbols on `path`, ordered by position and name. +fn head_symbols<'a>(changed: &'a [ChangedSymbol], path: &str) -> Vec<&'a ChangedSymbol> { + let mut symbols: Vec<&ChangedSymbol> = changed + .iter() + .filter(|symbol| symbol.side == RevisionSide::Head && symbol.path == path) + .collect(); + symbols.sort_by_key(|symbol| (symbol.lines.start, symbol.name.clone())); + symbols +} + +/// The first line of the attribute and comment block directly above `symbol`. +fn block_start(lines: &[&str], symbol: &ChangedSymbol) -> usize { + let mut start = symbol.lines.start.max(1); + while start > 1 { + let above = lines.get(start - 2).map(|line| line.trim()).unwrap_or(""); + if above.starts_with("#[") || above.starts_with("//") { + start -= 1; + } else { + break; + } + } + start +} + +/// Whether `source` names `trace_id` as a whole quoted id. +fn names_id(source: &str, trace_id: &str) -> bool { + source.contains(&format!("\"{trace_id}\"")) +} + +fn place_at(lines: &[&str], line: usize, symbol: Option<&ChangedSymbol>) -> Place { + Place { + line, + source_line: lines[line - 1].trim().to_owned(), + symbol: symbol.map(|symbol| symbol.name.clone()), + } +} + +/// The lines of `symbol`, with its attribute block, that name `trace_id`. +fn id_lines(lines: &[&str], symbol: &ChangedSymbol, trace_id: &str) -> Vec { + let end = symbol.lines.end.min(lines.len()); + (block_start(lines, symbol)..=end) + .filter(|line| *line >= 1 && names_id(lines[line - 1], trace_id)) + .collect() +} + +/// Places for an id the engine could not resolve or verify. The changed head +/// symbols whose bound ids contain it are the answer, one place each; only when +/// no symbol binds it is the head text searched for a single whole-id mention. +fn places_for_id( + head: &SourceSnapshot, + changed: &[ChangedSymbol], + path: &str, + trace_id: &str, +) -> Vec> { + let Some(text) = head.files.get(path) else { + return vec![None]; + }; + let lines: Vec<&str> = text.lines().collect(); + let bound: Vec<&ChangedSymbol> = head_symbols(changed, path) + .into_iter() + .filter(|symbol| symbol.implemented_ids.iter().any(|id| id == trace_id)) + .collect(); + if !bound.is_empty() { + return bound + .into_iter() + .map(|symbol| { + let line = id_lines(&lines, symbol, trace_id) + .first() + .copied() + .unwrap_or_else(|| symbol.lines.start.max(1)); + (line <= lines.len()).then(|| place_at(&lines, line, Some(symbol))) + }) + .collect(); + } + let mentions: Vec = (1..=lines.len()) + .filter(|line| names_id(lines[line - 1], trace_id)) + .collect(); + match mentions.as_slice() { + [line] => { + let symbol = head_symbols(changed, path) + .into_iter() + .find(|symbol| id_lines(&lines, symbol, trace_id).contains(line)); + vec![Some(place_at(&lines, *line, symbol))] + } + _ => vec![None], + } +} + +/// Places a non-binding attribute in the head file. The engine reports markers on +/// both revision sides without saying which, so its line is used only when the head +/// text at that line is an attribute naming the id; otherwise the head is searched +/// for a single such attribute inside a changed symbol. No place is invented. +fn locate_marker( head: &SourceSnapshot, changed: &[ChangedSymbol], path: &str, trace_id: &str, - engine_line: Option, + engine_line: usize, ) -> Option { let text = head.files.get(path)?; - let mut symbols: Vec<&ChangedSymbol> = changed - .iter() - .filter(|symbol| symbol.side == RevisionSide::Head && symbol.path == path) - .collect(); - symbols.sort_by_key(|symbol| (symbol.lines.start, symbol.name.clone())); - let symbol_at = |line: usize| { + let lines: Vec<&str> = text.lines().collect(); + let symbols = head_symbols(changed, path); + let is_marker = |line: usize| { + line >= 1 && line <= lines.len() && { + let source = lines[line - 1].trim(); + source.starts_with("#[") && names_id(source, trace_id) + } + }; + let owner = |line: usize| { symbols .iter() - .find(|symbol| symbol.lines.start <= line && line <= symbol.lines.end) - .or_else(|| symbols.iter().find(|symbol| symbol.lines.start >= line)) - .map(|symbol| symbol.name.clone()) + .find(|symbol| id_lines(&lines, symbol, trace_id).contains(&line)) + .copied() }; - let quoted = format!("\"{trace_id}\""); - let candidates = text - .lines() - .enumerate() - .map(|(index, text)| (index + 1, text)) - .filter(|(line, text)| match engine_line { - Some(wanted) => *line == wanted, - None => text.contains("ed) || text.contains(trace_id), - }); - let mut first = None; - for (line, source) in candidates { - let symbol = symbol_at(line); - let place = Place { - line, - source_line: source.trim().to_owned(), - symbol, - }; - if place.symbol.is_some() { - return Some(place); - } - first.get_or_insert(place); + if is_marker(engine_line) { + return Some(place_at(&lines, engine_line, owner(engine_line))); + } + let candidates: Vec<(usize, &ChangedSymbol)> = (1..=lines.len()) + .filter(|line| is_marker(*line)) + .filter_map(|line| owner(line).map(|symbol| (line, symbol))) + .collect(); + match candidates.as_slice() { + [(line, symbol)] => Some(place_at(&lines, *line, Some(symbol))), + _ => None, } - first } /// Writes the human-readable tag check section. @@ -245,20 +332,26 @@ pub fn render_human(check: &Value) -> Vec { "missing_link" => Kind::MissingLink, "invalid_id" => Kind::InvalidId, "unverifiable_id" => Kind::UnverifiableId, - _ => Kind::NonBindingAttribute, + "non_binding_attribute" => Kind::NonBindingAttribute, + other => { + lines.push(format!("Unknown tag finding kind: {other}")); + continue; + } }; let head = match kind { Kind::MissingLink => format!("{}: {}#{}", kind.label(), text("path"), text("symbol")), Kind::InvalidId | Kind::UnverifiableId => { format!("{}: {} in {}", kind.label(), text("trace_id"), text("path")) } - Kind::NonBindingAttribute => format!( - "{}: {} at {}:{}", - kind.label(), - text("trace_id"), - text("path"), - entry["line"] - ), + Kind::NonBindingAttribute => match entry["line"].as_u64() { + Some(line) => format!( + "{}: {} at {}:{line}", + kind.label(), + text("trace_id"), + text("path") + ), + None => format!("{}: {} in {}", kind.label(), text("trace_id"), text("path")), + }, }; lines.push(head); if kind != Kind::MissingLink { diff --git a/tests/cli_impact.rs b/tests/cli_impact.rs index a55c3a0..577d164 100644 --- a/tests/cli_impact.rs +++ b/tests/cli_impact.rs @@ -731,6 +731,7 @@ fn it_impact_tag_check_presents_an_invalid_id() { let entry = only_kind(&entries, "invalid_id"); assert_eq!(entry["trace_id"], "FR-999-AC-1"); assert_eq!(entry["path"], "src/lib.rs"); + assert_eq!(entry["symbol"], "invalid_link"); assert!(entry["reason_chain"] .to_string() .contains("no specification artifact")); @@ -759,6 +760,7 @@ fn it_impact_tag_check_presents_an_unverifiable_id() { let (entries, _) = tag_check(&repo, &[]); let entry = only_kind(&entries, "unverifiable_id"); assert_eq!(entry["trace_id"], "FR-901-AC-1"); + assert_eq!(entry["symbol"], "unavailable_link"); assert!(entry["reason_chain"] .to_string() .contains("could not be read")); @@ -843,3 +845,114 @@ fn it_impact_tag_check_output_is_absent_without_the_option() { let report: Value = serde_json::from_slice(&output.stdout).expect("impact JSON"); assert!(report.get("tag_check").is_none()); } + +/// Commits `base_source` and then `head_source` as `src/lib.rs` on top of the fixture +/// and returns the repository with those two commits as its base and head. +fn with_base_and_head(repo: Repo, base_source: &str, head_source: &str) -> Repo { + let mut repo = with_head_source(repo, base_source); + repo.base = repo.head.clone(); + with_head_source(repo, head_source) +} + +fn of_kind(entries: &[Value], kind: &str) -> Vec { + entries + .iter() + .filter(|entry| entry["kind"] == kind) + .cloned() + .collect() +} + +fn symbols_of(entries: &[Value]) -> Vec { + entries + .iter() + .map(|entry| entry["symbol"].as_str().unwrap_or("").to_owned()) + .collect() +} + +#[test] +#[trace("FR-049-AC-5")] +fn it_impact_tag_check_never_reads_a_base_side_line_in_the_head_file() { + let base = "pub fn target() { let _value = 1; }\n\ + #[ix_trace_rs::implements(\"FR-900-AC-1\")]\n\ + pub fn moved() { let _value = 1; }\n"; + let head = "pub fn target() { let _value = 1; }\n\ + pub fn unrelated() { let _value = 2; }\n\ + pub fn pad() {}\n\ + pub fn pad_more() {}\n\ + #[ix_trace_rs::implements(\"FR-900-AC-1\")]\n\ + pub fn moved() { let _value = 2; }\n"; + let repo = with_base_and_head(repository(false), base, head); + let (entries, _) = tag_check(&repo, &[]); + let nonbinding = of_kind(&entries, "non_binding_attribute"); + assert_eq!(nonbinding.len(), 1, "{entries:?}"); + assert_eq!(nonbinding[0]["symbol"], "moved", "{entries:?}"); + assert_eq!(nonbinding[0]["line"], 5, "{entries:?}"); + assert_eq!( + nonbinding[0]["source_line"], + "#[ix_trace_rs::implements(\"FR-900-AC-1\")]" + ); +} + +#[test] +#[trace("FR-049-AC-5")] +fn it_impact_tag_check_names_the_changed_symbol_that_carries_the_invalid_id() { + let base = "#[implements(\"FR-999-AC-1\")]\npub fn a() {}\n\ + pub fn b() { let _value = 0; }\n\ + #[implements(\"FR-999-AC-1\")]\npub fn c() { let _value = 0; }\n"; + let head = "#[implements(\"FR-999-AC-1\")]\npub fn a() {}\n\ + pub fn b() { let _value = 1; }\n\ + #[implements(\"FR-999-AC-1\")]\npub fn c() { let _value = 1; }\n"; + let repo = with_base_and_head(repository(false), base, head); + let (entries, _) = tag_check(&repo, &[]); + let invalid = of_kind(&entries, "invalid_id"); + assert_eq!(symbols_of(&invalid), vec!["c"], "{entries:?}"); + assert_eq!(invalid[0]["line"], 4, "{entries:?}"); +} + +#[test] +#[trace("FR-049-AC-5")] +fn it_impact_tag_check_lists_every_changed_symbol_with_the_same_invalid_id() { + let base = "#[implements(\"FR-999-AC-1\")]\npub fn c() { let _value = 0; }\n\ + #[implements(\"FR-999-AC-1\")]\npub fn d() { let _value = 0; }\n"; + let head = "#[implements(\"FR-999-AC-1\")]\npub fn c() { let _value = 1; }\n\ + #[implements(\"FR-999-AC-1\")]\npub fn d() { let _value = 1; }\n"; + let repo = with_base_and_head(repository(false), base, head); + let (entries, _) = tag_check(&repo, &[]); + let invalid = of_kind(&entries, "invalid_id"); + assert_eq!(symbols_of(&invalid), vec!["c", "d"], "{entries:?}"); +} + +#[test] +#[trace("FR-049-AC-5")] +fn it_impact_tag_check_does_not_match_an_id_that_is_a_prefix_of_another() { + let base = "#[implements(\"FR-999-AC-10\")]\npub fn a() {}\n\ + pub fn b() { let _value = 0; }\n\ + #[implements(\"FR-999-AC-1\")]\npub fn c() { let _value = 0; }\n"; + let head = "#[implements(\"FR-999-AC-10\")]\npub fn a() {}\n\ + pub fn b() { let _value = 1; }\n\ + #[implements(\"FR-999-AC-1\")]\npub fn c() { let _value = 1; }\n"; + let repo = with_base_and_head(repository(false), base, head); + let (entries, _) = tag_check(&repo, &[]); + let short: Vec = of_kind(&entries, "invalid_id") + .into_iter() + .filter(|entry| entry["trace_id"] == "FR-999-AC-1") + .collect(); + assert_eq!(symbols_of(&short), vec!["c"], "{entries:?}"); + assert_eq!(short[0]["source_line"], "#[implements(\"FR-999-AC-1\")]"); +} + +#[test] +#[trace("FR-049-AC-5")] +fn it_impact_tag_check_presents_identical_findings_once() { + let base = "#[implements(\"FR-999-AC-1\")]\npub fn c() { let _value = 0; }\n\ + pub fn missing() { let _value = 0; }\n"; + let head = "#[implements(\"FR-999-AC-1\")]\npub fn c() { let _value = 1; }\n\ + pub fn missing() { let _value = 1; }\n"; + let repo = with_base_and_head(repository(false), base, head); + let (entries, _) = tag_check(&repo, &[]); + assert_eq!(of_kind(&entries, "missing_link").len(), 1, "{entries:?}"); + assert_eq!(of_kind(&entries, "invalid_id").len(), 1, "{entries:?}"); + let mut unique: Vec = entries.iter().map(Value::to_string).collect(); + unique.dedup(); + assert_eq!(unique.len(), entries.len(), "{entries:?}"); +}