aboutsummaryrefslogtreecommitdiff
path: root/lib/xixanta/src/context.rs
blob: 32f9de94d9b7f30e26484e8eb2e9b9670a247e6e (plain)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use crate::instruction::PString;
use std::collections::HashMap;

const GLOBAL_CONTEXT: &str = "Global";

#[derive(Debug)]
pub struct PValue {
    pub node: PString,
    pub value: usize,
    pub label: bool,
}

#[derive(Debug)]
pub struct Context {
    stack: Vec<String>,
    map: HashMap<String, HashMap<String, PValue>>,
}

impl Default for Context {
    fn default() -> Self {
        Context::new()
    }
}

impl Context {
    pub fn new() -> Self {
        Context {
            stack: vec![],
            map: HashMap::from([(String::from(GLOBAL_CONTEXT), HashMap::new())]),
        }
    }

    pub fn global(&mut self) {
        self.stack = vec![];
    }

    pub fn find(&self, name: &str) -> Option<&HashMap<String, PValue>> {
        self.map.get(name)
    }

    pub fn current(&self) -> Option<&HashMap<String, PValue>> {
        match self.stack.last() {
            Some(name) => self.map.get(name),
            None => self.map.get(GLOBAL_CONTEXT),
        }
    }

    pub fn current_mut(&mut self) -> Option<&mut HashMap<String, PValue>> {
        match self.stack.last() {
            Some(name) => self.map.get_mut(name),
            None => self.map.get_mut(GLOBAL_CONTEXT),
        }
    }

    pub fn push(&mut self, identifier: &String) {
        let name = match self.stack.last() {
            Some(n) => n.to_owned() + &String::from("::") + identifier,
            None => identifier.to_string(),
        };

        self.stack.push(name.clone());
        self.map.entry(name).or_default();
    }

    pub fn push_stack(&mut self, identifier: &String) {
        let name = match self.stack.last() {
            Some(n) => n.to_owned() + &String::from("::") + identifier,
            None => identifier.to_string(),
        };

        self.stack.push(name.clone());
    }

    pub fn pop(&mut self) -> bool {
        if self.stack.is_empty() {
            return false;
        }

        self.stack.truncate(self.stack.len() - 1);
        true
    }
}