1use crate::{2 future_wrapper, lazy_binding, lazy_val, rc_fn_helper, LazyBinding, LazyVal, ObjValue, Val,3};4use closure::closure;5use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};67rc_fn_helper!(8 ContextCreator,9 context_creator,10 dyn Fn(Option<ObjValue>, Option<ObjValue>) -> Context11);1213future_wrapper!(Context, FutureContext);1415#[derive(Debug)]16struct ContextInternals {17 dollar: Option<ObjValue>,18 this: Option<ObjValue>,19 super_obj: Option<ObjValue>,20 bindings: Rc<HashMap<String, LazyVal>>,21}22pub struct Context(Rc<ContextInternals>);23impl Debug for Context {24 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {25 f.debug_struct("Context")26 .field("this", &self.0.this.clone().map(|e| Rc::as_ptr(&e.0)))27 .finish()28 }29}30impl Context {31 pub fn new_future() -> FutureContext {32 FutureContext(Rc::new(RefCell::new(None)))33 }3435 pub fn dollar(&self) -> &Option<ObjValue> {36 &self.0.dollar37 }3839 pub fn this(&self) -> &Option<ObjValue> {40 &self.0.this41 }4243 pub fn super_obj(&self) -> &Option<ObjValue> {44 &self.0.super_obj45 }4647 pub fn new() -> Context {48 Context(Rc::new(ContextInternals {49 dollar: None,50 this: None,51 super_obj: None,52 bindings: Rc::new(HashMap::new()),53 }))54 }5556 pub fn binding(&self, name: &str) -> LazyVal {57 self.0.bindings.get(name).cloned().unwrap_or_else(|| {58 panic!("can't find {} in {:?}", name, self);59 })60 }61 pub fn into_future(self, ctx: FutureContext) -> Context {62 {63 ctx.0.borrow_mut().replace(self);64 }65 ctx.unwrap()66 }6768 pub fn with_var(&self, name: String, value: Val) -> Context {69 let mut new_bindings: HashMap<_, LazyBinding> = HashMap::new();70 new_bindings.insert(71 name,72 lazy_binding!(73 closure!(clone value, |_t, _s|lazy_val!(closure!(clone value, ||value.clone())))74 ),75 );76 self.extend(new_bindings, None, None, None)77 }7879 pub fn extend(80 &self,81 new_bindings: HashMap<String, LazyBinding>,82 new_dollar: Option<ObjValue>,83 new_this: Option<ObjValue>,84 new_super_obj: Option<ObjValue>,85 ) -> Context {86 let dollar = new_dollar.or_else(|| self.0.dollar.clone());87 let this = new_this.or_else(|| self.0.this.clone());88 let super_obj = new_super_obj.or_else(|| self.0.super_obj.clone());89 let bindings = if new_bindings.is_empty() {90 self.0.bindings.clone()91 } else {92 let mut new = HashMap::new(); 93 for (k, v) in self.0.bindings.iter() {94 new.insert(k.clone(), v.clone());95 }96 for (k, v) in new_bindings.into_iter() {97 new.insert(k, v.0(this.clone(), super_obj.clone()));98 }99 Rc::new(new)100 };101 Context(Rc::new(ContextInternals {102 dollar,103 this,104 super_obj,105 bindings,106 }))107 }108}109110impl Default for Context {111 fn default() -> Self {112 Self::new()113 }114}115116impl PartialEq for Context {117 fn eq(&self, other: &Self) -> bool {118 Rc::ptr_eq(&self.0, &other.0)119 }120}121122impl Clone for Context {123 fn clone(&self) -> Self {124 Context(self.0.clone())125 }126}