Skip to main content

vvv_engine/
understanding.rs

1//! The questions about the whole tree rather than one file: what a package
2//! offers, who depends on a declaration, what nothing refers to, which
3//! imports are worth a look. Each is a walk over the graph's fragments —
4//! every file's placed declarations and resolved edges — and answers with
5//! plain data, the uncertainty counted rather than hidden.
6
7use std::collections::{BTreeMap, BTreeSet, HashSet};
8use std::path::PathBuf;
9
10use vvv_core::{Address, LanguageId, PackageId, Parsed};
11
12use crate::command::{Command, Context};
13use crate::graph::{Candidate, Declared, Node, Structure};
14use crate::{
15    Confidence, Consumer, Dead, DeadQuery, EngineError, Exposed, Impact, ImpactQuery, ImportSite,
16    ImportsQuery, ImportsReport, Placed, Reach, ReferencesQuery, Surface, SurfaceQuery,
17    Unreferenced,
18};
19
20impl Placed {
21    /// A fragment's declaration as an answer names it: with its file and line.
22    fn of(candidate: &Candidate, declared: &Declared) -> Self {
23        Self {
24            path: candidate.path().into(),
25            symbol: declared.symbol.clone(),
26            start: candidate
27                .file()
28                .source()
29                .position(declared.symbol.name_span.start),
30            address: declared.address.clone(),
31            reach: declared.reach.clone(),
32        }
33    }
34}
35
36/// What a package offers to everyone: its `pub` declarations — a re-export
37/// never widens what it re-exports — plus every address a re-export offers
38/// them at, with how many files take them.
39impl Command for SurfaceQuery {
40    type Output = Surface;
41
42    fn run(self, cx: &mut Context<'_>) -> Result<Self::Output, EngineError> {
43        let package = self.package.as_deref().map(PackageId::new);
44        let mut items: Vec<Exposed> = Vec::new();
45        let structure = Structure::of(&mut cx.graph)?;
46        for (ns, fragments) in structure.iter() {
47            for Node {
48                candidate,
49                fragment,
50            } in fragments
51            {
52                for declared in &fragment.declarations {
53                    if package
54                        .as_ref()
55                        .is_some_and(|p| declared.address.package() != p)
56                    {
57                        continue;
58                    }
59                    if declared.reach != Reach::Everyone {
60                        continue;
61                    }
62                    // Every address a re-export chain offers it at, itself first.
63                    let addresses =
64                        cx.graph
65                            .aliases_of(ns, &declared.address, &declared.symbol.name)?;
66                    let importers = fragments
67                        .iter()
68                        .filter(|n| n.path() != candidate.path())
69                        .filter(|n| {
70                            n.fragment
71                                .imports()
72                                .any(|e| e.address.as_ref().is_some_and(|a| addresses.contains(a)))
73                        })
74                        .count();
75                    items.push(Exposed {
76                        declaration: Placed::of(candidate, declared),
77                        via: addresses[1..].to_vec(),
78                        importers,
79                    });
80                }
81            }
82        }
83        items.sort_by(|a, b| a.declaration.address.cmp(&b.declaration.address));
84        Ok(Surface { package, items })
85    }
86}
87
88/// Who would feel a change to a declaration: the modules importing it (or
89/// an address that re-exports it), then the modules importing those,
90/// outward, each module once at the depth it is first reached.
91impl Command for ImpactQuery {
92    type Output = Impact;
93
94    fn run(self, cx: &mut Context<'_>) -> Result<Self::Output, EngineError> {
95        let graph = &mut *cx.graph;
96        let query = ReferencesQuery::new(self.name.as_str());
97        let query = match &self.declared_in {
98            Some(file) => query.declared_in(file),
99            None => query,
100        };
101        let evidence = graph.references(&query)?;
102        let declaration =
103            evidence
104                .declarations
105                .first()
106                .ok_or_else(|| EngineError::NoSuchSymbol {
107                    name: self.name.clone(),
108                    kind: None,
109                })?;
110        let ns = graph
111            .namespace(&declaration.language)
112            .ok_or_else(|| EngineError::NoLayout(declaration.language.clone()))?;
113        let address = declaration
114            .address
115            .clone()
116            .ok_or_else(|| EngineError::NoLayout(declaration.language.clone()))?;
117        let aliases = graph.aliases_of(&ns, &address, &self.name)?;
118        let fragments = graph.fragments(&ns)?;
119
120        // Breadth first over module imports: what reaches an address in the
121        // frontier joins the next ring.
122        let mut consumers: Vec<Consumer> = Vec::new();
123        let mut seen: HashSet<Address> = HashSet::new();
124        let mut frontier: Vec<Address> = aliases.clone();
125        let declaring = address.parent().unwrap_or_else(|| address.clone());
126        let mut depth = 1;
127        while !frontier.is_empty() && depth <= 8 {
128            let mut next = Vec::new();
129            for node in &fragments {
130                let Some(module) = &node.fragment.module else {
131                    continue;
132                };
133                if seen.contains(module) || module == &declaring {
134                    continue;
135                }
136                let through = node
137                    .fragment
138                    .imports()
139                    .filter_map(|e| e.address.as_ref())
140                    .find(|a| frontier.iter().any(|f| a.starts_with(f)))
141                    .and_then(|a| {
142                        frontier.iter().find(|f| a.starts_with(f)).map(|f| {
143                            if depth == 1 {
144                                declaring.clone()
145                            } else {
146                                f.clone()
147                            }
148                        })
149                    });
150                if let Some(through) = through {
151                    seen.insert(module.clone());
152                    consumers.push(Consumer {
153                        module: module.clone(),
154                        path: node.path().into(),
155                        depth,
156                        through,
157                    });
158                    next.push(module.clone());
159                }
160            }
161            frontier = next;
162            depth += 1;
163        }
164        Ok(Impact {
165            name: self.name,
166            address,
167            consumers,
168        })
169    }
170}
171
172/// Declarations nothing in the workspace refers to — no resolved token
173/// other than the declaration's own name — with how many tokens vvv could
174/// not judge and so might be a use after all.
175impl Command for DeadQuery {
176    type Output = Dead;
177
178    fn run(self, cx: &mut Context<'_>) -> Result<Self::Output, EngineError> {
179        let graph = &mut *cx.graph;
180        let mut items = Vec::new();
181        let languages: Vec<LanguageId> = graph
182            .language_ids()
183            .into_iter()
184            .filter(|id| self.language.as_ref().is_none_or(|l| l == id))
185            .collect();
186        for id in languages {
187            let Some(ns) = graph.namespace(&id) else {
188                continue;
189            };
190            let fragments = graph.fragments(&ns)?;
191            let mut asked: BTreeSet<(PathBuf, String)> = BTreeSet::new();
192            for Node {
193                candidate,
194                fragment,
195            } in &fragments
196            {
197                for declared in &fragment.declarations {
198                    // Pieces of one declaration (a type and its impls) are
199                    // one question.
200                    if !asked.insert((candidate.path().to_path_buf(), declared.symbol.name.clone()))
201                    {
202                        continue;
203                    }
204                    let query = ReferencesQuery::new(declared.symbol.name.as_str())
205                        .in_language(id.clone())
206                        .declared_in(candidate.path());
207                    let evidence = graph.references(&query)?;
208                    let own_names: Vec<_> = fragment
209                        .declarations
210                        .iter()
211                        .filter(|d| d.symbol.name == declared.symbol.name)
212                        .map(|d| d.symbol.name_span)
213                        .collect();
214                    let (mut used, mut unsure) = (false, 0);
215                    for o in &evidence.occurrences {
216                        let is_own_name =
217                            o.m.path == candidate.path() && own_names.contains(&o.m.span);
218                        match o.confidence {
219                            Confidence::Resolved if !is_own_name => used = true,
220                            Confidence::Unresolved => unsure += 1,
221                            _ => {}
222                        }
223                    }
224                    if !used {
225                        items.push(Unreferenced {
226                            declaration: Placed::of(candidate, declared),
227                            unsure,
228                        });
229                    }
230                }
231            }
232        }
233        items.sort_by(|a, b| {
234            (&a.declaration.path, a.declaration.start)
235                .cmp(&(&b.declaration.path, b.declaration.start))
236        });
237        Ok(Dead { items })
238    }
239}
240
241/// Import statements worth a look, per file or across the tree.
242impl Command for ImportsQuery {
243    type Output = ImportsReport;
244
245    fn run(self, cx: &mut Context<'_>) -> Result<Self::Output, EngineError> {
246        let path = self.path.as_deref().map(|p| cx.workspace.normalize(p));
247        let mut report = ImportsReport {
248            path: path.clone().map(Into::into),
249            unused: Vec::new(),
250            unresolved: Vec::new(),
251            redundant: Vec::new(),
252            unplaced: Vec::new(),
253        };
254        let structure = Structure::of(&mut cx.graph)?;
255        for (ns, fragments) in structure.iter() {
256            for Node {
257                candidate,
258                fragment,
259            } in fragments
260            {
261                if path.as_deref().is_some_and(|p| p != candidate.path()) {
262                    continue;
263                }
264                if fragment.module.is_none() {
265                    report.unplaced.push(candidate.path().into());
266                    continue;
267                }
268                let facts = candidate.facts()?;
269                let source = candidate.file().source();
270                let parsed = Parsed {
271                    path: candidate.path(),
272                    source,
273                    facts,
274                };
275                let site = |edge: &crate::graph::Edge| ImportSite {
276                    path: candidate.path().into(),
277                    import: edge.import.clone(),
278                    start: source.position(edge.import.span.start),
279                    address: edge.address.clone(),
280                };
281                // What each statement brings in: a glob of `X` and `X`
282                // itself are different things.
283                let mut brought: BTreeMap<(Address, bool), usize> = BTreeMap::new();
284                for edge in fragment.imports() {
285                    if parsed.is_group_prefix(&edge.import) {
286                        continue;
287                    }
288                    if edge.address.is_none() {
289                        report.unresolved.push(site(edge));
290                        continue;
291                    }
292                    if let Some(address) = &edge.address {
293                        let seen = brought
294                            .entry((address.clone(), edge.import.glob))
295                            .or_default();
296                        *seen += 1;
297                        if *seen > 1 {
298                            report.redundant.push(site(edge));
299                            continue;
300                        }
301                    }
302                    // A re-export is used by its takers; a language that hides
303                    // which names an import takes cannot be judged by tokens.
304                    if edge.import.reexport || ns.semantics().import_scopes_names {
305                        continue;
306                    }
307                    let Some(bound) = edge.import.binding() else {
308                        continue;
309                    };
310                    let statement = edge
311                        .import
312                        .group
313                        .as_ref()
314                        .map_or(edge.import.span, |g| g.statement);
315                    let used = facts
316                        .tokens_named(bound.as_str())
317                        .any(|(span, _)| !statement.contains(&span));
318                    if !used {
319                        report.unused.push(site(edge));
320                    }
321                }
322            }
323        }
324        Ok(report)
325    }
326}