git.delta.rocks / jrsonnet / refs/commits / bc97bc99f5fd

difftreelog

source

crates/jrsonnet-evaluator/src/obj.rs3.9 KiBsourcehistory
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}1314// Field => This15type 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(super_obj: Option<Self>, this_entries: Rc<HashMap<Rc<str>, ObjMember>>) -> Self {51		Self(Rc::new(ObjValueInternals {52			super_obj,53			this_entries,54			value_cache: RefCell::new(HashMap::new()),55		}))56	}57	pub fn new_empty() -> Self {58		Self::new(None, Rc::new(HashMap::new()))59	}60	pub fn with_super(&self, super_obj: Self) -> Self {61		match &self.0.super_obj {62			None => Self::new(Some(super_obj), self.0.this_entries.clone()),63			Some(v) => Self::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),64		}65	}66	pub fn enum_fields(&self, handler: &impl Fn(&Rc<str>, &Visibility)) {67		if let Some(s) = &self.0.super_obj {68			s.enum_fields(handler);69		}70		for (name, member) in self.0.this_entries.iter() {71			handler(name, &member.visibility);72		}73	}74	pub fn fields_visibility(&self) -> IndexMap<Rc<str>, bool> {75		let out = Rc::new(RefCell::new(IndexMap::new()));76		self.enum_fields(&|name, visibility| {77			let mut out = out.borrow_mut();78			match visibility {79				Visibility::Normal => {80					if !out.contains_key(name) {81						out.insert(name.to_owned(), true);82					}83				}84				Visibility::Hidden => {85					out.insert(name.to_owned(), false);86				}87				Visibility::Unhide => {88					out.insert(name.to_owned(), true);89				}90			};91		});92		Rc::try_unwrap(out).unwrap().into_inner()93	}94	pub fn visible_fields(&self) -> Vec<Rc<str>> {95		let mut visible_fields: Vec<_> = self96			.fields_visibility()97			.into_iter()98			.filter(|(_k, v)| *v)99			.map(|(k, _)| k)100			.collect();101		visible_fields.sort();102		visible_fields103	}104	pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {105		Ok(self.get_raw(key, self)?)106	}107	pub(crate) fn get_raw(&self, key: Rc<str>, real_this: &Self) -> Result<Option<Val>> {108		let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);109110		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {111			return Ok(v.clone());112		}113		let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {114			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),115			(Some(k), Some(s)) => {116				let our = self.evaluate_this(k, real_this)?;117				if k.add {118					s.get_raw(key, real_this)?119						.map_or(Ok(Some(our.clone())), |v| {120							Ok(Some(evaluate_add_op(&v, &our)?))121						})122				} else {123					Ok(Some(our))124				}125			}126			(None, Some(s)) => s.get_raw(key, real_this),127			(None, None) => Ok(None),128		}?;129		self.0130			.value_cache131			.borrow_mut()132			.insert(cache_key, value.clone());133		Ok(value)134	}135	fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {136		Ok(v.invoke137			.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?138			.evaluate()?)139	}140}141impl PartialEq for ObjValue {142	fn eq(&self, other: &Self) -> bool {143		Rc::ptr_eq(&self.0, &other.0)144	}145}