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::{Arc, Mutex, MutexGuard};
5
6use vvv_core::{LanguageRegistry, Oracle};
7
8use crate::command::{Command, Context};
9use crate::graph::{Graph, Retention};
10use crate::{EngineError, LanguageId, Workspace};
11
12#[derive(Clone)]
13pub struct Engine {
14    workspace: Workspace,
15    languages: LanguageRegistry,
16    retention: Retention,
17    /// What a per-call graph is built with; a session's graph holds its own.
18    oracle: Option<Arc<dyn Oracle>>,
19    /// Shared by clones, so a session's worker and its owner see one graph.
20    graph: Arc<Mutex<Graph>>,
21}
22
23impl std::fmt::Debug for Engine {
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        f.debug_struct("Engine")
26            .field("workspace", &self.workspace)
27            .field("retention", &self.retention)
28            .field("oracle", &self.oracle.is_some())
29            .finish_non_exhaustive()
30    }
31}
32
33impl Engine {
34    /// An engine over `workspace` that understands `languages`. Reads the
35    /// tree afresh for every command unless [`Engine::with_retention`] says
36    /// otherwise.
37    pub fn new(workspace: Workspace, languages: LanguageRegistry) -> Self {
38        let graph = Graph::new(workspace.clone(), languages.clone());
39        Self {
40            workspace,
41            languages,
42            retention: Retention::default(),
43            oracle: None,
44            graph: Arc::new(Mutex::new(graph)),
45        }
46    }
47
48    /// Keep files and facts between commands ([`Retention::Session`]) or
49    /// read the workspace afresh each time (the default).
50    pub fn with_retention(self, retention: Retention) -> Self {
51        Self { retention, ..self }
52    }
53
54    /// Run one command: bring the graph up to date with the tree, then let
55    /// the command answer against it.
56    pub fn run<C: Command>(&self, command: C) -> Result<C::Output, EngineError> {
57        let graph = self.graph()?;
58        let mut cx = Context::new(self, graph);
59        command.run(&mut cx)
60    }
61
62    /// Ask `oracle` about the tokens syntax cannot place — a build, a
63    /// language server, an index the host has. The graph judges every token
64    /// by imports first; the oracle is consulted only where that says `?`,
65    /// and its answer counts only when it names a declaration the graph
66    /// knows.
67    pub fn with_oracle(mut self, oracle: Arc<dyn Oracle>) -> Self {
68        {
69            let mut graph = self
70                .graph
71                .lock()
72                .unwrap_or_else(std::sync::PoisonError::into_inner);
73            *graph = Graph::new(self.workspace.clone(), self.languages.clone())
74                .with_oracle(oracle.clone());
75        }
76        self.oracle = Some(oracle);
77        self
78    }
79
80    /// Tell a session the tree changed behind its back — an editor wrote,
81    /// say — so its next command walks even within the trusted window.
82    pub fn touched(&self) {
83        self.graph
84            .lock()
85            .unwrap_or_else(std::sync::PoisonError::into_inner)
86            .touched();
87    }
88
89    /// The workspace root, absolute.
90    pub fn root(&self) -> &Path {
91        self.workspace.root()
92    }
93
94    /// The languages this engine understands.
95    pub fn language_ids(&self) -> Vec<LanguageId> {
96        self.languages.iter().map(|l| l.id().clone()).collect()
97    }
98
99    pub(crate) fn workspace(&self) -> &Workspace {
100        &self.workspace
101    }
102
103    pub(crate) fn languages(&self) -> &LanguageRegistry {
104        &self.languages
105    }
106
107    /// The graph, brought up to date with the tree. Held for the command;
108    /// per-file work happens on the candidates it hands out.
109    fn graph(&self) -> Result<MutexGuard<'_, Graph>, EngineError> {
110        let mut graph = self
111            .graph
112            .lock()
113            .unwrap_or_else(std::sync::PoisonError::into_inner);
114        if self.retention == Retention::PerCall {
115            let fresh = Graph::new(self.workspace.clone(), self.languages.clone());
116            *graph = match &self.oracle {
117                Some(oracle) => fresh.with_oracle(oracle.clone()),
118                None => fresh,
119            };
120        }
121        graph.refresh(self.retention)?;
122        Ok(graph)
123    }
124}