Skip to main content

vvv_engine/capabilities/
search.rs

1//! Structural and symbolic search: request, result, execution, and report.
2use crate::protocol::display::{Line, Role};
3use crate::protocol::vocabulary::{Files, Mark};
4use crate::report::lines as l;
5use crate::report::{Block, Document};
6use crate::{EngineError, Match, Skipped};
7use serde::{Deserialize, Serialize};
8use vvv_core::Query;
9
10/// A structural or symbolic search with a typed engine answer.
11/// Plugin predicates remain separate from engine-owned workspace filters.
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
14pub struct SearchQuery {
15    #[serde(flatten)]
16    pub query: Query,
17    #[serde(default, skip_serializing_if = "SearchScope::is_empty")]
18    pub scope: SearchScope,
19}
20
21/// Explicit file/directory prefixes and owning package names or IDs.
22/// Alternatives within each list are ORed; the two lists are intersected.
23#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
24#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
25#[serde(default, deny_unknown_fields)]
26pub struct SearchScope {
27    pub paths: Vec<crate::RelPath>,
28    pub packages: Vec<String>,
29}
30impl SearchScope {
31    pub fn is_empty(&self) -> bool {
32        self.paths.is_empty() && self.packages.is_empty()
33    }
34    pub fn validate(&self) -> Result<(), EngineError> {
35        use std::path::Component;
36        if self.paths.iter().any(|p| {
37            p.as_str().contains(['\\', ':', '\0'])
38                || p.components()
39                    .any(|c| !matches!(c, Component::Normal(_) | Component::CurDir))
40        }) || self.packages.iter().any(|p| p.is_empty())
41        {
42            return Err(EngineError::InvalidSearchScope);
43        }
44        Ok(())
45    }
46    pub(crate) fn includes_path(&self, path: &std::path::Path) -> bool {
47        self.paths.is_empty()
48            || self.paths.iter().any(|prefix| {
49                let normalized: std::path::PathBuf = prefix
50                    .components()
51                    .filter(|c| !matches!(c, std::path::Component::CurDir))
52                    .collect();
53                path.starts_with(normalized)
54            })
55    }
56    pub(crate) fn includes_package(&self, package: Option<&vvv_core::Package>) -> bool {
57        self.packages.is_empty()
58            || package.is_some_and(|p| {
59                self.packages
60                    .iter()
61                    .any(|filter| filter == p.id.as_str() || filter == &p.name)
62            })
63    }
64}
65
66/// `vvv search`: what was found, and which languages could not be asked.
67#[derive(Debug, Clone, Serialize, Deserialize)]
68#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
69pub struct Search {
70    pub query: Query,
71    #[serde(default, skip_serializing_if = "SearchScope::is_empty")]
72    pub scope: SearchScope,
73    pub matches: Vec<Match>,
74    /// Languages whose grammar could not compile the query; their files
75    /// were not searched.
76    #[serde(default, skip_serializing_if = "Vec::is_empty")]
77    pub skipped: Vec<Skipped>,
78}
79
80impl From<vvv_core::Query> for SearchQuery {
81    fn from(query: vvv_core::Query) -> Self {
82        Self {
83            query,
84            scope: SearchScope::default(),
85        }
86    }
87}
88
89/// Structural or symbolic search across the workspace: only files spelling
90/// the query's literal words are parsed.
91impl SearchQuery {
92    pub fn scoped(mut self, scope: SearchScope) -> Self {
93        self.scope = scope;
94        self
95    }
96    /// Answer with the concrete result of this query.
97    pub fn execute(self, engine: &crate::Engine) -> Result<Search, EngineError> {
98        let _operation = engine.operation();
99        let mut graph = engine.graph()?;
100        self.execute_in(&mut graph)
101    }
102
103    pub(crate) fn execute_in(self, graph: &mut crate::graph::Graph) -> Result<Search, EngineError> {
104        self.query.check()?;
105        self.scope.validate()?;
106        graph.search_scoped(&self.query, &self.scope)
107    }
108}
109
110impl Document {
111    pub fn search(matches: &[Match], skipped: &[Skipped]) -> Self {
112        let mut report = Self::new();
113        report.block_body(Block::Matches(matches.to_vec()));
114        if matches.is_empty() {
115            report.block_note(Block::Summary(
116                Line::mark(Mark::Nothing).and(Role::Plain, " no matches"),
117            ));
118        } else {
119            report.block_note(Block::Summary(Self::search_summary(matches)));
120        }
121        for skipped in skipped {
122            report.warning(l::SkippedLine::new(skipped).line());
123        }
124        report
125    }
126
127    /// `● 1  ○ 59   13 files`: what the search found.
128    fn search_summary(matches: &[Match]) -> Line {
129        let (declarations, uses) = l::Sections::split(matches);
130        let mut counts: Vec<Line> = Vec::new();
131        if !declarations.is_empty() {
132            counts.push(
133                Line::mark(Mark::Declaration)
134                    .and(Role::Plain, " ")
135                    .and(Role::Plain, declarations.len().to_string()),
136            );
137        }
138        if !uses.is_empty() {
139            counts.push(
140                Line::single(Role::Dim, "○")
141                    .and(Role::Plain, " ")
142                    .and(Role::Plain, uses.len().to_string()),
143            );
144        }
145        Self::join(counts, "  ").and(Role::Plain, "  ").and(
146            Role::Dim,
147            Files::among(matches.iter().map(|m| m.path.as_path())).to_string(),
148        )
149    }
150}
151
152#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
153#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
154#[serde(deny_unknown_fields)]
155pub struct SearchPageQuery {
156    pub query: Query,
157    #[serde(default)]
158    pub scope: SearchScope,
159    #[serde(default)]
160    pub page: crate::PageBudget,
161}
162#[derive(Debug, Clone, Serialize, Deserialize)]
163#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
164#[serde(tag = "kind", rename = "search")]
165pub struct SearchPage {
166    #[serde(default, skip_serializing_if = "SearchScope::is_empty")]
167    pub scope: SearchScope,
168    pub snapshot: crate::SnapshotId,
169    pub query: Query,
170    pub items: Vec<SearchPageItem>,
171    pub skipped: Vec<Skipped>,
172    pub total_items: usize,
173    pub next_cursor: Option<crate::Cursor>,
174}
175#[derive(Debug, Clone, Serialize, Deserialize)]
176#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
177pub struct SearchPageItem {
178    /// Absolute, one-based position in the complete search ordering.
179    pub ordinal: usize,
180    #[serde(flatten)]
181    pub item: Match,
182}
183#[derive(Debug, Clone, Serialize)]
184pub(crate) struct SearchSession {
185    pub next: usize,
186}
187impl SearchPageQuery {
188    pub fn execute(self, engine: &crate::Engine) -> Result<SearchPage, EngineError> {
189        let _operation = engine.operation();
190        self.execute_in(engine)
191    }
192    pub(crate) fn execute_in(self, engine: &crate::Engine) -> Result<SearchPage, EngineError> {
193        use crate::{graph::query_snapshot::QuerySnapshot, query_store::QueryData};
194        self.page.validate()?;
195        self.query.check()?;
196        self.scope.validate()?;
197        let (mut graph, snapshot) = QuerySnapshot::capture(engine)?;
198        let search = graph.search_bounded(
199            &self.query,
200            &self.scope,
201            crate::QueryLimits::default().max_query_bytes,
202        )?;
203        let mut session = super::pagination::PageSession::new(
204            engine,
205            snapshot,
206            &(&self.query, &self.scope),
207            QueryData::Search(search),
208        );
209        let result = SearchSession { next: 0 }.page(engine, &mut session, self.page);
210        match session.finish(engine, result)? {
211            crate::PageReply::Search(page) => Ok(page),
212            _ => unreachable!("capability returns its own page"),
213        }
214    }
215}
216impl SearchSession {
217    pub(crate) fn page(
218        mut self,
219        engine: &crate::Engine,
220        session: &mut super::pagination::PageSession,
221        budget: crate::PageBudget,
222    ) -> Result<crate::PageReply, EngineError> {
223        use crate::{
224            PageReply,
225            query_store::{Checkpoint, QueryData},
226        };
227        let QueryData::Search(search) = &session.root.data else {
228            return Err(EngineError::InvalidCursor);
229        };
230        let mut page = SearchPage {
231            scope: search.scope.clone(),
232            snapshot: session.root.identity.clone(),
233            query: search.query.clone(),
234            items: vec![],
235            skipped: search.skipped.clone(),
236            total_items: search.matches.len(),
237            next_cursor: None,
238        };
239        while self.next < search.matches.len() && page.items.len() < budget.max_items {
240            page.items.push(SearchPageItem {
241                ordinal: self.next + 1,
242                item: search.matches[self.next].clone(),
243            });
244            let after = Self {
245                next: self.next + 1,
246            };
247            page.next_cursor = (after.next < search.matches.len())
248                .then(|| session.token(engine, &Checkpoint::Search(after.clone())));
249            if let Err(EngineError::OutputLimit {
250                max_bytes,
251                required_bytes,
252            }) = budget.check(&PageReply::Search(page.clone()))
253            {
254                if page.items.len() == 1 {
255                    let m = &page.items[0].item;
256                    return Err(EngineError::PageOutputLimit {
257                        max_bytes,
258                        required_bytes,
259                        anchor: m.content.clone().map(|content| crate::SourceAnchor {
260                            path: m.path.clone(),
261                            content,
262                            span: m.span,
263                        }),
264                    });
265                }
266                page.items.pop();
267                break;
268            }
269            self = after;
270        }
271        let next = Checkpoint::Search(self.clone());
272        page.next_cursor = (self.next < search.matches.len()).then(|| session.token(engine, &next));
273        let reply = PageReply::Search(page);
274        budget.check(&reply)?;
275        if reply.next_cursor().is_some() {
276            session.retain(next);
277        }
278        Ok(reply)
279    }
280}
281impl Document {
282    pub(crate) fn search_page(page: &SearchPage) -> Self {
283        let mut doc = Self::new();
284        for item in &page.items {
285            doc.body([Line::single(Role::Plain, item.ordinal.to_string())
286                .and(Role::Plain, " ")
287                .and(Role::Path, item.item.path.to_string())
288                .and(Role::Plain, " ")
289                .and(Role::Plain, &item.item.text)]);
290        }
291        for skipped in &page.skipped {
292            doc.warning(l::SkippedLine::new(skipped).line());
293        }
294        doc
295    }
296}