Skip to main content

strata_js/engine/
scope.rs

1//! Lexical scope environment frame, closure descriptors, and parameter binding.
2
3use super::ast::Stmt;
4use crate::JsValue;
5use std::cell::RefCell;
6use std::collections::HashMap;
7use std::rc::Rc;
8
9/// Lexical scope environment frame supporting lexical nesting and closures.
10#[derive(Debug, Clone, PartialEq)]
11pub struct Scope {
12    pub parent: Option<Rc<RefCell<Scope>>>,
13    pub bindings: HashMap<String, JsValue>,
14}
15
16impl Scope {
17    pub fn new_root() -> Rc<RefCell<Self>> {
18        Rc::new(RefCell::new(Self {
19            parent: None,
20            bindings: HashMap::new(),
21        }))
22    }
23
24    pub fn new_child(parent: Rc<RefCell<Self>>) -> Rc<RefCell<Self>> {
25        Rc::new(RefCell::new(Self {
26            parent: Some(parent),
27            bindings: HashMap::new(),
28        }))
29    }
30
31    pub fn get(&self, name: &str) -> Option<JsValue> {
32        if let Some(val) = self.bindings.get(name) {
33            return Some(val.clone());
34        }
35        if let Some(ref parent) = self.parent {
36            return parent.borrow().get(name);
37        }
38        None
39    }
40
41    pub fn has(&self, name: &str) -> bool {
42        if self.bindings.contains_key(name) {
43            return true;
44        }
45        if let Some(ref parent) = self.parent {
46            return parent.borrow().has(name);
47        }
48        false
49    }
50
51    pub fn set(&mut self, name: &str, val: JsValue) -> bool {
52        if self.bindings.contains_key(name) {
53            self.bindings.insert(name.to_string(), val);
54            return true;
55        }
56        if let Some(ref parent) = self.parent {
57            return parent.borrow_mut().set(name, val);
58        }
59        false
60    }
61
62    pub fn declare(&mut self, name: &str, val: JsValue) {
63        self.bindings.insert(name.to_string(), val);
64    }
65}
66
67/// Represents an executable JavaScript function closure capturing its lexical environment.
68#[derive(Clone)]
69pub struct JsClosure {
70    pub id: u64,
71    pub name: Option<String>,
72    pub params: Vec<String>,
73    pub body: Vec<Stmt>,
74    pub env: Rc<RefCell<Scope>>,
75    pub is_async: bool,
76    pub is_generator: bool,
77}
78
79#[cfg(debug_assertions)]
80pub const MAX_CALL_STACK_DEPTH: usize = 48;
81#[cfg(not(debug_assertions))]
82pub const MAX_CALL_STACK_DEPTH: usize = 128;
83
84pub fn bind_parameters(params: &[String], args: Vec<JsValue>, scope: &Rc<RefCell<Scope>>) {
85    let mut arg_iter = args.into_iter();
86    for param in params {
87        if let Some(rest_name) = param.strip_prefix("...") {
88            let rest_vals: Vec<JsValue> = arg_iter.by_ref().collect();
89            scope
90                .borrow_mut()
91                .declare(rest_name, JsValue::new_array(rest_vals));
92            break;
93        } else {
94            let val = arg_iter.next().unwrap_or(JsValue::Undefined);
95            scope.borrow_mut().declare(param, val);
96        }
97    }
98}