-
Notifications
You must be signed in to change notification settings - Fork 0
/
scope.rs
66 lines (56 loc) · 1.92 KB
/
scope.rs
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
//! This module implements the runtime scope chain of lox programming language.
use std::{cell::RefCell, rc::Rc};
use rlox_span::SymbolId;
use rustc_hash::FxHashMap;
use super::{types::LoxValueKind, LoxRuntimeError};
/// [Scope] keeps track of a chain of mapping from [SymbolId] to [ObjectId] which is active
/// at a specific point in the execution of the program.
/// [Scope] are "immutable", and every declaration
#[derive(Debug, Default)]
pub struct Scope {
symbols: RefCell<FxHashMap<SymbolId, LoxValueKind>>,
enclosing_scope: Option<Rc<Scope>>,
}
impl Scope {
pub fn new(
symbols: FxHashMap<SymbolId, LoxValueKind>,
enclosing_scope: Option<Rc<Scope>>,
) -> Self {
Self {
symbols: RefCell::new(symbols),
enclosing_scope,
}
}
pub fn spawn_empty_child(self: &Rc<Self>) -> Rc<Self> {
Rc::new(Scope::new(FxHashMap::default(), Some(Rc::clone(self))))
}
pub fn define(self: &Rc<Self>, symbol: SymbolId, object: LoxValueKind) -> Self {
let enclosing_scope = Rc::clone(self);
let mut symbols = FxHashMap::default();
symbols.insert(symbol, object);
Self::new(symbols, Some(enclosing_scope))
}
pub fn get_lvalue_symbol(&self, symbol: SymbolId) -> Option<LoxValueKind> {
if let Some(object) = self.symbols.borrow().get(&symbol) {
Some(object.clone())
} else {
self
.enclosing_scope
.as_ref()
.and_then(|s| s.get_lvalue_symbol(symbol))
}
}
pub fn assign(&self, symbol: SymbolId, value: LoxValueKind) -> Result<(), LoxRuntimeError> {
if let Some(object) = self.symbols.borrow_mut().get_mut(&symbol) {
*object = value;
Ok(())
} else if let Some(scope) = &self.enclosing_scope {
scope.assign(symbol, value)
} else {
Err(LoxRuntimeError::UnresolvedReference)
}
}
pub fn assign_current_level(&self, symbol: SymbolId, value: LoxValueKind) {
self.symbols.borrow_mut().insert(symbol, value);
}
}