Skip to main content

annotate/
global_environment.rs

1use crate::{Environment, Function, Module};
2use std::collections::HashMap;
3use std::sync::Mutex;
4
5use once_cell::sync::OnceCell;
6
7pub fn global_environment() -> &'static GlobalEnvironment {
8    static INSTANCE: OnceCell<GlobalEnvironment> = OnceCell::new();
9    INSTANCE.get_or_init(GlobalEnvironment::new)
10}
11
12pub fn register_environment(name: &str, environment: &'static Environment) {
13    global_environment().register(name, environment);
14}
15
16#[derive(Debug)]
17pub struct GlobalEnvironment {
18    environments: Mutex<HashMap<String, &'static Environment>>,
19}
20
21impl GlobalEnvironment {
22    pub fn new() -> Self {
23        Self {
24            environments: Mutex::new(Default::default()),
25        }
26    }
27
28    pub fn register(&self, name: &str, environment: &'static Environment) {
29        self.environments
30            .lock()
31            .unwrap()
32            .insert(name.to_string(), environment);
33    }
34
35    pub fn find_modules_such_that(&self, f: &impl Fn(&Module) -> bool) -> Vec<Module> {
36        self.environments
37            .lock()
38            .unwrap()
39            .values()
40            .flat_map(|each| each.find_modules_such_that(f))
41            .collect()
42    }
43
44    pub fn find_functions_such_that(&self, f: &impl Fn(&Function) -> bool) -> Vec<Function> {
45        self.environments
46            .lock()
47            .unwrap()
48            .values()
49            .flat_map(|each| each.find_functions_such_that(f))
50            .collect()
51    }
52}
53
54impl Default for GlobalEnvironment {
55    fn default() -> Self {
56        Self::new()
57    }
58}