From 6c6d087a18024707b3dc9dc106354385c3e90bfd Mon Sep 17 00:00:00 2001 From: Kirill Mokevnin Date: Wed, 18 Nov 2026 21:53:27 -0500 Subject: [PATCH 1/4] refactor: rename Edge to ComponentDep, and the flow's Edge to NodeDep The type that carries a dependency of one component on another was called `Edge`, a word GLOSSARY.md avoids for a dependency. It is `ComponentDep` now, with the variables, parameters and doc comments that hold one saying dependency, not edge or import. The flow's reference from one node to another, also an `Edge`, is `NodeDep`, and `Flow::edges` is `Flow::node_deps`. No behaviour, output or snapshot changes. Closes #218 Co-Authored-By: Claude Opus 5.5 --- src/chains.rs | 90 ++++++++++++------------ src/check.rs | 123 +++++++++++++++++++-------------- src/commands.rs | 14 ++-- src/diagram.rs | 55 ++++++++------- src/drift.rs | 2 +- src/flow.rs | 18 ++--- src/graph.rs | 79 ++++++++++++++------- src/init.rs | 8 ++- src/policy.rs | 10 ++- src/project.rs | 18 ++--- src/propose.rs | 125 +++++++++++++++++----------------- src/scip/mod.rs | 10 +-- src/scope.rs | 5 +- src/suggest.rs | 44 ++++++------ tests/library/aliases.rs | 2 +- tests/library/baseline.rs | 2 +- tests/library/commands.rs | 2 +- tests/library/declarations.rs | 8 +-- tests/library/plan.rs | 6 +- 19 files changed, 348 insertions(+), 273 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index 832a73cf..bdb2bf63 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -8,7 +8,7 @@ use pathfinding::NodeRefs; use pathfinding::directed::bfs::{bfs, bfs_loop}; use pathfinding::directed::strongly_connected_components::strongly_connected_components; -use crate::check::{Chain, Edge, Hop, Place, RuleId, Violation}; +use crate::check::{Chain, ComponentDep, Hop, Place, RuleId, Violation}; use crate::components::ComponentMap; use crate::config::{Config, Listed}; use crate::decision::{self, Refusal}; @@ -19,15 +19,15 @@ use crate::relpath::{self, slash}; /// Dependency cycles between the components covered by `no_cycles`: one /// violation per strongly connected group, with the shortest cycle through it. -pub fn cycles(config: &Config, edges: &[Edge]) -> Vec { - let covered: Vec<&Edge> = edges +pub fn cycles(config: &Config, component_deps: &[ComponentDep]) -> Vec { + let covered: Vec<&ComponentDep> = component_deps .iter() - .filter(|e| config.no_cycles.covers(&e.from) && config.no_cycles.covers(&e.to)) + .filter(|dep| config.no_cycles.covers(&dep.from) && config.no_cycles.covers(&dep.to)) .collect(); let mut graph: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); - for e in &covered { - graph.entry(&e.from).or_default().insert(&e.to); - graph.entry(&e.to).or_default(); + for dep in &covered { + graph.entry(&dep.from).or_default().insert(&dep.to); + graph.entry(&dep.to).or_default(); } let nodes: Vec<&str> = graph.keys().copied().collect(); let mut groups: Vec> = @@ -42,15 +42,15 @@ pub fn cycles(config: &Config, edges: &[Edge]) -> Vec { .map(|members| { let start = *members.first().expect("non-empty group"); let cycle = shortest_cycle(&graph, &members, start); - // The first import of each step of the cycle. - let steps: Vec<&&Edge> = cycle + // The first line that writes each step of the cycle. + let steps: Vec<&&ComponentDep> = cycle .windows(2) .map(|step| { covered .iter() - .filter(|e| e.from == step[0] && e.to == step[1]) + .filter(|dep| dep.from == step[0] && dep.to == step[1]) .min_by(|x, y| (&x.file, x.line).cmp(&(&y.file, y.line))) - .expect("cycle edge exists") + .expect("a step of the cycle is a dependency between components") }) .collect(); let first = steps[0]; @@ -67,8 +67,10 @@ pub fn cycles(config: &Config, edges: &[Edge]) -> Vec { }; let mut evidence: Vec = covered .iter() - .filter(|e| members.contains(e.from.as_str()) && members.contains(e.to.as_str())) - .map(|e| Place::new(e.file.clone(), e.line)) + .filter(|dep| { + members.contains(dep.from.as_str()) && members.contains(dep.to.as_str()) + }) + .map(|dep| Place::new(dep.file.clone(), dep.line)) .collect(); evidence.sort(); Violation { @@ -81,11 +83,11 @@ pub fn cycles(config: &Config, edges: &[Edge]) -> Vec { chain: Some(Chain::shortest( steps .iter() - .map(|e| Hop { - file: e.file.clone(), - line: e.line, - from_component: Some(e.from.clone()), - to_component: Some(e.to.clone()), + .map(|dep| Hop { + file: dep.file.clone(), + line: dep.line, + from_component: Some(dep.from.clone()), + to_component: Some(dep.to.clone()), }) .collect(), )), @@ -309,16 +311,16 @@ fn symbol_graph( let files = Files::new(files); let mut graph: BTreeMap> = BTreeMap::new(); let mut covered: BTreeSet<(&str, usize, &str)> = BTreeSet::new(); - for edge in &flow.edges { - let (from, to) = (edge.from.file.as_str(), edge.to.file.as_str()); + for node_dep in &flow.node_deps { + let (from, to) = (node_dep.from.file.as_str(), node_dep.to.file.as_str()); if !files.known.contains(from) || !files.known.contains(to) { continue; } - covered.insert((from, edge.line, to)); + covered.insert((from, node_dep.line, to)); graph - .entry(edge.from.key()) + .entry(node_dep.from.key()) .or_default() - .insert((edge.to.key(), edge.line)); + .insert((node_dep.to.key(), node_dep.line)); } for dep in deps { let keys = dep.targets(); @@ -496,8 +498,8 @@ mod tests { use super::*; use crate::lang::Target; - fn edge(from: &str, to: &str) -> Edge { - Edge { + fn component_dep(from: &str, to: &str) -> ComponentDep { + ComponentDep { from: from.into(), to: to.into(), file: format!("{from}/x"), @@ -574,14 +576,14 @@ rules: } #[test] fn reports_each_cycle_group_once_with_shortest_path() { - let edges = [ - edge("a", "b"), - edge("b", "c"), - edge("c", "a"), - edge("b", "a"), - edge("c", "d"), + let component_deps = [ + component_dep("a", "b"), + component_dep("b", "c"), + component_dep("c", "a"), + component_dep("b", "a"), + component_dep("c", "d"), ]; - let found = cycles(&config("true"), &edges); + let found = cycles(&config("true"), &component_deps); assert_eq!(found.len(), 1); assert_eq!( found[0].message, @@ -716,13 +718,13 @@ rules: } #[test] fn of_cycles_as_short_the_first_in_name_order_is_shown() { - let edges = [ - edge("a", "c"), - edge("c", "a"), - edge("a", "b"), - edge("b", "a"), + let component_deps = [ + component_dep("a", "c"), + component_dep("c", "a"), + component_dep("a", "b"), + component_dep("b", "a"), ]; - let found = cycles(&config("true"), &edges); + let found = cycles(&config("true"), &component_deps); assert_eq!( found[0].message, "component dependency cycle among 3 components: a, b, c (shortest: a -> b -> a)" @@ -730,14 +732,18 @@ rules: } #[test] fn simple_cycle_and_scoping() { - let edges = [edge("a", "b"), edge("b", "c"), edge("c", "a")]; - let found = cycles(&config("true"), &edges); + let component_deps = [ + component_dep("a", "b"), + component_dep("b", "c"), + component_dep("c", "a"), + ]; + let found = cycles(&config("true"), &component_deps); assert_eq!( found[0].message, "component dependency cycle: a -> b -> c -> a" ); - assert!(cycles(&config("[a, b]"), &edges).is_empty()); - assert!(cycles(&config("false"), &edges).is_empty()); + assert!(cycles(&config("[a, b]"), &component_deps).is_empty()); + assert!(cycles(&config("false"), &component_deps).is_empty()); } /// `r1` and `r2` are roots and `r2` imports `r1`; `x` imports `r1` at line 7, `y` /// imports `r2` at line 8, and `z` imports `y` (line 1) and `x` (line 2). diff --git a/src/check.rs b/src/check.rs index b033fd18..9d1f51be 100644 --- a/src/check.rs +++ b/src/check.rs @@ -624,7 +624,7 @@ pub struct SymbolRef { /// A dependency of one component on another, at the line that writes it. #[derive(Debug, Clone)] -pub struct Edge { +pub struct ComponentDep { pub from: String, pub to: String, pub file: String, @@ -632,16 +632,16 @@ pub struct Edge { } /// Checks every internal dependency against the dependency and privacy rules. -/// Every violating import is returned, one per line, see [`dedupe`]. The edges -/// between components feed [`cycles`]. +/// Every violating dependency is returned, one per line, see [`dedupe`]. The +/// dependencies between components feed [`cycles`]. pub fn evaluate( config: &Config, map: &ComponentMap, deps: &[Dep], -) -> (Vec, Vec, Stats) { +) -> (Vec, Vec, Stats) { let mut stats = Stats::default(); let mut found = Vec::new(); - let mut edges = Vec::new(); + let mut component_deps = Vec::new(); let mut unmapped = BTreeSet::new(); // The rejected dependencies, judged once every dependency is decided: what // re-exports a name one writes, the dependencies of the re-exporter tell. @@ -681,17 +681,17 @@ pub fn evaluate( stats.std_unknown.push(ext); } } - // Preferred edge (proven when unambiguous). + // The dependency on the preferred target (proven when unambiguous). if let Some(to) = decision.to.filter(|to| *to != decision.from) { - edges.push(Edge { + component_deps.push(ComponentDep { from: decision.from.to_string(), to: to.to_string(), file: file.clone(), line: dep.line, }); } - // Over-approximation for ambiguous/same-scope deps: contribute an edge - // for every other candidate target so potential paths are not lost. + // Over-approximation for ambiguous/same-scope deps: a dependency on + // every other candidate target, so potential paths are not lost. if decision.resolution != decision::ResolutionStatus::Unambiguous && !dep.candidates.is_empty() { @@ -702,7 +702,7 @@ pub fn evaluate( continue; } if to != decision.from { - edges.push(Edge { + component_deps.push(ComponentDep { from: decision.from.to_string(), to: to.to_string(), file: file.clone(), @@ -729,7 +729,7 @@ pub fn evaluate( found.extend(violation(&decision, dep, &reexport)); } stats.unmapped_files = unmapped.len(); - (found, edges, stats) + (found, component_deps, stats) } /// The components that re-export a name a dependency writes through a module of @@ -915,13 +915,16 @@ pub fn violation(decision: &Decision, dep: &Dep, reexport: &Reexport) -> Option< }) } -/// Component dependencies, as `a -> b`, whose every import sits on a line -/// that `changed` accepts: the edges that did not exist before the change. -pub fn new_dependencies(edges: &[Edge], changed: impl Fn(&str, usize) -> bool) -> Vec { +/// Component dependencies, as `a -> b`, whose every line that writes them +/// is one `changed` accepts: the dependencies that did not exist before the change. +pub fn new_dependencies( + component_deps: &[ComponentDep], + changed: impl Fn(&str, usize) -> bool, +) -> Vec { let mut all_changed: BTreeMap<(&str, &str), bool> = BTreeMap::new(); - for e in edges { - let entry = all_changed.entry((&e.from, &e.to)).or_insert(true); - *entry &= changed(&e.file, e.line); + for dep in component_deps { + let entry = all_changed.entry((&dep.from, &dep.to)).or_insert(true); + *entry &= changed(&dep.file, dep.line); } all_changed .into_iter() @@ -931,13 +934,13 @@ pub fn new_dependencies(edges: &[Edge], changed: impl Fn(&str, usize) -> bool) - } /// Coupling limits: `max_fan_out` counts the components a component depends -/// on, `max_instability` is `out / (in + out)` over the same component edges. -pub fn metrics(config: &Config, edges: &[Edge]) -> Vec { +/// on, `max_instability` is `out / (in + out)` over the same component dependencies. +pub fn metrics(config: &Config, component_deps: &[ComponentDep]) -> Vec { let mut out: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); let mut incoming: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); - for e in edges { - out.entry(&e.from).or_default().insert(&e.to); - incoming.entry(&e.to).or_default().insert(&e.from); + for dep in component_deps { + out.entry(&dep.from).or_default().insert(&dep.to); + incoming.entry(&dep.to).or_default().insert(&dep.from); } let mut found = Vec::new(); for (name, rule) in &config.rules { @@ -947,10 +950,10 @@ pub fn metrics(config: &Config, edges: &[Edge]) -> Vec { let fan_out = targets.len(); let fan_in = incoming.get(name.as_str()).map_or(0, BTreeSet::len); let instability = fan_out as f64 / (fan_in + fan_out) as f64; - let mut evidence: Vec = edges + let mut evidence: Vec = component_deps .iter() - .filter(|e| e.from == *name) - .map(|e| Place::new(e.file.clone(), e.line)) + .filter(|dep| dep.from == *name) + .map(|dep| Place::new(dep.file.clone(), dep.line)) .collect(); evidence.sort(); let Place { file, line, .. } = evidence[0].clone(); @@ -1427,8 +1430,8 @@ components: assert_eq!(lines, [3, 9]); } - fn edge(from: &str, to: &str) -> Edge { - Edge { + fn component_dep(from: &str, to: &str) -> ComponentDep { + ComponentDep { from: from.into(), to: to.into(), file: format!("{from}/x"), @@ -1452,43 +1455,56 @@ rules: #[test] fn metrics_report_fan_out_and_instability() { - let edges = [edge("a", "b"), edge("a", "c"), edge("b", "a")]; + let component_deps = [ + component_dep("a", "b"), + component_dep("a", "c"), + component_dep("b", "a"), + ]; // a: out 2, in 1 -> instability 0.67 - let found = metrics(&limits("max_fan_out: 1, max_instability: 0.5"), &edges); + let found = metrics( + &limits("max_fan_out: 1, max_instability: 0.5"), + &component_deps, + ); let targets: Vec<_> = found.iter().map(|v| v.target.as_str()).collect(); assert_eq!(targets, ["max_fan_out", "max_instability"]); assert!(found[0].message.contains("depends on 2 components")); assert!(found[1].message.contains("instability 0.67")); - assert!(metrics(&limits("max_fan_out: 2, max_instability: 0.7"), &edges).is_empty()); + assert!( + metrics( + &limits("max_fan_out: 2, max_instability: 0.7"), + &component_deps + ) + .is_empty() + ); } #[test] - fn a_dependency_is_new_only_when_all_its_imports_changed() { - let edges = [ - Edge { + fn a_dependency_is_new_only_when_every_line_that_writes_it_changed() { + let component_deps = [ + ComponentDep { line: 1, - ..edge("a", "b") + ..component_dep("a", "b") }, - Edge { + ComponentDep { line: 2, - ..edge("a", "b") + ..component_dep("a", "b") }, - Edge { + ComponentDep { line: 3, - ..edge("a", "c") + ..component_dep("a", "c") }, ]; // Line 1 of a/x is old, so a -> b existed before; only a -> c is new. - let got = new_dependencies(&edges, |_, line| line != 1); + let got = new_dependencies(&component_deps, |_, line| line != 1); assert_eq!(got, ["a -> c"]); } - /// The graph keeps an edge to every candidate of a component: a dependency - /// on a name several files may declare may reach any of them. A candidate - /// of no component has no place in a graph of components, and a candidate - /// of the component itself is no edge. + /// The graph keeps a dependency on the component of every candidate: a + /// dependency on a name several files may declare may reach any of them. A + /// candidate of no component has no place in a graph of components, and a + /// candidate of the component itself is no dependency between components. #[test] - fn the_graph_keeps_an_edge_to_every_candidate_of_a_component() { + fn the_graph_keeps_a_dependency_on_the_component_of_every_candidate() { let config: Config = serde_norway::from_str( "version: 1 components: @@ -1512,15 +1528,15 @@ rules: dep.candidates = candidates.iter().map(|c| c.to_string()).collect(); dep }; - let pairs = |edges: &[Edge]| { - let mut pairs: Vec<(String, String)> = edges + let pairs = |component_deps: &[ComponentDep]| { + let mut pairs: Vec<(String, String)> = component_deps .iter() - .map(|e| (e.from.clone(), e.to.clone())) + .map(|dep| (dep.from.clone(), dep.to.clone())) .collect(); pairs.sort(); pairs }; - let (violations, edges, _) = evaluate( + let (violations, component_deps, _) = evaluate( &config, &map, &[dep_of(&[ @@ -1532,20 +1548,23 @@ rules: ); assert!(violations.is_empty(), "{violations:?}"); assert_eq!( - pairs(&edges), + pairs(&component_deps), [ ("app".to_string(), "lib".to_string()), ("app".to_string(), "other".to_string()), ("app".to_string(), "third".to_string()), ] ); - // A candidate of the component itself is no edge. - let (violations, edges, _) = evaluate( + // A candidate of the component itself is no dependency between components. + let (violations, component_deps, _) = evaluate( &config, &map, &[dep_of(&["app/a/Thing.kt", "lib/a/Thing.kt"])], ); assert!(violations.is_empty(), "{violations:?}"); - assert_eq!(pairs(&edges), [("app".to_string(), "lib".to_string())]); + assert_eq!( + pairs(&component_deps), + [("app".to_string(), "lib".to_string())] + ); } } diff --git a/src/commands.rs b/src/commands.rs index 21755d40..35045f81 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -156,7 +156,7 @@ pub fn check(options: &CheckOptions, cache: &mut scan::Cache) -> Result suppressions, mut stats, map, - edges, + component_deps, deps, accepted, unindexed, @@ -167,7 +167,7 @@ pub fn check(options: &CheckOptions, cache: &mut scan::Cache) -> Result let (unused, left) = suggest::unused_allowances( &project.policy, &map, - &edges, + &component_deps, &unindexed, &project.config_file()?, ); @@ -188,7 +188,7 @@ pub fn check(options: &CheckOptions, cache: &mut scan::Cache) -> Result let mut drift = None; if let Some(diff) = &diff { stats.new_dependencies = - check::new_dependencies(&edges, |f, l| diff.changes.contains(f, l)); + check::new_dependencies(&component_deps, |f, l| diff.changes.contains(f, l)); drift = proposals.as_deref().map(|plan| { drift::compare(&drift::Compared { plan, @@ -509,7 +509,7 @@ pub fn graph( diagram: graph::render( format, project.config(), - &analysis.edges, + &analysis.component_deps, &analysis.violations, focus, ), @@ -525,11 +525,11 @@ pub fn suggest(config: &Path, cache: &mut scan::Cache) -> Result Result let gone = suggest::removable( project.config(), &analysis.map, - &analysis.edges, + &analysis.component_deps, &analysis.unindexed, ); let (gone, held) = patch::by_name(project.config(), gone); diff --git a/src/diagram.rs b/src/diagram.rs index 19dc4519..88771530 100644 --- a/src/diagram.rs +++ b/src/diagram.rs @@ -7,7 +7,7 @@ use std::path::Path; use anyhow::{Context, Result, bail}; -use crate::check::{Edge, Place, RuleId, Violation}; +use crate::check::{ComponentDep, Place, RuleId, Violation}; use crate::config::Config; use crate::policy::Policy; @@ -296,40 +296,40 @@ fn node(text: &str) -> Node { } /// With `diagram`, every dependency between components that the diagram -/// has no arrow for, reported once per pair at its first import. The diagram -/// is the one the policy was loaded with. -pub fn check(policy: &Policy, edges: &[Edge]) -> Result> { +/// has no arrow for, reported once per pair at the first line that writes it. +/// The diagram is the one the policy was loaded with. +pub fn check(policy: &Policy, component_deps: &[ComponentDep]) -> Result> { let config = &policy.config; let Some((path, drawn)) = drawn_arrows(policy)? else { return Ok(Vec::new()); }; - let mut missing: BTreeMap<(&str, &str), Vec<&Edge>> = BTreeMap::new(); - for edge in edges.iter().filter(|e| drawn_needed(config, e)) { - if !drawn.contains(&(edge.from.clone(), edge.to.clone())) { - missing - .entry((&edge.from, &edge.to)) - .or_default() - .push(edge); + let mut missing: BTreeMap<(&str, &str), Vec<&ComponentDep>> = BTreeMap::new(); + for dep in component_deps + .iter() + .filter(|dep| drawn_needed(config, dep)) + { + if !drawn.contains(&(dep.from.clone(), dep.to.clone())) { + missing.entry((&dep.from, &dep.to)).or_default().push(dep); } } Ok(missing .into_iter() - .map(|((from, to), mut imports)| { - imports.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line))); - let first = imports[0]; + .map(|((from, to), mut deps)| { + deps.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line))); + let first = deps[0]; Violation { file: first.file.clone(), line: first.line, message: format!( "{from} -> {to} is not in the diagram {} ({} dependency(ies)); draw the arrow, or drop the dependency", path.display(), - imports.len() + deps.len() ), from: from.to_string(), to: to.to_string(), - evidence: imports + evidence: deps .iter() - .map(|e| Place::new(e.file.clone(), e.line)) + .map(|dep| Place::new(dep.file.clone(), dep.line)) .collect(), ..Violation::of(RuleId::Diagram) } @@ -360,23 +360,26 @@ fn drawn_arrows(policy: &Policy) -> Result> { Ok(Some((path, drawn))) } -/// Whether a dependency has to be drawn: not the imports of the `tests` -/// that `tests: auto` makes, and not those of `common` components, which +/// Whether a dependency has to be drawn: not the dependencies of the `tests` +/// that `tests: auto` makes, and not those on `common` components, which /// every component may use. -fn drawn_needed(config: &Config, edge: &Edge) -> bool { - let tests = config.tests.is_some() && edge.from == crate::config::TESTS; - !tests && !config.common.contains(&edge.to) +fn drawn_needed(config: &Config, dep: &ComponentDep) -> bool { + let tests = config.tests.is_some() && dep.from == crate::config::TESTS; + !tests && !config.common.contains(&dep.to) } -/// The arrows of the diagram that no import stands for: pictures of +/// The arrows of the diagram that no dependency stands for: pictures of /// dependencies the code does not have. -pub fn unused_arrows(policy: &Policy, edges: &[Edge]) -> Result> { +pub fn unused_arrows( + policy: &Policy, + component_deps: &[ComponentDep], +) -> Result> { let Some((_, drawn)) = drawn_arrows(policy)? else { return Ok(Vec::new()); }; - let real: BTreeSet<(&str, &str)> = edges + let real: BTreeSet<(&str, &str)> = component_deps .iter() - .map(|e| (e.from.as_str(), e.to.as_str())) + .map(|dep| (dep.from.as_str(), dep.to.as_str())) .collect(); Ok(drawn .into_iter() diff --git a/src/drift.rs b/src/drift.rs index 61f18b75..129a8a9a 100644 --- a/src/drift.rs +++ b/src/drift.rs @@ -68,7 +68,7 @@ struct Pair<'a> { to_component: Option<&'a str>, line: usize, /// Whether every line of the pair is a changed one: the import is new, as - /// `new_dependencies` tells a new edge between components. + /// `new_dependencies` tells a new dependency between components. new: bool, } diff --git a/src/flow.rs b/src/flow.rs index 68ac4579..5237f061 100644 --- a/src/flow.rs +++ b/src/flow.rs @@ -4,11 +4,12 @@ //! file reaches everything the file imports. With `reach: symbols` a chain follows //! the definitions a call references instead: a node is a method or function (a //! symbol with the lines it spans) or what a file holds outside any of them (its -//! class bodies, constants, top-level code), and an edge is a reference at a line. +//! class bodies, constants, top-level code), and a dependency of one node on another +//! ([`NodeDep`]) is a reference at a line. //! -//! A dependency that no reference accounts for stays an edge to everything in its -//! target, and so does a class or constant used with no method named, so no import -//! is dropped for want of a range. The index is read into a flow in `scip::Indexed::flow`. +//! A dependency that no reference accounts for stays a dependency on everything in +//! its target, and so does a class or constant used with no method named, so no +//! import is dropped for want of a range. The index is read into a flow in `scip::Indexed::flow`. //! //! `impact --diff` reads the flow whatever `reach` says: the uses of a definition the //! change touched are the places worth re-checking ([`Flow::callers`]). @@ -48,9 +49,10 @@ pub fn file_of(key: &str) -> &str { key.split_once(SEPARATOR).map_or(key, |(file, _)| file) } -/// A reference at `line` of the source node's file to the target node. +/// A dependency of one node on another: a reference at `line` of the source node's +/// file to the target node. #[derive(Debug, Clone)] -pub struct Edge { +pub struct NodeDep { pub from: Node, pub to: Node, pub line: usize, @@ -58,7 +60,7 @@ pub struct Edge { /// A reference the index records at `line` of `file` to a definition: to the method /// it names, or to the own code of the file that defines the class or constant it -/// names. Unlike an [`Edge`], it is never widened to every method of a file, and a +/// names. Unlike a [`NodeDep`], it is never widened to every method of a file, and a /// module named on its own (an import) is none. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Use { @@ -71,7 +73,7 @@ pub struct Use { pub struct Flow { /// The methods of each file that the index gave a range. pub scopes: BTreeMap>, - pub edges: Vec, + pub node_deps: Vec, /// Every reference of the index to a definition, as [`Flow::callers`] reads them. pub uses: Vec, /// The name of each method of `scopes` as its symbol spells it, without the diff --git a/src/graph.rs b/src/graph.rs index 23067abe..6e197004 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use crate::check::{Edge, RuleId, Violation}; +use crate::check::{ComponentDep, RuleId, Violation}; use crate::config::Config; #[derive(Clone, Copy, clap::ValueEnum)] @@ -9,23 +9,26 @@ pub enum GraphFormat { Dot, } -/// One arrow of the component graph: how many imports it stands for, and +/// One arrow of the component graph: how many dependencies it stands for, and /// whether any of them breaks a rule. struct Arrow { - imports: usize, + deps: usize, violating: bool, } -fn arrows(edges: &[Edge], violations: &[Violation]) -> BTreeMap<(String, String), Arrow> { +fn arrows( + component_deps: &[ComponentDep], + violations: &[Violation], +) -> BTreeMap<(String, String), Arrow> { let mut arrows: BTreeMap<(String, String), Arrow> = BTreeMap::new(); - for e in edges { + for dep in component_deps { arrows - .entry((e.from.clone(), e.to.clone())) + .entry((dep.from.clone(), dep.to.clone())) .or_insert(Arrow { - imports: 0, + deps: 0, violating: false, }) - .imports += 1; + .deps += 1; } for v in violations { if matches!(v.rule, RuleId::Dependency | RuleId::Privacy) @@ -42,11 +45,11 @@ fn arrows(edges: &[Edge], violations: &[Violation]) -> BTreeMap<(String, String) pub fn render( format: GraphFormat, config: &Config, - edges: &[Edge], + component_deps: &[ComponentDep], violations: &[Violation], focus: Option<&str>, ) -> String { - let mut arrows = arrows(edges, violations); + let mut arrows = arrows(component_deps, violations); if let Some(focus) = focus { arrows.retain(|(from, to), _| from == focus || to == focus); } @@ -80,10 +83,10 @@ fn mermaid(nodes: &[&str], arrows: &BTreeMap<(String, String), Arrow>) -> String for (i, ((from, to), arrow)) in arrows.iter().enumerate() { let (from, to) = (&ids[from.as_str()], &ids[to.as_str()]); if arrow.violating { - out.push_str(&format!(" {from} -.->|{} ✗| {to}\n", arrow.imports)); + out.push_str(&format!(" {from} -.->|{} ✗| {to}\n", arrow.deps)); red.push(i.to_string()); } else { - out.push_str(&format!(" {from} -->|{}| {to}\n", arrow.imports)); + out.push_str(&format!(" {from} -->|{}| {to}\n", arrow.deps)); } } if !red.is_empty() { @@ -111,7 +114,7 @@ fn dot(nodes: &[&str], arrows: &BTreeMap<(String, String), Arrow>) -> String { " {} -> {} [label=\"{}\"{style}];\n", quote(from), quote(to), - arrow.imports + arrow.deps )); } out.push_str("}\n"); @@ -124,15 +127,27 @@ mod tests { #[test] fn focus_keeps_a_component_and_its_neighbours() { - let (config, edges, violations) = fixture(); - let dot = render(GraphFormat::Dot, &config, &edges, &violations, Some("b")); + let (config, component_deps, violations) = fixture(); + let dot = render( + GraphFormat::Dot, + &config, + &component_deps, + &violations, + Some("b"), + ); assert!(dot.contains("\"a\" -> \"b\"")); assert!(!dot.contains("lone")); - let alone = render(GraphFormat::Dot, &config, &edges, &violations, Some("lone")); + let alone = render( + GraphFormat::Dot, + &config, + &component_deps, + &violations, + Some("lone"), + ); assert!(alone.contains("\"lone\";") && !alone.contains("->")); } - fn fixture() -> (Config, Vec, Vec) { + fn fixture() -> (Config, Vec, Vec) { let config: Config = serde_norway::from_str( "version: 1 components: @@ -142,13 +157,17 @@ components: ", ) .unwrap(); - let edge = |from: &str, to: &str, line| Edge { + let component_dep = |from: &str, to: &str, line| ComponentDep { from: from.into(), to: to.into(), file: format!("{from}/x"), line, }; - let edges = vec![edge("a", "b", 1), edge("a", "b", 2), edge("b", "a", 1)]; + let component_deps = vec![ + component_dep("a", "b", 1), + component_dep("a", "b", 2), + component_dep("b", "a", 1), + ]; let violation = Violation { file: "b/x".into(), line: 1, @@ -156,13 +175,19 @@ components: to: "a".into(), ..Violation::of(RuleId::Dependency) }; - (config, edges, vec![violation]) + (config, component_deps, vec![violation]) } #[test] fn mermaid_marks_violations() { - let (config, edges, violations) = fixture(); - let out = render(GraphFormat::Mermaid, &config, &edges, &violations, None); + let (config, component_deps, violations) = fixture(); + let out = render( + GraphFormat::Mermaid, + &config, + &component_deps, + &violations, + None, + ); assert_eq!( out, "graph LR\n c0[\"a\"]\n c1[\"b\"]\n c2[\"lone\"]\n c0 -->|2| c1\n c1 -.->|1 ✗| c0\n linkStyle 1 stroke:#d00,stroke-width:2px,color:#d00\n" @@ -171,8 +196,14 @@ components: #[test] fn dot_marks_violations() { - let (config, edges, violations) = fixture(); - let out = render(GraphFormat::Dot, &config, &edges, &violations, None); + let (config, component_deps, violations) = fixture(); + let out = render( + GraphFormat::Dot, + &config, + &component_deps, + &violations, + None, + ); assert!(out.contains("\"a\" -> \"b\" [label=\"2\"];")); assert!( out.contains("\"b\" -> \"a\" [label=\"1\", color=red, fontcolor=red, style=dashed];") diff --git a/src/init.rs b/src/init.rs index f96863b8..4da89762 100644 --- a/src/init.rs +++ b/src/init.rs @@ -176,10 +176,12 @@ pub fn run(root: &Path, force: bool, cache: &mut scan::Cache) -> Result let config: Config = serde_norway::from_str(&draft)?; let scanned = scan::scan(root, &config.scan_policy(), cache)?; let map = ComponentMap::new(&config)?; - let (_, edges, _) = check::evaluate(&config, &map, &scanned.deps); + let (_, component_deps, _) = check::evaluate(&config, &map, &scanned.deps); let mut deps: BTreeMap> = BTreeMap::new(); - for e in &edges { - deps.entry(e.from.clone()).or_default().insert(e.to.clone()); + for dep in &component_deps { + deps.entry(dep.from.clone()) + .or_default() + .insert(dep.to.clone()); } std::fs::write(&path, render(&found, &deps))?; let mut out = format!( diff --git a/src/policy.rs b/src/policy.rs index 8b7bea9f..a5f55335 100644 --- a/src/policy.rs +++ b/src/policy.rs @@ -1458,7 +1458,7 @@ rules: ); commit(repo, "drop the arrow"); - let edges = [crate::check::Edge { + let component_deps = [crate::check::ComponentDep { from: "web".to_string(), to: "db".to_string(), file: "web/a.ts".to_string(), @@ -1466,9 +1466,13 @@ rules: }]; let config = repo.join("easement.yml"); let old = Policy::load(&config, Some("HEAD~1")).unwrap(); - assert!(crate::diagram::check(&old, &edges).unwrap().is_empty()); + assert!( + crate::diagram::check(&old, &component_deps) + .unwrap() + .is_empty() + ); let now = Policy::load(&config, None).unwrap(); - let violations = crate::diagram::check(&now, &edges).unwrap(); + let violations = crate::diagram::check(&now, &component_deps).unwrap(); assert_eq!(violations.len(), 1); assert!( violations[0] diff --git a/src/project.rs b/src/project.rs index 04239139..9e90e625 100644 --- a/src/project.rs +++ b/src/project.rs @@ -95,7 +95,7 @@ impl Project { let config = &policy.config; let map = ComponentMap::new(config)?; symbols::contradicted_grants(config, &map, &scan.all_files, &scan.symbols)?; - let (mut violations, edges, mut stats) = check::evaluate(config, &map, &scan.deps); + let (mut violations, component_deps, mut stats) = check::evaluate(config, &map, &scan.deps); violations.extend(symbols::symbols(config, &map, &scan.symbols)); violations.extend(check::naming(config, &map, &scan.types)?); violations.extend(implementations::violations( @@ -125,9 +125,9 @@ impl Project { &config_file, )); violations.extend(examples::check(policy, &map, &self.root)); - violations.extend(chains::cycles(config, &edges)); + violations.extend(chains::cycles(config, &component_deps)); let mut unread_diagram = None; - match diagram::check(policy, &edges) { + match diagram::check(policy, &component_deps) { Ok(drawn) => violations.extend(drawn), Err(err) if unread_diagram_fails => return Err(err), Err(err) => unread_diagram = Some(format!("{err:#}")), @@ -139,7 +139,7 @@ impl Project { &scan.all_files, scan.reach_flow(config), )); - violations.extend(check::metrics(config, &edges)); + violations.extend(check::metrics(config, &component_deps)); violations.extend(matching::orphans(config, &map, &scan.paths)); violations.extend(check::forbidden_files(config, &map, &scan.all_files)); violations.extend(check::required( @@ -174,7 +174,7 @@ impl Project { Ok(Judgment { violations, suppressions: honoured, - edges, + component_deps, stats, map, unread_diagram, @@ -201,7 +201,7 @@ impl Project { let Judgment { violations, suppressions, - edges, + component_deps, mut stats, map, unread_diagram, @@ -257,7 +257,7 @@ impl Project { violations, suppressions, all_files: scan.all_files, - edges, + component_deps, deps: scan.deps, files: scan.paths, stats, @@ -298,7 +298,7 @@ pub struct Judgment { /// The inline suppressions that excused violations, with them: the /// violations the policy produces besides `violations`. pub suppressions: Vec, - pub edges: Vec, + pub component_deps: Vec, pub stats: check::Stats, pub map: ComponentMap, /// Why the diagram the policy names could not be read, when the judging @@ -327,7 +327,7 @@ pub struct Analysis { pub accepted: Vec, /// Every file that is not excluded, source or not. pub all_files: Vec, - pub edges: Vec, + pub component_deps: Vec, pub deps: Vec, pub files: Vec, pub stats: check::Stats, diff --git a/src/propose.rs b/src/propose.rs index e0ff663f..2b5ce610 100644 --- a/src/propose.rs +++ b/src/propose.rs @@ -11,7 +11,7 @@ use pathfinding::directed::bfs::bfs; use serde::{Deserialize, Serialize}; use crate::chains; -use crate::check::{self, Edge, RuleId, Violation}; +use crate::check::{self, ComponentDep, RuleId, Violation}; use crate::components::ComponentMap; use crate::config::{Config, TESTS}; use crate::decision::{self, Clause, Outside}; @@ -405,8 +405,8 @@ pub fn notes(config: &Config, map: &ComponentMap, proposals: &[Proposal]) -> Vec .collect() } -/// One step of a witness: an edge between components, or for a reach chain, an -/// import between files. +/// One step of a witness: a dependency between components, or for a reach chain, +/// a dependency between files. #[derive(Debug, Serialize)] pub struct Step { pub from: String, @@ -434,15 +434,15 @@ impl Step { } } - /// The step of components `from -> to`: its first import in the code, else - /// the first proposal that makes it. - fn of_edge(from: &str, to: &str, edges: &[Edge]) -> Self { - let edge = edges + /// The step of components `from -> to`: the first line of the code that + /// writes the dependency, else the first proposal that makes it. + fn of_component_dep(from: &str, to: &str, component_deps: &[ComponentDep]) -> Self { + let dep = component_deps .iter() - .filter(|e| e.from == from && e.to == to) - .min_by_key(|e| (proposal_at(e.line).is_some(), &e.file, e.line)) - .expect("a step of a witness is an edge"); - Step::at(from, to, &edge.file, edge.line) + .filter(|dep| dep.from == from && dep.to == to) + .min_by_key(|dep| (proposal_at(dep.line).is_some(), &dep.file, dep.line)) + .expect("a step of a witness is a dependency between components"); + Step::at(from, to, &dep.file, dep.line) } } @@ -481,11 +481,11 @@ pub struct Graph<'a> { pub flow: Option<&'a Flow>, } -/// The violations of the rules that judge the whole graph, and its edges between components. -fn graph_rules(graph: &Graph) -> Result<(Vec, Vec)> { +/// The violations of the rules that judge the whole graph, and its dependencies between components. +fn graph_rules(graph: &Graph) -> Result<(Vec, Vec)> { let config = &graph.policy.config; - let (_, edges, _) = check::evaluate(config, graph.map, graph.deps); - let mut found = chains::cycles(config, &edges); + let (_, component_deps, _) = check::evaluate(config, graph.map, graph.deps); + let mut found = chains::cycles(config, &component_deps); found.extend(chains::reaches( config, graph.map, @@ -493,9 +493,9 @@ fn graph_rules(graph: &Graph) -> Result<(Vec, Vec)> { graph.files, graph.flow, )); - found.extend(check::metrics(config, &edges)); - found.extend(crate::diagram::check(graph.policy, &edges)?); - Ok((found, edges)) + found.extend(check::metrics(config, &component_deps)); + found.extend(crate::diagram::check(graph.policy, &component_deps)?); + Ok((found, component_deps)) } /// The cycles, reach chains, crossed limits and missing diagram arrows that the @@ -528,7 +528,7 @@ pub fn consequences(graph: &Graph, proposals: &[Proposal]) -> Result Result Consequence { +fn consequence(graph: &Graph, v: Violation, component_deps: &[ComponentDep]) -> Consequence { let config = &graph.policy.config; let mut limit = None; let (message, witness) = match v.rule { RuleId::Cycle => { let members: BTreeSet<&str> = v.components().collect(); - let witness = cycle_witness(&members, edges); + let witness = cycle_witness(&members, component_deps); let path: Vec<&str> = witness .iter() .map(|s| s.from.as_str()) @@ -589,33 +589,33 @@ fn consequence(graph: &Graph, v: Violation, edges: &[Edge]) -> Consequence { } RuleId::Metric => { limit = Some(v.target.clone()); - let targets: BTreeSet<&str> = edges + let targets: BTreeSet<&str> = component_deps .iter() - .filter(|e| e.from == v.from) - .map(|e| e.to.as_str()) + .filter(|dep| dep.from == v.from) + .map(|dep| dep.to.as_str()) .collect(); let witness = targets .into_iter() - .map(|to| Step::of_edge(&v.from, to, edges)) + .map(|to| Step::of_component_dep(&v.from, to, component_deps)) .collect(); (v.message.clone(), witness) } _ => ( v.message.clone(), - vec![Step::of_edge(&v.from, &v.to, edges)], + vec![Step::of_component_dep(&v.from, &v.to, component_deps)], ), }; let mut proposals: BTreeSet = witness.iter().filter_map(|s| s.proposal).collect(); // A group of components holds every cycle among them: each proposal that - // makes an edge of it no import makes is in it, not only those of the witness. + // makes a dependency of it that no code makes is in it, not only those of the witness. if v.rule == RuleId::Cycle { let members: BTreeSet<&str> = v.components().collect(); - for (from, to) in proposed_edges(&members, edges) { + for (from, to) in proposed_component_deps(&members, component_deps) { proposals.extend( - edges + component_deps .iter() - .filter(|e| e.from == from && e.to == to) - .filter_map(|e| proposal_at(e.line)), + .filter(|dep| dep.from == from && dep.to == to) + .filter_map(|dep| proposal_at(dep.line)), ); } } @@ -632,18 +632,18 @@ fn consequence(graph: &Graph, v: Violation, edges: &[Edge]) -> Consequence { } } -/// The shortest cycle among `members` that takes an edge only the proposals -/// make, as its steps: the cycle the proposals close. -fn cycle_witness(members: &BTreeSet<&str>, edges: &[Edge]) -> Vec { - let inside: Vec<&Edge> = edges +/// The shortest cycle among `members` that takes a dependency only the +/// proposals make, as its steps: the cycle the proposals close. +fn cycle_witness(members: &BTreeSet<&str>, component_deps: &[ComponentDep]) -> Vec { + let inside: Vec<&ComponentDep> = component_deps .iter() - .filter(|e| members.contains(e.from.as_str()) && members.contains(e.to.as_str())) + .filter(|dep| members.contains(dep.from.as_str()) && members.contains(dep.to.as_str())) .collect(); let mut graph: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); - for e in &inside { - graph.entry(&e.from).or_default().insert(&e.to); + for dep in &inside { + graph.entry(&dep.from).or_default().insert(&dep.to); } - let cycle = proposed_edges(members, edges) + let cycle = proposed_component_deps(members, component_deps) .into_iter() .filter_map(|(a, b)| { let back = bfs( @@ -654,25 +654,28 @@ fn cycle_witness(members: &BTreeSet<&str>, edges: &[Edge]) -> Vec { Some(std::iter::once(a).chain(back).collect::>()) }) .min_by_key(Vec::len) - .expect("a cycle the proposals add takes an edge only they make"); + .expect("a cycle the proposals add takes a dependency only they make"); cycle .windows(2) - .map(|pair| Step::of_edge(pair[0], pair[1], edges)) + .map(|pair| Step::of_component_dep(pair[0], pair[1], component_deps)) .collect() } -/// The edges among `members` that only proposals make. -fn proposed_edges<'a>(members: &BTreeSet<&str>, edges: &'a [Edge]) -> BTreeSet<(&'a str, &'a str)> { - let inside = edges +/// The dependencies among `members` that only proposals make. +fn proposed_component_deps<'a>( + members: &BTreeSet<&str>, + component_deps: &'a [ComponentDep], +) -> BTreeSet<(&'a str, &'a str)> { + let inside = component_deps .iter() - .filter(|e| members.contains(e.from.as_str()) && members.contains(e.to.as_str())); + .filter(|dep| members.contains(dep.from.as_str()) && members.contains(dep.to.as_str())); let real: BTreeSet<(&str, &str)> = inside .clone() - .filter(|e| proposal_at(e.line).is_none()) - .map(|e| (e.from.as_str(), e.to.as_str())) + .filter(|dep| proposal_at(dep.line).is_none()) + .map(|dep| (dep.from.as_str(), dep.to.as_str())) .collect(); inside - .map(|e| (e.from.as_str(), e.to.as_str())) + .map(|dep| (dep.from.as_str(), dep.to.as_str())) .filter(|pair| !real.contains(pair)) .collect() } @@ -845,8 +848,8 @@ fn tag(rule: RuleId, warning: bool) -> String { mod tests { use super::*; - fn edge(from: &str, to: &str, file: &str, line: usize) -> Edge { - Edge { + fn component_dep(from: &str, to: &str, file: &str, line: usize) -> ComponentDep { + ComponentDep { from: from.into(), to: to.into(), file: file.into(), @@ -886,19 +889,19 @@ mod tests { /// `a <-> b` exists; proposal 0 adds `c -> a`, proposals 1 and 2 add /// `a -> c` and `b -> c`. The witness is a shortest cycle through a - /// proposal, at the import where the code has one; every proposal of the - /// group is named. + /// proposal, at the line that writes each step where the code has one; + /// every proposal of the group is named. #[test] fn a_cycle_is_told_through_the_proposals_that_make_it() { - let edges = vec![ - edge("a", "b", "a.ts", 3), - edge("b", "a", "b.ts", 4), - edge("c", "a", "c.ts", FIRST_LINE), - edge("a", "c", "a.ts", FIRST_LINE + 1), - edge("b", "c", "b.ts", FIRST_LINE + 2), + let component_deps = vec![ + component_dep("a", "b", "a.ts", 3), + component_dep("b", "a", "b.ts", 4), + component_dep("c", "a", "c.ts", FIRST_LINE), + component_dep("a", "c", "a.ts", FIRST_LINE + 1), + component_dep("b", "c", "b.ts", FIRST_LINE + 2), ]; let members: BTreeSet<&str> = ["a", "b", "c"].into(); - let witness = cycle_witness(&members, &edges); + let witness = cycle_witness(&members, &component_deps); let told: Vec<(&str, &str, Option, Option)> = witness .iter() .map(|s| (s.from.as_str(), s.to.as_str(), s.line, s.proposal)) @@ -908,7 +911,7 @@ mod tests { vec![("a", "c", None, Some(1)), ("c", "a", None, Some(0))] ); assert_eq!( - proposed_edges(&members, &edges), + proposed_component_deps(&members, &component_deps), [("a", "c"), ("b", "c"), ("c", "a")].into() ); } diff --git a/src/scip/mod.rs b/src/scip/mod.rs index f5fefb5c..92619962 100644 --- a/src/scip/mod.rs +++ b/src/scip/mod.rs @@ -24,7 +24,7 @@ use protobuf::Message; use scip::types::{Index, Occurrence, PositionEncoding, occurrence::Typed_range}; use crate::check::{SymbolRef, Unjudged}; -use crate::flow::{Edge, Flow, Node, Use}; +use crate::flow::{Flow, Node, NodeDep, Use}; use crate::lang::parts::Part; use crate::lang::registry; use crate::lang::{ @@ -1736,11 +1736,11 @@ impl Indexed<'_> { } // A method reaches the code of its own file that is in none: the class body and the // constants that run when the file loads. - let own: Vec = flow + let own: Vec = flow .scopes .iter() .flat_map(|(file, scopes)| { - scopes.iter().map(|scope| Edge { + scopes.iter().map(|scope| NodeDep { from: Node { file: file.clone(), scope: Some(scope.symbol.clone()), @@ -1750,7 +1750,7 @@ impl Indexed<'_> { }) }) .collect(); - flow.edges.extend(own); + flow.node_deps.extend(own); for document in documents { // The files whose method a line names: such a line reaches that method, and a // reference to the class around it (`Document` of `Document.host`) adds nothing. @@ -1801,7 +1801,7 @@ impl Indexed<'_> { for from in flow.owners(&document.path, reference.line) { for to in &targets { if from != *to { - flow.edges.push(Edge { + flow.node_deps.push(NodeDep { from: from.clone(), to: to.clone(), line: reference.line, diff --git a/src/scope.rs b/src/scope.rs index ac7962bd..beac2ae2 100644 --- a/src/scope.rs +++ b/src/scope.rs @@ -8,8 +8,9 @@ use crate::config::Config; /// What a run reports on: the whole project, or the files of some components /// and/or paths. The whole project is still read and judged, because cycles, -/// limits and every edge need all of it; the scope narrows only the violations -/// and stale entries reported, never the counters or the evidence gaps. +/// limits and every dependency between components need all of it; the scope +/// narrows only the violations and stale entries reported, never the counters +/// or the evidence gaps. #[derive(Default)] pub struct Scope { components: BTreeSet, diff --git a/src/suggest.rs b/src/suggest.rs index c3657342..bb8cd5f1 100644 --- a/src/suggest.rs +++ b/src/suggest.rs @@ -2,7 +2,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::Serialize; -use crate::check::{Edge, RuleId, Violation}; +use crate::check::{ComponentDep, RuleId, Violation}; use crate::components::{AcceptedGap, ComponentMap}; use crate::config::Config; use crate::decision::{self, Grant, Refusal}; @@ -170,12 +170,12 @@ fn capitalized(text: &str) -> String { pub fn unused_allowances( policy: &Policy, map: &ComponentMap, - edges: &[Edge], + component_deps: &[ComponentDep], unindexed: &[String], config_file: &str, ) -> (Vec, Spared) { let config = &policy.config; - let counts = counts(map, edges, unindexed); + let counts = counts(map, component_deps, unindexed); let found = unused(config, &counts.used, &counts.unindexed); let removable: Vec<(String, String)> = found .removable @@ -237,13 +237,13 @@ pub struct Isolated { pub fn suggest( config: &Config, map: &ComponentMap, - edges: &[Edge], + component_deps: &[ComponentDep], deps: &[Dep], files: &[String], uncovered: &[String], stale_arrows: &[(String, String)], ) -> Suggestions { - let Counts { unindexed, used } = counts(map, edges, uncovered); + let Counts { unindexed, used } = counts(map, component_deps, uncovered); let unread_of = |pair: [&str; 2]| unread_of(&unindexed, pair); let Unused { removable, @@ -370,10 +370,10 @@ impl Suggestions { pub fn removable( config: &Config, map: &ComponentMap, - edges: &[Edge], + component_deps: &[ComponentDep], uncovered: &[String], ) -> Vec<(String, String)> { - let Counts { unindexed, used } = counts(map, edges, uncovered); + let Counts { unindexed, used } = counts(map, component_deps, uncovered); unused(config, &used, &unindexed) .removable .into_iter() @@ -427,14 +427,18 @@ fn unread_of(unindexed: &BTreeMap<&str, usize>, pair: [&str; 2]) -> BTreeMap { - /// Files no indexer saw have no edges: a missing import next to them proves nothing. + /// Files no indexer saw have no dependencies: a missing one next to them proves nothing. unindexed: BTreeMap<&'a str, usize>, used: BTreeMap<(&'a str, &'a str), usize>, } -fn counts<'a>(map: &'a ComponentMap, edges: &'a [Edge], uncovered: &[String]) -> Counts<'a> { +fn counts<'a>( + map: &'a ComponentMap, + component_deps: &'a [ComponentDep], + uncovered: &[String], +) -> Counts<'a> { let mut unindexed: BTreeMap<&str, usize> = BTreeMap::new(); for file in uncovered { if let Some(component) = map.component_of(file) { @@ -442,8 +446,8 @@ fn counts<'a>(map: &'a ComponentMap, edges: &'a [Edge], uncovered: &[String]) -> } } let mut used: BTreeMap<(&str, &str), usize> = BTreeMap::new(); - for e in edges { - *used.entry((&e.from, &e.to)).or_default() += 1; + for dep in component_deps { + *used.entry((&dep.from, &dep.to)).or_default() += 1; } Counts { unindexed, used } } @@ -541,8 +545,8 @@ mod tests { Dep::module(file, 1, "", Target::Internal(target.into())) } - fn edge(from: &str, to: &str) -> Edge { - Edge { + fn component_dep(from: &str, to: &str) -> ComponentDep { + ComponentDep { from: from.into(), to: to.into(), file: format!("{from}/x"), @@ -565,7 +569,7 @@ rules: ) .unwrap(); let map = ComponentMap::new(&config).unwrap(); - let edges = [edge("web", "core"), edge("core", "data")]; + let component_deps = [component_dep("web", "core"), component_dep("core", "data")]; let deps = [ dep("src/pages/a/x.ts", "src/core/c.ts"), dep("src/pages/b/y.ts", "src/pages/b/z.ts"), @@ -576,7 +580,7 @@ rules: "src/pages/b/z.ts".to_string(), "src/pages/c/leaf.ts".to_string(), ]; - let out = suggest(&config, &map, &edges, &deps, &files, &[], &[]).text(); + let out = suggest(&config, &map, &component_deps, &deps, &files, &[], &[]).text(); assert!(out.contains(" web -> data\n"), "{out}"); assert!(!out.contains("web -> core"), "{out}"); assert!(out.contains(" core: data (1 dependency(ies))\n"), "{out}"); @@ -584,7 +588,7 @@ rules: let crossing = [dep("src/pages/a/x.ts", "src/pages/b/y.ts")]; assert!( - !suggest(&config, &map, &edges, &crossing, &files, &[], &[]) + !suggest(&config, &map, &component_deps, &crossing, &files, &[], &[]) .text() .contains("pages") ); @@ -604,16 +608,16 @@ rules: ) .unwrap(); let map = ComponentMap::new(&config).unwrap(); - let edges = [edge("web", "core")]; + let component_deps = [component_dep("web", "core")]; let uncovered = ["src/generated/index.ts".to_string()]; - let out = suggest(&config, &map, &edges, &[], &[], &uncovered, &[]).text(); + let out = suggest(&config, &map, &component_deps, &[], &[], &uncovered, &[]).text(); assert!( out.contains(" web -> generated (not indexed: 1 file(s) of generated)\n"), "{out}" ); // It is not offered as a plain removal. assert!(!out.contains(" web -> generated\n"), "{out}"); - let clean = suggest(&config, &map, &edges, &[], &[], &[], &[]).text(); + let clean = suggest(&config, &map, &component_deps, &[], &[], &[], &[]).text(); assert!(clean.contains(" web -> generated\n"), "{clean}"); } diff --git a/tests/library/aliases.rs b/tests/library/aliases.rs index 75fa0998..90edea4f 100644 --- a/tests/library/aliases.rs +++ b/tests/library/aliases.rs @@ -361,7 +361,7 @@ fn why_shows_each_alias_behind_a_dependency_as_a_hop() { "{}", why.text() ); - // A use of the alias is a use of the name it stands for: one name of the edge. + // A use of the alias is a use of the name it stands for: one name of the dependency. assert_eq!( data["names"], serde_json::json!([{ diff --git a/tests/library/baseline.rs b/tests/library/baseline.rs index 66c71673..da4e8339 100644 --- a/tests/library/baseline.rs +++ b/tests/library/baseline.rs @@ -126,7 +126,7 @@ fn a_new_file_on_a_baselined_cycle_or_limit_is_not_new_debt() { "{}", recorded.text() ); - // A file that sorts first now carries the same edge. + // A file that sorts first now carries the same dependency between components. fs::write(root.join("src/a/A.kt"), "package a\nimport b.N\nclass A\n").unwrap(); let checked = check(&root); assert_eq!(checked.outcome(), Outcome::Passed); diff --git a/tests/library/commands.rs b/tests/library/commands.rs index 96667436..b8cfa7f9 100644 --- a/tests/library/commands.rs +++ b/tests/library/commands.rs @@ -98,7 +98,7 @@ fn explain_and_graph() { assert!(mermaid.starts_with("graph LR\n"), "{mermaid}"); assert!( mermaid.contains("-.->"), - "the forbidden web -> data edge is dashed: {mermaid}" + "the forbidden web -> data arrow is dashed: {mermaid}" ); assert!(mermaid.contains("linkStyle")); let dot = commands::graph(&config, GraphFormat::Dot, None, &mut cache()) diff --git a/tests/library/declarations.rs b/tests/library/declarations.rs index 8099bcda..b6d2c3ce 100644 --- a/tests/library/declarations.rs +++ b/tests/library/declarations.rs @@ -460,7 +460,7 @@ fn a_function_of_one_name_in_two_components_is_ambiguous_but_no_gap() { } /// `impact` of a copy that `decide` did not pick still names the importer: the -/// file graph keeps an edge to every candidate. +/// file graph keeps a dependency on every candidate. #[test] fn impact_of_an_alternative_copy_names_the_importer() { let (_tmp, root) = project_of(&[ @@ -599,7 +599,7 @@ fn a_dependency_of_only_unowned_candidates_is_judged_by_no_rule() { } /// A cycle between components that only the alternative candidate closes is -/// reported: the graph keeps an edge to every candidate of a component. +/// reported: the graph keeps a dependency on the component of every candidate. #[test] fn a_cycle_through_an_alternative_candidate_is_reported() { let (_tmp, root) = project_with( @@ -636,10 +636,10 @@ fn a_cycle_through_an_alternative_candidate_is_reported() { ); } -/// A candidate outside every component adds no edge to the graph of the +/// A candidate outside every component adds no dependency to the graph of the /// components: no cycle comes of it. #[test] -fn a_candidate_outside_the_components_adds_no_edge() { +fn a_candidate_outside_the_components_adds_no_dependency() { let (_tmp, root) = project_with( &policy( &["a", "b"], diff --git a/tests/library/plan.rs b/tests/library/plan.rs index e301e9c2..7e43db19 100644 --- a/tests/library/plan.rs +++ b/tests/library/plan.rs @@ -183,9 +183,9 @@ fn a_new_import_inside_one_component_is_not_compared() { assert_eq!(unplanned(&report), Vec::::new(), "{report}"); } -/// An import is new as an edge is new in `new_dependencies`: when every line of -/// it changed. An edited import line is all of it, so it is reported, since the -/// imports of the merge-base are not read. +/// An import is new as a dependency between components is new in +/// `new_dependencies`: when every line of it changed. An edited import line is +/// all of it, so it is reported, since the imports of the merge-base are not read. #[test] fn an_edited_import_line_is_new_as_new_dependencies_tells_it() { let (_tmp, root) = web_and_core(); From 248986c5e00c6d6e786f3ea879974c9a6abdddea Mon Sep 17 00:00:00 2001 From: Kirill Mokevnin Date: Wed, 18 Nov 2026 22:01:42 -0500 Subject: [PATCH 2/4] refactor: name a component dependency component_dep where dep means a Dep Review of the rename: `dep` already names a `lang::Dep`, so the locals that hold a `ComponentDep` are `component_dep`, as those of a `NodeDep` are `node_dep`. The arrow of the drawn graph counts its dependencies in `count`. The doc comments of `Step::file`, of the flow and of `NodeDep` say what they hold: a line that writes a step, a node reaching another. Refs #218 Co-Authored-By: Claude Opus 5.5 --- src/chains.rs | 37 +++++++++++++++++++++++-------------- src/check.rs | 25 ++++++++++++++++--------- src/diagram.rs | 19 +++++++++++-------- src/flow.rs | 12 ++++++------ src/graph.rs | 16 ++++++++-------- src/init.rs | 6 +++--- src/propose.rs | 48 ++++++++++++++++++++++++++++++------------------ src/suggest.rs | 6 ++++-- 8 files changed, 101 insertions(+), 68 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index bdb2bf63..819cef67 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -22,12 +22,18 @@ use crate::relpath::{self, slash}; pub fn cycles(config: &Config, component_deps: &[ComponentDep]) -> Vec { let covered: Vec<&ComponentDep> = component_deps .iter() - .filter(|dep| config.no_cycles.covers(&dep.from) && config.no_cycles.covers(&dep.to)) + .filter(|component_dep| { + config.no_cycles.covers(&component_dep.from) + && config.no_cycles.covers(&component_dep.to) + }) .collect(); let mut graph: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); - for dep in &covered { - graph.entry(&dep.from).or_default().insert(&dep.to); - graph.entry(&dep.to).or_default(); + for component_dep in &covered { + graph + .entry(&component_dep.from) + .or_default() + .insert(&component_dep.to); + graph.entry(&component_dep.to).or_default(); } let nodes: Vec<&str> = graph.keys().copied().collect(); let mut groups: Vec> = @@ -48,7 +54,9 @@ pub fn cycles(config: &Config, component_deps: &[ComponentDep]) -> Vec Vec = covered .iter() - .filter(|dep| { - members.contains(dep.from.as_str()) && members.contains(dep.to.as_str()) + .filter(|component_dep| { + members.contains(component_dep.from.as_str()) + && members.contains(component_dep.to.as_str()) }) - .map(|dep| Place::new(dep.file.clone(), dep.line)) + .map(|component_dep| Place::new(component_dep.file.clone(), component_dep.line)) .collect(); evidence.sort(); Violation { @@ -83,11 +92,11 @@ pub fn cycles(config: &Config, component_deps: &[ComponentDep]) -> Vec bool, ) -> Vec { let mut all_changed: BTreeMap<(&str, &str), bool> = BTreeMap::new(); - for dep in component_deps { - let entry = all_changed.entry((&dep.from, &dep.to)).or_insert(true); - *entry &= changed(&dep.file, dep.line); + for component_dep in component_deps { + let entry = all_changed + .entry((&component_dep.from, &component_dep.to)) + .or_insert(true); + *entry &= changed(&component_dep.file, component_dep.line); } all_changed .into_iter() @@ -938,9 +940,14 @@ pub fn new_dependencies( pub fn metrics(config: &Config, component_deps: &[ComponentDep]) -> Vec { let mut out: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); let mut incoming: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); - for dep in component_deps { - out.entry(&dep.from).or_default().insert(&dep.to); - incoming.entry(&dep.to).or_default().insert(&dep.from); + for component_dep in component_deps { + out.entry(&component_dep.from) + .or_default() + .insert(&component_dep.to); + incoming + .entry(&component_dep.to) + .or_default() + .insert(&component_dep.from); } let mut found = Vec::new(); for (name, rule) in &config.rules { @@ -952,8 +959,8 @@ pub fn metrics(config: &Config, component_deps: &[ComponentDep]) -> Vec = component_deps .iter() - .filter(|dep| dep.from == *name) - .map(|dep| Place::new(dep.file.clone(), dep.line)) + .filter(|component_dep| component_dep.from == *name) + .map(|component_dep| Place::new(component_dep.file.clone(), component_dep.line)) .collect(); evidence.sort(); let Place { file, line, .. } = evidence[0].clone(); @@ -1531,7 +1538,7 @@ rules: let pairs = |component_deps: &[ComponentDep]| { let mut pairs: Vec<(String, String)> = component_deps .iter() - .map(|dep| (dep.from.clone(), dep.to.clone())) + .map(|component_dep| (component_dep.from.clone(), component_dep.to.clone())) .collect(); pairs.sort(); pairs diff --git a/src/diagram.rs b/src/diagram.rs index 88771530..505da2f0 100644 --- a/src/diagram.rs +++ b/src/diagram.rs @@ -304,12 +304,15 @@ pub fn check(policy: &Policy, component_deps: &[ComponentDep]) -> Result> = BTreeMap::new(); - for dep in component_deps + for component_dep in component_deps .iter() - .filter(|dep| drawn_needed(config, dep)) + .filter(|component_dep| drawn_needed(config, component_dep)) { - if !drawn.contains(&(dep.from.clone(), dep.to.clone())) { - missing.entry((&dep.from, &dep.to)).or_default().push(dep); + if !drawn.contains(&(component_dep.from.clone(), component_dep.to.clone())) { + missing + .entry((&component_dep.from, &component_dep.to)) + .or_default() + .push(component_dep); } } Ok(missing @@ -363,9 +366,9 @@ fn drawn_arrows(policy: &Policy) -> Result> { /// Whether a dependency has to be drawn: not the dependencies of the `tests` /// that `tests: auto` makes, and not those on `common` components, which /// every component may use. -fn drawn_needed(config: &Config, dep: &ComponentDep) -> bool { - let tests = config.tests.is_some() && dep.from == crate::config::TESTS; - !tests && !config.common.contains(&dep.to) +fn drawn_needed(config: &Config, component_dep: &ComponentDep) -> bool { + let tests = config.tests.is_some() && component_dep.from == crate::config::TESTS; + !tests && !config.common.contains(&component_dep.to) } /// The arrows of the diagram that no dependency stands for: pictures of @@ -379,7 +382,7 @@ pub fn unused_arrows( }; let real: BTreeSet<(&str, &str)> = component_deps .iter() - .map(|dep| (dep.from.as_str(), dep.to.as_str())) + .map(|component_dep| (component_dep.from.as_str(), component_dep.to.as_str())) .collect(); Ok(drawn .into_iter() diff --git a/src/flow.rs b/src/flow.rs index 5237f061..c25aeee1 100644 --- a/src/flow.rs +++ b/src/flow.rs @@ -4,11 +4,11 @@ //! file reaches everything the file imports. With `reach: symbols` a chain follows //! the definitions a call references instead: a node is a method or function (a //! symbol with the lines it spans) or what a file holds outside any of them (its -//! class bodies, constants, top-level code), and a dependency of one node on another -//! ([`NodeDep`]) is a reference at a line. +//! class bodies, constants, top-level code), and a node reaches another through a +//! reference at a line ([`NodeDep`]). //! -//! A dependency that no reference accounts for stays a dependency on everything in -//! its target, and so does a class or constant used with no method named, so no +//! A dependency that no reference accounts for still reaches every node of its +//! target, and so does a class or constant used with no method named, so no //! import is dropped for want of a range. The index is read into a flow in `scip::Indexed::flow`. //! //! `impact --diff` reads the flow whatever `reach` says: the uses of a definition the @@ -49,8 +49,8 @@ pub fn file_of(key: &str) -> &str { key.split_once(SEPARATOR).map_or(key, |(file, _)| file) } -/// A dependency of one node on another: a reference at `line` of the source node's -/// file to the target node. +/// One node reaching another: a reference at `line` of the source node's file to +/// the target node, or a method reaching the code of its own file that is in none. #[derive(Debug, Clone)] pub struct NodeDep { pub from: Node, diff --git a/src/graph.rs b/src/graph.rs index 6e197004..17b21e91 100644 --- a/src/graph.rs +++ b/src/graph.rs @@ -12,7 +12,7 @@ pub enum GraphFormat { /// One arrow of the component graph: how many dependencies it stands for, and /// whether any of them breaks a rule. struct Arrow { - deps: usize, + count: usize, violating: bool, } @@ -21,14 +21,14 @@ fn arrows( violations: &[Violation], ) -> BTreeMap<(String, String), Arrow> { let mut arrows: BTreeMap<(String, String), Arrow> = BTreeMap::new(); - for dep in component_deps { + for component_dep in component_deps { arrows - .entry((dep.from.clone(), dep.to.clone())) + .entry((component_dep.from.clone(), component_dep.to.clone())) .or_insert(Arrow { - deps: 0, + count: 0, violating: false, }) - .deps += 1; + .count += 1; } for v in violations { if matches!(v.rule, RuleId::Dependency | RuleId::Privacy) @@ -83,10 +83,10 @@ fn mermaid(nodes: &[&str], arrows: &BTreeMap<(String, String), Arrow>) -> String for (i, ((from, to), arrow)) in arrows.iter().enumerate() { let (from, to) = (&ids[from.as_str()], &ids[to.as_str()]); if arrow.violating { - out.push_str(&format!(" {from} -.->|{} ✗| {to}\n", arrow.deps)); + out.push_str(&format!(" {from} -.->|{} ✗| {to}\n", arrow.count)); red.push(i.to_string()); } else { - out.push_str(&format!(" {from} -->|{}| {to}\n", arrow.deps)); + out.push_str(&format!(" {from} -->|{}| {to}\n", arrow.count)); } } if !red.is_empty() { @@ -114,7 +114,7 @@ fn dot(nodes: &[&str], arrows: &BTreeMap<(String, String), Arrow>) -> String { " {} -> {} [label=\"{}\"{style}];\n", quote(from), quote(to), - arrow.deps + arrow.count )); } out.push_str("}\n"); diff --git a/src/init.rs b/src/init.rs index 4da89762..3f3f9cf9 100644 --- a/src/init.rs +++ b/src/init.rs @@ -178,10 +178,10 @@ pub fn run(root: &Path, force: bool, cache: &mut scan::Cache) -> Result let map = ComponentMap::new(&config)?; let (_, component_deps, _) = check::evaluate(&config, &map, &scanned.deps); let mut deps: BTreeMap> = BTreeMap::new(); - for dep in &component_deps { - deps.entry(dep.from.clone()) + for component_dep in &component_deps { + deps.entry(component_dep.from.clone()) .or_default() - .insert(dep.to.clone()); + .insert(component_dep.to.clone()); } std::fs::write(&path, render(&found, &deps))?; let mut out = format!( diff --git a/src/propose.rs b/src/propose.rs index 2b5ce610..79dc76e8 100644 --- a/src/propose.rs +++ b/src/propose.rs @@ -411,7 +411,7 @@ pub fn notes(config: &Config, map: &ComponentMap, proposals: &[Proposal]) -> Vec pub struct Step { pub from: String, pub to: String, - /// The import that makes the step, when the code has it. + /// The line of the code that writes the step, when the code has it. #[serde(skip_serializing_if = "Option::is_none")] pub file: Option, #[serde(skip_serializing_if = "Option::is_none")] @@ -437,12 +437,18 @@ impl Step { /// The step of components `from -> to`: the first line of the code that /// writes the dependency, else the first proposal that makes it. fn of_component_dep(from: &str, to: &str, component_deps: &[ComponentDep]) -> Self { - let dep = component_deps + let component_dep = component_deps .iter() - .filter(|dep| dep.from == from && dep.to == to) - .min_by_key(|dep| (proposal_at(dep.line).is_some(), &dep.file, dep.line)) + .filter(|component_dep| component_dep.from == from && component_dep.to == to) + .min_by_key(|component_dep| { + ( + proposal_at(component_dep.line).is_some(), + &component_dep.file, + component_dep.line, + ) + }) .expect("a step of a witness is a dependency between components"); - Step::at(from, to, &dep.file, dep.line) + Step::at(from, to, &component_dep.file, component_dep.line) } } @@ -591,8 +597,8 @@ fn consequence(graph: &Graph, v: Violation, component_deps: &[ComponentDep]) -> limit = Some(v.target.clone()); let targets: BTreeSet<&str> = component_deps .iter() - .filter(|dep| dep.from == v.from) - .map(|dep| dep.to.as_str()) + .filter(|component_dep| component_dep.from == v.from) + .map(|component_dep| component_dep.to.as_str()) .collect(); let witness = targets .into_iter() @@ -614,8 +620,8 @@ fn consequence(graph: &Graph, v: Violation, component_deps: &[ComponentDep]) -> proposals.extend( component_deps .iter() - .filter(|dep| dep.from == from && dep.to == to) - .filter_map(|dep| proposal_at(dep.line)), + .filter(|component_dep| component_dep.from == from && component_dep.to == to) + .filter_map(|component_dep| proposal_at(component_dep.line)), ); } } @@ -637,11 +643,17 @@ fn consequence(graph: &Graph, v: Violation, component_deps: &[ComponentDep]) -> fn cycle_witness(members: &BTreeSet<&str>, component_deps: &[ComponentDep]) -> Vec { let inside: Vec<&ComponentDep> = component_deps .iter() - .filter(|dep| members.contains(dep.from.as_str()) && members.contains(dep.to.as_str())) + .filter(|component_dep| { + members.contains(component_dep.from.as_str()) + && members.contains(component_dep.to.as_str()) + }) .collect(); let mut graph: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new(); - for dep in &inside { - graph.entry(&dep.from).or_default().insert(&dep.to); + for component_dep in &inside { + graph + .entry(&component_dep.from) + .or_default() + .insert(&component_dep.to); } let cycle = proposed_component_deps(members, component_deps) .into_iter() @@ -666,16 +678,16 @@ fn proposed_component_deps<'a>( members: &BTreeSet<&str>, component_deps: &'a [ComponentDep], ) -> BTreeSet<(&'a str, &'a str)> { - let inside = component_deps - .iter() - .filter(|dep| members.contains(dep.from.as_str()) && members.contains(dep.to.as_str())); + let inside = component_deps.iter().filter(|component_dep| { + members.contains(component_dep.from.as_str()) && members.contains(component_dep.to.as_str()) + }); let real: BTreeSet<(&str, &str)> = inside .clone() - .filter(|dep| proposal_at(dep.line).is_none()) - .map(|dep| (dep.from.as_str(), dep.to.as_str())) + .filter(|component_dep| proposal_at(component_dep.line).is_none()) + .map(|component_dep| (component_dep.from.as_str(), component_dep.to.as_str())) .collect(); inside - .map(|dep| (dep.from.as_str(), dep.to.as_str())) + .map(|component_dep| (component_dep.from.as_str(), component_dep.to.as_str())) .filter(|pair| !real.contains(pair)) .collect() } diff --git a/src/suggest.rs b/src/suggest.rs index bb8cd5f1..dc5df132 100644 --- a/src/suggest.rs +++ b/src/suggest.rs @@ -446,8 +446,10 @@ fn counts<'a>( } } let mut used: BTreeMap<(&str, &str), usize> = BTreeMap::new(); - for dep in component_deps { - *used.entry((&dep.from, &dep.to)).or_default() += 1; + for component_dep in component_deps { + *used + .entry((&component_dep.from, &component_dep.to)) + .or_default() += 1; } Counts { unindexed, used } } From f3ca99d33af9b0abb73f5ebd0d506c1cb18bea48 Mon Sep 17 00:00:00 2001 From: Kirill Mokevnin Date: Wed, 18 Nov 2026 22:06:08 -0500 Subject: [PATCH 3/4] refactor: name the flow's NodeDep NodeReach, as the glossary keeps dependency for what a file writes Refs #218 Co-Authored-By: Claude Opus 5.5 --- src/chains.rs | 10 +++++----- src/flow.rs | 8 ++++---- src/scip/mod.rs | 10 +++++----- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/chains.rs b/src/chains.rs index 819cef67..e42cc1c2 100644 --- a/src/chains.rs +++ b/src/chains.rs @@ -320,16 +320,16 @@ fn symbol_graph( let files = Files::new(files); let mut graph: BTreeMap> = BTreeMap::new(); let mut covered: BTreeSet<(&str, usize, &str)> = BTreeSet::new(); - for node_dep in &flow.node_deps { - let (from, to) = (node_dep.from.file.as_str(), node_dep.to.file.as_str()); + for node_reach in &flow.node_reaches { + let (from, to) = (node_reach.from.file.as_str(), node_reach.to.file.as_str()); if !files.known.contains(from) || !files.known.contains(to) { continue; } - covered.insert((from, node_dep.line, to)); + covered.insert((from, node_reach.line, to)); graph - .entry(node_dep.from.key()) + .entry(node_reach.from.key()) .or_default() - .insert((node_dep.to.key(), node_dep.line)); + .insert((node_reach.to.key(), node_reach.line)); } for dep in deps { let keys = dep.targets(); diff --git a/src/flow.rs b/src/flow.rs index c25aeee1..a03f6be3 100644 --- a/src/flow.rs +++ b/src/flow.rs @@ -5,7 +5,7 @@ //! the definitions a call references instead: a node is a method or function (a //! symbol with the lines it spans) or what a file holds outside any of them (its //! class bodies, constants, top-level code), and a node reaches another through a -//! reference at a line ([`NodeDep`]). +//! reference at a line ([`NodeReach`]). //! //! A dependency that no reference accounts for still reaches every node of its //! target, and so does a class or constant used with no method named, so no @@ -52,7 +52,7 @@ pub fn file_of(key: &str) -> &str { /// One node reaching another: a reference at `line` of the source node's file to /// the target node, or a method reaching the code of its own file that is in none. #[derive(Debug, Clone)] -pub struct NodeDep { +pub struct NodeReach { pub from: Node, pub to: Node, pub line: usize, @@ -60,7 +60,7 @@ pub struct NodeDep { /// A reference the index records at `line` of `file` to a definition: to the method /// it names, or to the own code of the file that defines the class or constant it -/// names. Unlike a [`NodeDep`], it is never widened to every method of a file, and a +/// names. Unlike a [`NodeReach`], it is never widened to every method of a file, and a /// module named on its own (an import) is none. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Use { @@ -73,7 +73,7 @@ pub struct Use { pub struct Flow { /// The methods of each file that the index gave a range. pub scopes: BTreeMap>, - pub node_deps: Vec, + pub node_reaches: Vec, /// Every reference of the index to a definition, as [`Flow::callers`] reads them. pub uses: Vec, /// The name of each method of `scopes` as its symbol spells it, without the diff --git a/src/scip/mod.rs b/src/scip/mod.rs index 92619962..aa005646 100644 --- a/src/scip/mod.rs +++ b/src/scip/mod.rs @@ -24,7 +24,7 @@ use protobuf::Message; use scip::types::{Index, Occurrence, PositionEncoding, occurrence::Typed_range}; use crate::check::{SymbolRef, Unjudged}; -use crate::flow::{Flow, Node, NodeDep, Use}; +use crate::flow::{Flow, Node, NodeReach, Use}; use crate::lang::parts::Part; use crate::lang::registry; use crate::lang::{ @@ -1736,11 +1736,11 @@ impl Indexed<'_> { } // A method reaches the code of its own file that is in none: the class body and the // constants that run when the file loads. - let own: Vec = flow + let own: Vec = flow .scopes .iter() .flat_map(|(file, scopes)| { - scopes.iter().map(|scope| NodeDep { + scopes.iter().map(|scope| NodeReach { from: Node { file: file.clone(), scope: Some(scope.symbol.clone()), @@ -1750,7 +1750,7 @@ impl Indexed<'_> { }) }) .collect(); - flow.node_deps.extend(own); + flow.node_reaches.extend(own); for document in documents { // The files whose method a line names: such a line reaches that method, and a // reference to the class around it (`Document` of `Document.host`) adds nothing. @@ -1801,7 +1801,7 @@ impl Indexed<'_> { for from in flow.owners(&document.path, reference.line) { for to in &targets { if from != *to { - flow.node_deps.push(NodeDep { + flow.node_reaches.push(NodeReach { from: from.clone(), to: to.clone(), line: reference.line, From 65168f3cf42972d1d32d14a0c11e4dbbf6a40124 Mon Sep 17 00:00:00 2001 From: Kirill Mokevnin Date: Wed, 18 Nov 2026 22:06:20 -0500 Subject: [PATCH 4/4] refactor: say dependency, not edge, for what a Cargo manifest declares Refs #218 Co-Authored-By: Claude Opus 5.5 --- src/packages/cargo.rs | 30 +++++++++++++++--------------- src/packages/declared.rs | 4 ++-- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/packages/cargo.rs b/src/packages/cargo.rs index e2dd0971..41a48e0e 100644 --- a/src/packages/cargo.rs +++ b/src/packages/cargo.rs @@ -308,7 +308,7 @@ fn item(text: &str) -> Item<'_> { /// The dependencies of the tables, put where the features say they belong: an optional /// one is a dependency of what turns it on, and of its implicit feature when nothing -/// names it with `dep:`; and the items of the features, which are edges of their own. +/// names it with `dep:`; and the items of the features, which are dependencies of their own. fn with_features(declared: Vec, items: &[(usize, String, String)]) -> Vec { let named = |name: &str| { items @@ -371,8 +371,8 @@ fn with_features(declared: Vec, items: &[(usize, String, String)]) -> Vec ..d.clone() }) }; - let mut edge = |name: &str, feature: Option<&str>| { - // A name no table declares is a mistake Cargo reports; it is no edge. + let mut add_dep = |name: &str, feature: Option<&str>| { + // A name no table declares is a mistake Cargo reports; it is no dependency. if let Some(base) = base(name) { out.push(Entry { part: from.clone(), @@ -382,16 +382,16 @@ fn with_features(declared: Vec, items: &[(usize, String, String)]) -> Vec } }; match item(text) { - Item::Dependency(name) => edge(name, None), + Item::Dependency(name) => add_dep(name, None), Item::Reaches { name, feature, weak, } => { if !weak { - edge(name, None); + add_dep(name, None); } - edge(name, Some(feature)); + add_dep(name, Some(feature)); } Item::Feature(name) => out.push(Entry { line: *line, @@ -756,7 +756,7 @@ mod tests { ); /// The dependencies of a crate at the root of the project, alone in it. - fn edges_of(text: &str) -> Vec { + fn deps_of(text: &str) -> Vec { listed_in("Cargo.toml", text, &[]) .declared .into_iter() @@ -791,7 +791,7 @@ mod tests { let n = |x: &str| x.to_string(); let own = || Source::Path(String::new()); assert_eq!( - edges_of(text), + deps_of(text), [ // `default` is the package itself; `fake` is a feature of it. (2, n("fake"), None, reaches("feature/fake"), own()), @@ -844,7 +844,7 @@ mod tests { /// `default` is no part: a feature item that names it reaches the package itself. #[test] fn the_default_feature_is_the_whole_package() { - let rows = edges_of("[features]\ndefault = []\nfull = [\"default\"]\n"); + let rows = deps_of("[features]\ndefault = []\nfull = [\"default\"]\n"); assert_eq!( rows, [( @@ -859,7 +859,7 @@ mod tests { #[test] fn a_literal_string_is_an_item_too() { - let rows = edges_of( + let rows = deps_of( "[features]\nfake = ['dep:serde']\n\n[dependencies]\nserde = { version = \"1\", optional = true }\n", ); assert_eq!( @@ -886,7 +886,7 @@ mod tests { "[features]\n", "f = [\"x/g\"]\n", ); - let items: Vec<_> = edges_of(text).into_iter().filter(|r| r.0 == 8).collect(); + let items: Vec<_> = deps_of(text).into_iter().filter(|r| r.0 == 8).collect(); let f = Some("feature/f".to_string()); assert_eq!( items, @@ -905,7 +905,7 @@ mod tests { #[test] fn an_item_that_names_no_dependency_declares_none() { - let rows = edges_of("[features]\nf = [\"typo/g\", \"dep:typo\"]\n"); + let rows = deps_of("[features]\nf = [\"typo/g\", \"dep:typo\"]\n"); assert!(rows.is_empty(), "{rows:?}"); } @@ -961,7 +961,7 @@ mod tests { } /// (line, the part it leaves, what it reaches and the part of it) for each dependency. - fn edge_list(files: &[(&str, &str)]) -> Vec<(usize, Option, String, Option)> { + fn dep_list(files: &[(&str, &str)]) -> Vec<(usize, Option, String, Option)> { let dir = tempfile::TempDir::new().unwrap(); let mut names = Vec::new(); for (path, text) in files { @@ -995,7 +995,7 @@ mod tests { fn a_feature_item_reaches_the_feature_of_another_manifest_of_the_project() { let s = |x: &str| Some(x.to_string()); let n = |x: &str| x.to_string(); - let got = edge_list(&[ + let got = dep_list(&[ ( "Cargo.toml", "[workspace]\n\n[workspace.dependencies]\nstorage-api = { path = \"crates/storage-api\" }\n", @@ -1037,7 +1037,7 @@ mod tests { #[test] fn default_as_a_target_is_the_package_itself() { let own = "crates/telegram/Cargo.toml".to_string(); - let got = edge_list(&[( + let got = dep_list(&[( "crates/telegram/Cargo.toml", "[features]\ndefault = []\nfull = [\"default\"]\n", )]); diff --git a/src/packages/declared.rs b/src/packages/declared.rs index 37d69088..9c21b6bf 100644 --- a/src/packages/declared.rs +++ b/src/packages/declared.rs @@ -606,7 +606,7 @@ pub(crate) mod tests { }; /// (file, line, what it reaches and the part of it) for each dependency. - fn fake_edges(found: &Declarations) -> Vec<(String, usize, String, Option)> { + fn fake_deps(found: &Declarations) -> Vec<(String, usize, String, Option)> { found .deps .iter() @@ -647,7 +647,7 @@ pub(crate) mod tests { let found = declared_in(&[&DEPS_TXT], &files, &read, |file| file != "c/deps.txt"); let s = |x: &str| x.to_string(); assert_eq!( - fake_edges(&found), + fake_deps(&found), [ (s("a/deps.txt"), 2, s("b/deps.txt"), None), (s("a/deps.txt"), 3, s("b/deps.txt"), Some(s("fast"))),