1use crate::{evaluate_add_op, LazyBinding, Result, Val};2use indexmap::IndexMap;3use jrsonnet_parser::{ExprLocation, Visibility};4use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};56#[derive(Debug)]7pub struct ObjMember {8 pub add: bool,9 pub visibility: Visibility,10 pub invoke: LazyBinding,11 pub location: Option<ExprLocation>,12}131415type CacheKey = (Rc<str>, usize);16#[derive(Debug)]17pub struct ObjValueInternals {18 super_obj: Option<ObjValue>,19 this_entries: Rc<HashMap<Rc<str>, ObjMember>>,20 value_cache: RefCell<HashMap<CacheKey, Option<Val>>>,21}22#[derive(Clone)]23pub struct ObjValue(pub(crate) Rc<ObjValueInternals>);24impl Debug for ObjValue {25 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {26 if let Some(super_obj) = self.0.super_obj.as_ref() {27 if f.alternate() {28 write!(f, "{:#?}", super_obj)?;29 } else {30 write!(f, "{:?}", super_obj)?;31 }32 write!(f, " + ")?;33 }34 let mut debug = f.debug_struct("ObjValue");35 for (name, member) in self.0.this_entries.iter() {36 debug.field(name, member);37 }38 debug.finish_non_exhaustive()39 }40}4142impl ObjValue {43 pub fn new(44 super_obj: Option<ObjValue>,45 this_entries: Rc<HashMap<Rc<str>, ObjMember>>,46 ) -> ObjValue {47 ObjValue(Rc::new(ObjValueInternals {48 super_obj,49 this_entries,50 value_cache: RefCell::new(HashMap::new()),51 }))52 }53 pub fn new_empty() -> ObjValue {54 Self::new(None, Rc::new(HashMap::new()))55 }56 pub fn with_super(&self, super_obj: ObjValue) -> ObjValue {57 match &self.0.super_obj {58 None => ObjValue::new(Some(super_obj), self.0.this_entries.clone()),59 Some(v) => ObjValue::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),60 }61 }62 pub fn enum_fields(&self, handler: &impl Fn(&Rc<str>, &Visibility)) {63 if let Some(s) = &self.0.super_obj {64 s.enum_fields(handler);65 }66 for (name, member) in self.0.this_entries.iter() {67 handler(&name, &member.visibility);68 }69 }70 pub fn fields_visibility(&self) -> IndexMap<Rc<str>, bool> {71 let out = Rc::new(RefCell::new(IndexMap::new()));72 self.enum_fields(&|name, visibility| {73 let mut out = out.borrow_mut();74 match visibility {75 Visibility::Normal => {76 if !out.contains_key(name) {77 out.insert(name.to_owned(), true);78 }79 }80 Visibility::Hidden => {81 out.insert(name.to_owned(), false);82 }83 Visibility::Unhide => {84 out.insert(name.to_owned(), true);85 }86 };87 });88 Rc::try_unwrap(out).unwrap().into_inner()89 }90 pub fn visible_fields(&self) -> Vec<Rc<str>> {91 let mut visible_fields: Vec<_> = self92 .fields_visibility()93 .into_iter()94 .filter(|(_k, v)| *v)95 .map(|(k, _)| k)96 .collect();97 visible_fields.sort();98 visible_fields99 }100 pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {101 Ok(self.get_raw(key, self)?)102 }103 pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &ObjValue) -> Result<Option<Val>> {104 let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);105106 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {107 return Ok(v.clone());108 }109 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {110 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),111 (Some(k), Some(s)) => {112 let our = self.evaluate_this(k, real_this)?;113 if k.add {114 s.get_raw(key, real_this)?115 .map_or(Ok(Some(our.clone())), |v| {116 Ok(Some(evaluate_add_op(&v, &our)?))117 })118 } else {119 Ok(Some(our))120 }121 }122 (None, Some(s)) => s.get_raw(key, real_this),123 (None, None) => Ok(None),124 }?;125 self.0126 .value_cache127 .borrow_mut()128 .insert(cache_key, value.clone());129 Ok(value)130 }131 fn evaluate_this(&self, v: &ObjMember, real_this: &ObjValue) -> Result<Val> {132 Ok(v.invoke133 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?134 .evaluate()?)135 }136}137impl PartialEq for ObjValue {138 fn eq(&self, other: &Self) -> bool {139 Rc::ptr_eq(&self.0, &other.0)140 }141}