swamp_script_semantic/
inst_cache.rs

1use seq_fmt::comma;
2use seq_map::{SeqMap, SeqMapError};
3use swamp_script_types::Type;
4use tracing::debug;
5
6/// It is not a proper Monomorphization cache, but similar
7#[derive(Debug, Clone)]
8pub struct InstantiationCache {
9    pub cache: SeqMap<String, Type>,
10}
11
12impl InstantiationCache {
13    pub fn new() -> Self {
14        Self {
15            cache: SeqMap::default(),
16        }
17    }
18
19    pub fn complete_name(path: &[String], base_name: &str, argument_types: &[Type]) -> String {
20        format!(
21            "{}::{}<{}>",
22            path.join("::"),
23            base_name,
24            comma(argument_types)
25        )
26    }
27    pub fn add(
28        &mut self,
29        path: &[String],
30        name: &str,
31        ty: Type,
32        argument_type: &[Type],
33    ) -> Result<(), SeqMapError> {
34        if let Type::Blueprint(_) = ty {
35            panic!("can not add blueprint to cache");
36        }
37        let converted_name = Self::complete_name(path, name, argument_type);
38        debug!(?converted_name, ?name, ?ty, "adding to instantiation cache");
39        self.cache.insert(converted_name, ty)
40    }
41
42    pub fn is_empty(&self) -> bool {
43        self.cache.is_empty()
44    }
45
46    pub fn get(&self, path: &[String], base_name: &str, argument_type: &[Type]) -> Option<&Type> {
47        let name = Self::complete_name(path, base_name, argument_type);
48        debug!(?name, ?path, ?base_name, ?argument_type, "checking cache");
49
50        self.cache.get(&name)
51    }
52}