Skip to main content

vvv_engine/
engine.rs

1//! The runtime: what holds the graph and runs commands against it.
2
3use std::path::Path;
4use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5use std::sync::{Arc, Mutex, MutexGuard};
6
7use vvv_core::{LanguageRegistry, Oracle};
8
9use crate::graph::{Graph, Retention};
10use crate::{EngineError, LanguageId, Workspace};
11
12#[derive(Clone)]
13pub struct Engine {
14    workspace: Workspace,
15    languages: LanguageRegistry,
16    pub(crate) file_previews: Arc<Mutex<crate::capabilities::file::FileCache>>,
17    retention: Retention,
18    /// What a per-call graph is built with; a session's graph holds its own.
19    oracle: Option<Arc<dyn Oracle>>,
20    /// Shared by clones, so a session's worker and its owner see one graph.
21    graph: Arc<Mutex<Graph>>,
22    /// One complete operation, including planning, writes and recovery.
23    operation: Arc<Mutex<()>>,
24    /// Invalidation does not acquire or refresh the graph.
25    dirty: Arc<AtomicBool>,
26    queries: Arc<Mutex<crate::query_store::QueryStore>>,
27    plans: Arc<Mutex<crate::plan_store::PlanStore>>,
28    query_revision: Arc<AtomicU64>,
29    cancellation: Option<crate::ReadCancellation>,
30}
31
32impl std::fmt::Debug for Engine {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        f.debug_struct("Engine")
35            .field("workspace", &self.workspace)
36            .field("retention", &self.retention)
37            .field("oracle", &self.oracle.is_some())
38            .finish_non_exhaustive()
39    }
40}
41
42impl Engine {
43    /// An engine over `workspace` that understands `languages`. Reads the
44    /// tree afresh for every graph-dependent request unless
45    /// [`Engine::with_retention`] says otherwise.
46    pub fn new(workspace: Workspace, languages: LanguageRegistry) -> Self {
47        let graph = Graph::new(workspace.clone(), languages.clone());
48        Self {
49            workspace,
50            languages,
51            file_previews: Arc::new(Mutex::new(crate::capabilities::file::FileCache::default())),
52            retention: Retention::default(),
53            oracle: None,
54            graph: Arc::new(Mutex::new(graph)),
55            operation: Arc::new(Mutex::new(())),
56            dirty: Arc::new(AtomicBool::new(false)),
57            queries: Arc::new(Mutex::new(crate::query_store::QueryStore::default())),
58            query_revision: Arc::new(AtomicU64::new(0)),
59            cancellation: None,
60            plans: Arc::new(Mutex::new(crate::plan_store::PlanStore::default())),
61        }
62    }
63
64    /// Keep files and facts between commands ([`Retention::Session`]) or
65    /// read the workspace afresh each time (the default).
66    pub fn with_retention(self, retention: Retention) -> Self {
67        Self { retention, ..self }
68    }
69
70    /// Run one request under operation exclusion. Acquire the graph only for
71    /// capabilities that need source-tree facts; retain mutation plans until
72    /// the caller applies them or converts the execution to a wire answer.
73    /// A typed query goes through its capability method, not this dispatcher:
74    ///
75    /// ```compile_fail,E0308
76    /// use vvv_engine::{Engine, Languages, MemoryVfs, Query, Workspace};
77    /// use std::sync::Arc;
78    /// let engine = Engine::new(Workspace::new("/ws", Arc::new(MemoryVfs::new())), Languages::new());
79    /// engine.run(Query::pattern("foo"));
80    /// ```
81    pub fn run(&self, request: crate::Request) -> Result<Execution, EngineError> {
82        let _operation = self.operation();
83        self.check_read()?;
84        let result = (|| {
85            Ok(match request {
86                crate::Request::DiscardPlan(query) => {
87                    Execution::Completed(crate::Answer::DiscardPlan(query.execute_in(self)?))
88                }
89                crate::Request::ValidatePlan(query) => {
90                    Execution::Completed(crate::Answer::ValidatePlan(query.execute_in(self)?))
91                }
92                crate::Request::ApplyPlan(query) => {
93                    Execution::Completed(crate::Answer::ApplyPlan(query.execute_in(self)?))
94                }
95                crate::Request::InspectPlan(query) => {
96                    Execution::Completed(crate::Answer::InspectPlan(query.execute_in(self)?))
97                }
98                crate::Request::PrepareMove(query) => {
99                    Execution::Completed(crate::Answer::PrepareMove(query.execute_in(self)?))
100                }
101                crate::Request::PrepareRewrite(query) => {
102                    Execution::Completed(crate::Answer::PrepareRewrite(query.execute_in(self)?))
103                }
104                crate::Request::ReviewPlan(query) => {
105                    Execution::Completed(crate::Answer::ReviewPlan(query.execute_in(self)?))
106                }
107                crate::Request::PrepareRename(query) => {
108                    Execution::Completed(crate::Answer::PrepareRename(query.execute_in(self)?))
109                }
110                #[cfg(feature = "schema")]
111                crate::Request::Schema(query) => {
112                    Execution::Completed(crate::Answer::Schema(query.execute()?))
113                }
114                crate::Request::SearchPage(query) => {
115                    Execution::Completed(crate::Answer::SearchPage(query.execute_in(self)?))
116                }
117                crate::Request::ContextPage(query) => {
118                    Execution::Completed(crate::Answer::ContextPage(query.execute_in(self)?))
119                }
120                crate::Request::Continue(query) => {
121                    Execution::Completed(crate::Answer::Continue(query.execute_in(self)?))
122                }
123                crate::Request::Expand(query) => {
124                    Execution::Completed(crate::Answer::Expand(query.execute_in(self)?))
125                }
126                crate::Request::Discover(query) => {
127                    Execution::Completed(crate::Answer::Discover(query.execute(self)))
128                }
129                crate::Request::Context(query) => Execution::Completed(crate::Answer::Context(
130                    query.execute_in(&mut *self.graph()?)?,
131                )),
132                crate::Request::PrepareMoveSymbol(query) => {
133                    Execution::Completed(crate::Answer::PrepareMoveSymbol(query.execute_in(self)?))
134                }
135                crate::Request::SymbolMoveCandidates(query) => {
136                    Execution::Completed(crate::Answer::SymbolMoveCandidates(
137                        query.execute_in(&mut *self.graph()?, self.workspace())?,
138                    ))
139                }
140                crate::Request::Relationships(query) => {
141                    Execution::Completed(crate::Answer::Relationships(query.execute_in(self)?))
142                }
143                crate::Request::Resolve(query) => Execution::Completed(crate::Answer::Resolve(
144                    query.execute_in(&mut *self.graph()?)?,
145                )),
146                crate::Request::Navigate(query) => Execution::Completed(crate::Answer::Navigate(
147                    query.execute_in(&mut *self.graph()?)?,
148                )),
149                crate::Request::Search(query) => Execution::Completed(crate::Answer::Search(
150                    query.execute_in(&mut *self.graph()?)?,
151                )),
152                crate::Request::Outline(query) => Execution::Completed(crate::Answer::Outline(
153                    query.execute_in(&mut *self.graph()?, self.workspace())?,
154                )),
155                crate::Request::References(query) => Execution::Completed(
156                    crate::Answer::References(query.execute_in(&mut *self.graph()?)?),
157                ),
158                crate::Request::Where(query) => Execution::Completed(crate::Answer::Where(
159                    query.execute_in(&mut *self.graph()?, self.workspace())?,
160                )),
161                crate::Request::Deps(query) => Execution::Completed(crate::Answer::Deps(
162                    query.execute_in(&mut *self.graph()?, self.workspace())?,
163                )),
164                crate::Request::Explain(query) => Execution::Completed(crate::Answer::Explain(
165                    query.execute_in(&mut *self.graph()?, self.workspace())?,
166                )),
167                crate::Request::Surface(query) => Execution::Completed(crate::Answer::Surface(
168                    query.execute_in(&mut *self.graph()?)?,
169                )),
170                crate::Request::Impact(query) => Execution::Completed(crate::Answer::Impact(
171                    query.execute_in(&mut *self.graph()?)?,
172                )),
173                crate::Request::Dead(query) => Execution::Completed(crate::Answer::Dead(
174                    query.execute_in(&mut *self.graph()?)?,
175                )),
176                crate::Request::Imports(query) => Execution::Completed(crate::Answer::Imports(
177                    query.execute_in(&mut *self.graph()?, self.workspace())?,
178                )),
179                crate::Request::WorkspaceFiles(query) => {
180                    Execution::Completed(crate::Answer::WorkspaceFiles(query.execute_in(self)?))
181                }
182                crate::Request::File(query) => {
183                    Execution::Completed(crate::Answer::File(query.execute_in(self)?))
184                }
185                crate::Request::Rename { intent, apply } => {
186                    let planned = {
187                        let mut graph = self.graph()?;
188                        intent.plan_in(&mut graph, self.workspace())?
189                    };
190                    self.mutation(planned, apply)?
191                }
192                crate::Request::Move { intent, apply } => {
193                    let planned = {
194                        let mut graph = self.graph()?;
195                        intent.plan_in(&mut graph, self.workspace())?
196                    };
197                    self.mutation(planned, apply)?
198                }
199                crate::Request::MoveSymbol { intent, apply } => {
200                    let planned = {
201                        let mut graph = self.graph()?;
202                        intent.plan_in(&mut graph, self.workspace())?
203                    };
204                    self.mutation(planned, apply)?
205                }
206                crate::Request::Rewrite { intent, apply } => {
207                    let planned = {
208                        let mut graph = self.graph()?;
209                        intent.plan_in(&mut graph, self.workspace())?
210                    };
211                    self.mutation(planned, apply)?
212                }
213                crate::Request::Batch { intent, apply } => {
214                    self.mutation(intent.plan_in(self)?, apply)?
215                }
216                crate::Request::History => Execution::Completed(crate::Answer::History(
217                    crate::Ledger::new(self).history_in()?,
218                )),
219                crate::Request::Undo => {
220                    Execution::Completed(crate::Answer::Undo(crate::Ledger::new(self).undo_in()?))
221                }
222            })
223        })();
224        self.check_read()?;
225        result
226    }
227
228    fn mutation<T: crate::Mutation>(
229        &self,
230        planned: crate::Planned<T>,
231        apply: bool,
232    ) -> Result<Execution, EngineError> {
233        if apply {
234            Ok(Execution::Applied(
235                crate::Apply(planned).apply_in(self)?.into_mutation(),
236            ))
237        } else {
238            Ok(Execution::Preview(planned.into_mutation()))
239        }
240    }
241
242    /// Ask `oracle` about the tokens syntax cannot place — a build, a
243    /// language server, an index the host has. The graph judges every token
244    /// by imports first; the oracle is consulted only where that says `?`,
245    /// and its answer counts only when it names a declaration the graph
246    /// knows.
247    pub fn with_oracle(mut self, oracle: Arc<dyn Oracle>) -> Self {
248        {
249            let _operation = self.operation();
250            let mut graph = self
251                .graph
252                .lock()
253                .unwrap_or_else(std::sync::PoisonError::into_inner);
254            *graph = Graph::new(self.workspace.clone(), self.languages.clone())
255                .with_oracle(oracle.clone());
256        }
257        self.oracle = Some(oracle);
258        self
259    }
260
261    /// Tell a session the tree changed behind its back — an editor wrote,
262    /// say — so its next command walks even within the trusted window.
263    pub fn touched(&self) {
264        self.dirty.store(true, Ordering::Release);
265        self.query_revision.fetch_add(1, Ordering::AcqRel);
266    }
267
268    /// The workspace root, absolute.
269    pub fn root(&self) -> &Path {
270        self.workspace.root()
271    }
272
273    /// The languages this engine understands.
274    pub fn language_ids(&self) -> Vec<LanguageId> {
275        self.languages.iter().map(|l| l.id().clone()).collect()
276    }
277
278    pub(crate) fn plans(&self) -> MutexGuard<'_, crate::plan_store::PlanStore> {
279        self.plans
280            .lock()
281            .unwrap_or_else(std::sync::PoisonError::into_inner)
282    }
283    pub(crate) fn queries(&self) -> MutexGuard<'_, crate::query_store::QueryStore> {
284        self.queries
285            .lock()
286            .unwrap_or_else(std::sync::PoisonError::into_inner)
287    }
288    pub(crate) fn query_revision(&self) -> u64 {
289        self.query_revision.load(Ordering::Acquire)
290    }
291
292    pub(crate) fn with_cancellation(&self, cancellation: crate::ReadCancellation) -> Self {
293        Self {
294            cancellation: Some(cancellation),
295            ..self.clone()
296        }
297    }
298    pub(crate) fn without_cancellation(&self) -> Self {
299        Self {
300            cancellation: None,
301            ..self.clone()
302        }
303    }
304    pub(crate) fn cancellation(&self) -> Option<crate::ReadCancellation> {
305        self.cancellation.clone()
306    }
307    pub(crate) fn check_read(&self) -> Result<(), EngineError> {
308        self.cancellation
309            .as_ref()
310            .map_or(Ok(()), crate::ReadCancellation::check)
311    }
312    pub(crate) fn publish_read<T>(
313        &self,
314        publish: impl FnOnce() -> Result<T, EngineError>,
315    ) -> Result<T, EngineError> {
316        match &self.cancellation {
317            Some(c) => c.complete(publish),
318            None => publish(),
319        }
320    }
321
322    pub(crate) fn oracle(&self) -> Option<Arc<dyn Oracle>> {
323        self.oracle.clone()
324    }
325
326    pub(crate) fn workspace(&self) -> &Workspace {
327        &self.workspace
328    }
329
330    pub(crate) fn languages(&self) -> &LanguageRegistry {
331        &self.languages
332    }
333
334    /// Shared by clones; acquire before the graph or transaction work.
335    pub(crate) fn operation(&self) -> MutexGuard<'_, ()> {
336        self.operation
337            .lock()
338            .unwrap_or_else(std::sync::PoisonError::into_inner)
339    }
340
341    /// A fresh staging session for batch composition.
342    pub(crate) fn staged(&self) -> (Engine, Workspace) {
343        let staging = self.workspace.staged();
344        let engine =
345            Engine::new(staging.clone(), self.languages.clone()).with_retention(Retention::PerCall);
346        (engine, staging)
347    }
348
349    /// The graph, brought up to date with the tree. Held for the command;
350    /// per-file work happens on the candidates it hands out.
351    pub(crate) fn graph(&self) -> Result<MutexGuard<'_, Graph>, EngineError> {
352        let mut graph = self
353            .graph
354            .lock()
355            .unwrap_or_else(std::sync::PoisonError::into_inner);
356        if self.dirty.swap(false, Ordering::AcqRel) {
357            graph.touched();
358        }
359        if self.retention == Retention::PerCall {
360            let fresh = Graph::new(self.workspace.clone(), self.languages.clone());
361            *graph = match &self.oracle {
362                Some(oracle) => fresh.with_oracle(oracle.clone()),
363                None => fresh,
364            };
365        }
366        graph.cancellation = self.cancellation();
367        graph.refresh(self.retention)?;
368        Ok(graph)
369    }
370}
371
372/// An in-process result. Only mutation previews carry executable plans.
373#[derive(Debug)]
374pub enum Execution {
375    Completed(crate::Answer),
376    Preview(crate::Planned<crate::MutationAnswer>),
377    Applied(crate::Applied<crate::MutationAnswer>),
378}
379
380/// The kind of retained result requested by an in-process caller.
381#[derive(Debug, Clone, Copy, PartialEq, Eq)]
382pub enum ExecutionKind {
383    Completed,
384    Preview,
385    Applied,
386}
387
388impl std::fmt::Display for ExecutionKind {
389    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
390        f.write_str(match self {
391            Self::Completed => "completed",
392            Self::Preview => "preview",
393            Self::Applied => "applied",
394        })
395    }
396}
397
398impl Execution {
399    pub fn kind(&self) -> ExecutionKind {
400        match self {
401            Self::Completed(_) => ExecutionKind::Completed,
402            Self::Preview(_) => ExecutionKind::Preview,
403            Self::Applied(_) => ExecutionKind::Applied,
404        }
405    }
406
407    /// Consume the retained handle at a reporting or wire boundary.
408    pub fn into_answer(self) -> crate::Answer {
409        match self {
410            Self::Completed(answer) => answer,
411            Self::Preview(planned) => planned.into_inner().into(),
412            Self::Applied(applied) => applied.into_inner().into(),
413        }
414    }
415
416    pub fn into_preview(self) -> Result<crate::Planned<crate::MutationAnswer>, EngineError> {
417        match self {
418            Self::Preview(planned) => Ok(planned),
419            other => Err(EngineError::ExecutionKind {
420                expected: ExecutionKind::Preview,
421                actual: other.kind(),
422            }),
423        }
424    }
425
426    pub fn into_applied(self) -> Result<crate::Applied<crate::MutationAnswer>, EngineError> {
427        match self {
428            Self::Applied(applied) => Ok(applied),
429            other => Err(EngineError::ExecutionKind {
430                expected: ExecutionKind::Applied,
431                actual: other.kind(),
432            }),
433        }
434    }
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440
441    #[test]
442    fn engine_clones_exclude_whole_operations_even_without_a_graph() {
443        let engine = Engine::new(
444            Workspace::new("/ws", Arc::new(crate::MemoryVfs::new())),
445            LanguageRegistry::new(),
446        );
447        let guard = engine.operation();
448        let clone = engine.clone();
449        let (started, ready) = std::sync::mpsc::channel();
450        let (finished, result) = std::sync::mpsc::channel();
451        let worker = std::thread::spawn(move || {
452            started.send(()).unwrap();
453            finished.send(crate::Ledger::new(&clone).history()).unwrap();
454        });
455        ready.recv().unwrap();
456        assert!(matches!(
457            result.recv_timeout(std::time::Duration::from_millis(50)),
458            Err(std::sync::mpsc::RecvTimeoutError::Timeout)
459        ));
460        drop(guard);
461        assert!(result.recv().unwrap().unwrap().entries.is_empty());
462        worker.join().unwrap();
463    }
464}