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 #[cfg(feature = "unstable")]39 {40 debug.finish_non_exhaustive()41 }42 #[cfg(not(feature = "unstable"))]43 {44 debug.finish()45 }46 }47}4849impl ObjValue {50 pub fn new(51 super_obj: Option<ObjValue>,52 this_entries: Rc<HashMap<Rc<str>, ObjMember>>,53 ) -> ObjValue {54 ObjValue(Rc::new(ObjValueInternals {55 super_obj,56 this_entries,57 value_cache: RefCell::new(HashMap::new()),58 }))59 }60 pub fn new_empty() -> ObjValue {61 Self::new(None, Rc::new(HashMap::new()))62 }63 pub fn with_super(&self, super_obj: ObjValue) -> ObjValue {64 match &self.0.super_obj {65 None => ObjValue::new(Some(super_obj), self.0.this_entries.clone()),66 Some(v) => ObjValue::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),67 }68 }69 pub fn enum_fields(&self, handler: &impl Fn(&Rc<str>, &Visibility)) {70 if let Some(s) = &self.0.super_obj {71 s.enum_fields(handler);72 }73 for (name, member) in self.0.this_entries.iter() {74 handler(&name, &member.visibility);75 }76 }77 pub fn fields_visibility(&self) -> IndexMap<Rc<str>, bool> {78 let out = Rc::new(RefCell::new(IndexMap::new()));79 self.enum_fields(&|name, visibility| {80 let mut out = out.borrow_mut();81 match visibility {82 Visibility::Normal => {83 if !out.contains_key(name) {84 out.insert(name.to_owned(), true);85 }86 }87 Visibility::Hidden => {88 out.insert(name.to_owned(), false);89 }90 Visibility::Unhide => {91 out.insert(name.to_owned(), true);92 }93 };94 });95 Rc::try_unwrap(out).unwrap().into_inner()96 }97 pub fn visible_fields(&self) -> Vec<Rc<str>> {98 let mut visible_fields: Vec<_> = self99 .fields_visibility()100 .into_iter()101 .filter(|(_k, v)| *v)102 .map(|(k, _)| k)103 .collect();104 visible_fields.sort();105 visible_fields106 }107 pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {108 Ok(self.get_raw(key, self)?)109 }110 pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &ObjValue) -> Result<Option<Val>> {111 let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);112113 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {114 return Ok(v.clone());115 }116 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {117 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),118 (Some(k), Some(s)) => {119 let our = self.evaluate_this(k, real_this)?;120 if k.add {121 s.get_raw(key, real_this)?122 .map_or(Ok(Some(our.clone())), |v| {123 Ok(Some(evaluate_add_op(&v, &our)?))124 })125 } else {126 Ok(Some(our))127 }128 }129 (None, Some(s)) => s.get_raw(key, real_this),130 (None, None) => Ok(None),131 }?;132 self.0133 .value_cache134 .borrow_mut()135 .insert(cache_key, value.clone());136 Ok(value)137 }138 fn evaluate_this(&self, v: &ObjMember, real_this: &ObjValue) -> Result<Val> {139 Ok(v.invoke140 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?141 .evaluate()?)142 }143}144impl PartialEq for ObjValue {145 fn eq(&self, other: &Self) -> bool {146 Rc::ptr_eq(&self.0, &other.0)147 }148}