Skip to main content

vvv_engine/capabilities/
surface.rs

1//! Public package exposure and its consumers.
2use crate::graph::{Node, Structure};
3use crate::protocol::display::{Line, Role};
4use crate::protocol::vocabulary::Mark;
5use crate::report::{Block, Document};
6use crate::{EngineError, Placed, Reach};
7use serde::{Deserialize, Serialize};
8use vvv_core::{Address, PackageId};
9
10/// `vvv surface [package]`: what a package offers to everyone.
11#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
12#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
13pub struct SurfaceQuery {
14    #[serde(default, skip_serializing_if = "Option::is_none")]
15    pub package: Option<String>,
16}
17
18/// `surface [package]`: what a package offers to everyone, and who takes it.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
21pub struct Surface {
22    /// The package asked about; every package when absent.
23    #[serde(default, skip_serializing_if = "Option::is_none")]
24    pub package: Option<vvv_core::PackageId>,
25    pub items: Vec<Exposed>,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
30pub struct Exposed {
31    #[serde(flatten)]
32    pub declaration: Placed,
33    /// The other addresses it is offered at, through re-exports.
34    #[serde(default, skip_serializing_if = "Vec::is_empty")]
35    pub via: Vec<Address>,
36    /// Files in the workspace importing it, at any of its addresses.
37    pub importers: usize,
38}
39
40/// What a package offers to everyone: its `pub` declarations — a re-export
41/// never widens what it re-exports — plus every address a re-export offers
42/// them at, with how many files take them.
43impl SurfaceQuery {
44    /// Answer with the concrete result of this query.
45    pub fn execute(self, engine: &crate::Engine) -> Result<Surface, EngineError> {
46        let _operation = engine.operation();
47        let mut graph = engine.graph()?;
48        self.execute_in(&mut graph)
49    }
50
51    pub(crate) fn execute_in(
52        self,
53        graph: &mut crate::graph::Graph,
54    ) -> Result<Surface, EngineError> {
55        let package = self.package.as_deref().map(PackageId::new);
56        let mut items: Vec<Exposed> = Vec::new();
57        let structure = Structure::of(graph)?;
58        for (ns, fragments) in structure.iter() {
59            for Node {
60                candidate,
61                fragment,
62            } in fragments
63            {
64                for declared in &fragment.declarations {
65                    if package
66                        .as_ref()
67                        .is_some_and(|p| declared.address.package() != p)
68                    {
69                        continue;
70                    }
71                    if declared.reach != Reach::Everyone {
72                        continue;
73                    }
74                    // Every address a re-export chain offers it at, itself first.
75                    let addresses =
76                        graph.aliases_of(ns, &declared.address, &declared.symbol.name)?;
77                    let importers = fragments
78                        .iter()
79                        .filter(|n| n.path() != candidate.path())
80                        .filter(|n| {
81                            n.fragment
82                                .imports()
83                                .any(|e| e.address().is_some_and(|a| addresses.contains(a)))
84                        })
85                        .count();
86                    items.push(Exposed {
87                        declaration: candidate.placed(declared),
88                        via: addresses[1..].to_vec(),
89                        importers,
90                    });
91                }
92            }
93        }
94        items.sort_by(|a, b| a.declaration.address.cmp(&b.declaration.address));
95        Ok(Surface { package, items })
96    }
97}
98
99impl Document {
100    pub(crate) fn surface(result: &Surface) -> Self {
101        let mut report = Self::new();
102        let scope = result
103            .package
104            .as_ref()
105            .map_or_else(|| "every package".to_owned(), ToString::to_string);
106        report.title(format!("surface {scope}"));
107        if result.items.is_empty() {
108            report.block_note(Block::Summary(
109                Line::mark(Mark::Nothing).and(Role::Plain, " nothing exposed"),
110            ));
111            return report;
112        }
113        report.block_body(Block::Exposed(result.items.clone()));
114        report.block_note(Block::Summary(Self::surface_summary(result)));
115        report
116    }
117
118    fn surface_summary(result: &Surface) -> Line {
119        let importers: usize = result.items.iter().map(|i| i.importers).sum();
120        Line::mark(Mark::Declaration)
121            .and(Role::Plain, " ")
122            .and(Role::Strong, result.items.len().to_string())
123            .and(Role::Plain, "   ")
124            .and_line(Line::mark(Mark::ImportedBy))
125            .and(Role::Plain, " ")
126            .and(Role::Dim, format!("{importers} imports"))
127    }
128}