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
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use std::clone::Clone;
use std::collections::HashMap;
use std::convert::AsRef;
use std::convert::Into;
use std::error::Error;
use std::rc::Rc;
use crate::ast::Position;
use crate::ast::PositionedItem;
use crate::build::ir::Val;
use crate::error;
pub fn find_in_fieldlist(target: &str, fs: &Vec<(String, Rc<Val>)>) -> Option<Rc<Val>> {
    for (key, val) in fs.iter().cloned() {
        if target == &key {
            return Some(val.clone());
        }
    }
    return None;
}
pub type ValueMap = HashMap<PositionedItem<String>, Rc<Val>>;
#[derive(Debug, PartialEq, Clone)]
pub struct Scope {
    pub import_stack: Vec<String>,
    pub env: Rc<Val>,
    pub curr_val: Option<Rc<Val>>,
    pub build_output: ValueMap,
    pub search_curr_val: bool,
    pub strict: bool,
}
impl Scope {
    
    pub fn new(env: Rc<Val>) -> Self {
        Self {
            import_stack: Vec::new(),
            env: env,
            
            
            curr_val: None,
            build_output: HashMap::new(),
            search_curr_val: false,
            strict: false,
        }
    }
    pub fn use_strict(mut self) -> Self {
        self.strict = true;
        self
    }
    pub fn use_curr_val(mut self) -> Self {
        self.search_curr_val = true;
        self
    }
    
    
    pub fn spawn_child(&self) -> Self {
        Self {
            import_stack: self.import_stack.clone(),
            env: self.env.clone(),
            
            curr_val: None,
            build_output: self.build_output.clone(),
            search_curr_val: false,
            strict: self.strict,
        }
    }
    pub fn spawn_clean(&self) -> Self {
        Self {
            import_stack: self.import_stack.clone(),
            env: self.env.clone(),
            
            curr_val: None,
            build_output: HashMap::new(),
            search_curr_val: false,
            strict: self.strict,
        }
    }
    
    pub fn push_import<S: Into<String>>(&mut self, path: S) {
        self.import_stack.push(path.into());
    }
    pub fn prepend_import_stack(&mut self, imports: &Vec<String>) {
        let mut new_stack = self.import_stack.clone();
        new_stack.append(imports.clone().as_mut());
        self.import_stack = new_stack;
    }
    
    pub fn set_curr_val(mut self, val: Rc<Val>) -> Self {
        self.curr_val = Some(val);
        self
    }
    
    pub fn lookup_idx(&self, pos: &Position, idx: &Val) -> Result<Rc<Val>, Box<dyn Error>> {
        if self.search_curr_val && self.curr_val.is_some() {
            if let &Val::List(ref fs) = self.curr_val.as_ref().unwrap().as_ref() {
                return Self::lookup_in_list(pos, idx, fs);
            }
        }
        Err(error::BuildError::with_pos(
            "Not a list in index lookup.",
            error::ErrorType::TypeFail,
            pos.clone(),
        )
        .to_boxed())
    }
    
    
    
    
    
    
    
    
    
    pub fn lookup_sym(&self, sym: &PositionedItem<String>, is_symbol: bool) -> Option<Rc<Val>> {
        if &sym.val == "env" && is_symbol {
            return Some(self.env.clone());
        }
        if &sym.val == "self" && is_symbol {
            return self.curr_val.clone();
        }
        if self.search_curr_val && self.curr_val.is_some() {
            match self.curr_val.as_ref().unwrap().as_ref() {
                Val::Env(ref fs) => {
                    for (name, val) in fs.iter() {
                        if name == &sym.val {
                            return Some(Rc::new(Val::Str(val.clone())));
                        }
                    }
                    if !self.strict {
                        return Some(Rc::new(Val::Empty));
                    }
                }
                Val::Tuple(ref fs) => match Self::lookup_in_tuple(&sym.pos, &sym.val, fs) {
                    Ok(v) => return Some(v),
                    Err(_) => {
                        
                    }
                },
                Val::List(ref fs) => {
                    match Self::lookup_in_list(&sym.pos, &Val::Str(sym.val.clone()), fs) {
                        Ok(v) => return Some(v),
                        Err(_) => {
                            
                        }
                    }
                }
                Val::Boolean(_)
                | Val::Empty
                | Val::Float(_)
                | Val::Int(_)
                | Val::Module(_)
                | Val::Str(_)
                | Val::Func(_) => {
                    
                }
            };
        }
        if self.build_output.contains_key(sym) {
            return Some(self.build_output[sym].clone());
        }
        None
    }
    fn lookup_in_tuple(
        pos: &Position,
        field: &str,
        fs: &Vec<(String, Rc<Val>)>,
    ) -> Result<Rc<Val>, Box<dyn Error>> {
        if let Some(vv) = find_in_fieldlist(&field, fs) {
            Ok(vv)
        } else {
            Err(error::BuildError::with_pos(
                format!("Unable to {} match element in tuple.", field,),
                error::ErrorType::NoSuchSymbol,
                pos.clone(),
            )
            .to_boxed())
        }
    }
    fn lookup_in_list(
        pos: &Position,
        field: &Val,
        elems: &Vec<Rc<Val>>,
    ) -> Result<Rc<Val>, Box<dyn Error>> {
        let idx = match field {
            &Val::Int(i) => i as usize,
            &Val::Str(ref s) => s.parse::<usize>()?,
            _ => {
                return Err(error::BuildError::with_pos(
                    format!("Invalid idx type {} for list lookup", field),
                    error::ErrorType::TypeFail,
                    pos.clone(),
                )
                .to_boxed());
            }
        };
        if idx < elems.len() {
            Ok(elems[idx].clone())
        } else {
            Err(error::BuildError::with_pos(
                format!("idx {} out of bounds in list", idx),
                error::ErrorType::NoSuchSymbol,
                pos.clone(),
            )
            .to_boxed())
        }
    }
}