Skip to main content

vvv_engine/capabilities/
usage.rs

1//! Declaration usage: impact and declarations with no resolved uses.
2use crate::graph::Node;
3use crate::protocol::display::{Line, Role};
4use crate::protocol::vocabulary::{Files, Mark};
5use crate::report::{Block, Document};
6use crate::{Confidence, EngineError, Placed, ReferencesQuery};
7use serde::{Deserialize, Serialize};
8use std::collections::{BTreeSet, HashSet};
9use std::path::PathBuf;
10use vvv_core::{Address, LanguageId, RelPath};
11
12/// `vvv impact <name>`: who would feel a change to a declaration.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
15pub struct ImpactQuery {
16    pub name: String,
17    /// The file declaring the symbol meant, when several share the name.
18    #[serde(default, skip_serializing_if = "Option::is_none")]
19    pub declared_in: Option<RelPath>,
20}
21
22/// `vvv dead`: declarations nothing in the workspace refers to.
23#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
24#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
25pub struct DeadQuery {
26    #[serde(default, skip_serializing_if = "Option::is_none")]
27    pub language: Option<vvv_core::LanguageId>,
28}
29
30/// `impact <name>`: every module that would feel a change to a declaration —
31/// those importing it, then those importing them, outward.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
34pub struct Impact {
35    pub name: String,
36    pub address: Address,
37    /// Nearest first: depth 1 imports the declaration itself.
38    pub consumers: Vec<Consumer>,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
42#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
43pub struct Consumer {
44    pub module: Address,
45    pub path: RelPath,
46    pub depth: u32,
47    /// The module it reaches the declaration through; the declaration's
48    /// own module at depth 1.
49    pub through: Address,
50}
51
52/// `dead [--lang]`: declarations nothing in the workspace refers to, with
53/// how many tokens might.
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
55#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
56pub struct Dead {
57    pub items: Vec<Unreferenced>,
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
61#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
62pub struct Unreferenced {
63    #[serde(flatten)]
64    pub declaration: Placed,
65    /// Tokens spelling the name that vvv could not judge: any of them might
66    /// be a use.
67    pub unsure: usize,
68}
69
70/// Who would feel a change to a declaration: the modules importing it (or
71/// an address that re-exports it), then the modules importing those,
72/// outward, each module once at the depth it is first reached.
73impl ImpactQuery {
74    /// Answer with the concrete result of this query.
75    pub fn execute(self, engine: &crate::Engine) -> Result<Impact, EngineError> {
76        let _operation = engine.operation();
77        let mut graph = engine.graph()?;
78        self.execute_in(&mut graph)
79    }
80
81    pub(crate) fn execute_in(self, graph: &mut crate::graph::Graph) -> Result<Impact, EngineError> {
82        let query = ReferencesQuery::new(self.name.as_str());
83        let query = match &self.declared_in {
84            Some(file) => query.declared_in(file),
85            None => query,
86        };
87        let evidence = graph.references(&query)?;
88        let declaration =
89            evidence
90                .declarations
91                .first()
92                .ok_or_else(|| EngineError::NoSuchSymbol {
93                    name: self.name.clone(),
94                    kind: None,
95                })?;
96        let ns = graph
97            .namespace(&declaration.language)
98            .ok_or_else(|| EngineError::NoLayout(declaration.language.clone()))?;
99        let address = declaration
100            .address
101            .clone()
102            .ok_or_else(|| EngineError::NoLayout(declaration.language.clone()))?;
103        let aliases = graph.aliases_of(&ns, &address, &self.name)?;
104        let fragments = graph.fragments(&ns)?;
105
106        // Breadth first over module imports: what reaches an address in the
107        // frontier joins the next ring.
108        let mut consumers: Vec<Consumer> = Vec::new();
109        let mut seen: HashSet<Address> = HashSet::new();
110        let mut frontier: Vec<Address> = aliases.clone();
111        let declaring = address.parent().unwrap_or_else(|| address.clone());
112        let mut depth = 1;
113        while !frontier.is_empty() && depth <= 8 {
114            let mut next = Vec::new();
115            for node in &fragments {
116                let Some(module) = &node.fragment.module else {
117                    continue;
118                };
119                if seen.contains(module) || module == &declaring {
120                    continue;
121                }
122                let through = node
123                    .fragment
124                    .imports()
125                    .filter_map(|e| e.address())
126                    .find(|a| frontier.iter().any(|f| a.starts_with(f)))
127                    .and_then(|a| {
128                        frontier.iter().find(|f| a.starts_with(f)).map(|f| {
129                            if depth == 1 {
130                                declaring.clone()
131                            } else {
132                                f.clone()
133                            }
134                        })
135                    });
136                if let Some(through) = through {
137                    seen.insert(module.clone());
138                    consumers.push(Consumer {
139                        module: module.clone(),
140                        path: node.path().into(),
141                        depth,
142                        through,
143                    });
144                    next.push(module.clone());
145                }
146            }
147            frontier = next;
148            depth += 1;
149        }
150        Ok(Impact {
151            name: self.name,
152            address,
153            consumers,
154        })
155    }
156}
157
158/// Declarations nothing in the workspace refers to — no resolved token
159/// other than the declaration's own name — with how many tokens vvv could
160/// not judge and so might be a use after all.
161impl DeadQuery {
162    /// Answer with the concrete result of this query.
163    pub fn execute(self, engine: &crate::Engine) -> Result<Dead, EngineError> {
164        let _operation = engine.operation();
165        let mut graph = engine.graph()?;
166        self.execute_in(&mut graph)
167    }
168
169    pub(crate) fn execute_in(self, graph: &mut crate::graph::Graph) -> Result<Dead, EngineError> {
170        let mut items = Vec::new();
171        let languages: Vec<LanguageId> = graph
172            .language_ids()
173            .into_iter()
174            .filter(|id| self.language.as_ref().is_none_or(|l| l == id))
175            .collect();
176        for id in languages {
177            let Some(ns) = graph.namespace(&id) else {
178                continue;
179            };
180            let fragments = graph.fragments(&ns)?;
181            let mut asked: BTreeSet<(PathBuf, String)> = BTreeSet::new();
182            for Node {
183                candidate,
184                fragment,
185            } in &fragments
186            {
187                for declared in &fragment.declarations {
188                    // Pieces of one declaration (a type and its impls) are
189                    // one question.
190                    if !asked.insert((candidate.path().to_path_buf(), declared.symbol.name.clone()))
191                    {
192                        continue;
193                    }
194                    let query = ReferencesQuery::new(declared.symbol.name.as_str())
195                        .in_language(id.clone())
196                        .declared_in(candidate.path());
197                    let evidence = graph.references(&query)?;
198                    let own_names: Vec<_> = fragment
199                        .declarations
200                        .iter()
201                        .filter(|d| d.symbol.name == declared.symbol.name)
202                        .map(|d| d.symbol.name_span)
203                        .collect();
204                    let (mut used, mut unsure) = (false, 0);
205                    for o in &evidence.occurrences {
206                        let is_own_name =
207                            o.m.path == candidate.path() && own_names.contains(&o.m.span);
208                        match o.confidence {
209                            Confidence::Resolved if !is_own_name => used = true,
210                            Confidence::Unresolved => unsure += 1,
211                            _ => {}
212                        }
213                    }
214                    if !used {
215                        items.push(Unreferenced {
216                            declaration: candidate.placed(declared),
217                            unsure,
218                        });
219                    }
220                }
221            }
222        }
223        items.sort_by(|a, b| {
224            (&a.declaration.path, a.declaration.start)
225                .cmp(&(&b.declaration.path, b.declaration.start))
226        });
227        Ok(Dead { items })
228    }
229}
230
231impl Document {
232    pub(crate) fn impact(result: &Impact) -> Self {
233        let mut report = Self::new();
234        report.body([Line::single(Role::Title, format!("impact {}", result.name))]);
235        if result.consumers.is_empty() {
236            report.block_note(Block::Summary(
237                Line::mark(Mark::Nothing).and(Role::Plain, " no module imports it"),
238            ));
239            return report;
240        }
241        report.block_body(Block::Consumers(result.consumers.clone()));
242        report.block_note(Block::Summary(
243            Line::mark(Mark::ImportedBy)
244                .and(Role::Plain, " ")
245                .and(Role::Strong, result.consumers.len().to_string())
246                .and(Role::Plain, "   ")
247                .and(
248                    Role::Dim,
249                    Files::among(result.consumers.iter().map(|c| c.path.as_path())).to_string(),
250                ),
251        ));
252        report
253    }
254
255    pub(crate) fn dead(result: &Dead) -> Self {
256        let mut report = Self::new();
257        report.title("dead");
258        if result.items.is_empty() {
259            report.block_note(Block::Summary(
260                Line::mark(Mark::Nothing).and(Role::Plain, " everything is referred to"),
261            ));
262            return report;
263        }
264        report.block_body(Block::Dead(result.items.clone()));
265        report.block_note(Block::Summary(Self::dead_summary(result)));
266        report
267    }
268
269    fn dead_summary(result: &Dead) -> Line {
270        let unsure = result.items.iter().filter(|i| i.unsure > 0).count();
271        Line::mark(Mark::Declaration)
272            .and(Role::Plain, " ")
273            .and(Role::Strong, result.items.len().to_string())
274            .and(Role::Plain, "   ")
275            .and_line(Line::mark(Mark::Unverified))
276            .and(Role::Plain, " ")
277            .and(
278                Role::Dim,
279                format!("{unsure} with tokens that might be uses"),
280            )
281    }
282}