1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    sync::{Arc, Mutex, RwLock},
};

use bson::Bson;

pub use anyhow;
pub use serde_json;

use anyhow::Result;

pub type Vars = HashMap<Vec<u8>, Arc<RwLock<Bson>>>;
pub type VarsStack = Vec<Vars>;

pub trait IncludeAdaptor {
    fn include(&mut self, path: PathBuf) -> Option<Arc<Vec<u8>>>;
}

pub trait WildDocScript {
    fn new(state: WildDocState) -> Result<Self>
    where
        Self: Sized;
    fn evaluate_module(&mut self, file_name: &str, src: &[u8]) -> Result<()>;
    fn eval(&mut self, code: &[u8]) -> Result<Bson>;
}

#[derive(Clone)]
pub struct WildDocState {
    stack: Arc<RwLock<VarsStack>>,
    cache_dir: PathBuf,
    include_adaptor: Arc<Mutex<Box<dyn IncludeAdaptor + Send>>>,
}

impl WildDocState {
    pub fn new(
        stack: Arc<RwLock<VarsStack>>,
        cache_dir: PathBuf,
        include_adaptor: Arc<Mutex<Box<dyn IncludeAdaptor + Send>>>,
    ) -> Self {
        Self {
            stack,
            cache_dir,
            include_adaptor,
        }
    }

    #[inline(always)]
    pub fn cache_dir(&self) -> &Path {
        &self.cache_dir
    }

    #[inline(always)]
    pub fn stack(&self) -> Arc<RwLock<VarsStack>> {
        self.stack.clone()
    }

    #[inline(always)]
    pub fn include_adaptor(&self) -> &Mutex<Box<dyn IncludeAdaptor + Send>> {
        &self.include_adaptor
    }
}