1use 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 oracle: Option<Arc<dyn Oracle>>,
19 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 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 pub fn with_retention(self, retention: Retention) -> Self {
51 Self { retention, ..self }
52 }
53
54 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 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 pub fn touched(&self) {
83 self.graph
84 .lock()
85 .unwrap_or_else(std::sync::PoisonError::into_inner)
86 .touched();
87 }
88
89 pub fn root(&self) -> &Path {
91 self.workspace.root()
92 }
93
94 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 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}