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

difftreelog

source

crates/jrsonnet-evaluator/src/obj.rs3.7 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#[derive(Debug)]15pub struct ObjValueInternals {16	super_obj: Option<ObjValue>,17	this_entries: Rc<HashMap<Rc<str>, ObjMember>>,18	value_cache: RefCell<HashMap<Rc<str>, Val>>,19}20#[derive(Clone)]21pub struct ObjValue(pub(crate) Rc<ObjValueInternals>);22impl Debug for ObjValue {23	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {24		if let Some(super_obj) = self.0.super_obj.as_ref() {25			if f.alternate() {26				write!(f, "{:#?}", super_obj)?;27			} else {28				write!(f, "{:?}", super_obj)?;29			}30			write!(f, " + ")?;31		}32		let mut debug = f.debug_struct("ObjValue");33		for (name, member) in self.0.this_entries.iter() {34			debug.field(name, member);35		}36		debug.finish_non_exhaustive()37	}38}3940impl ObjValue {41	pub fn new(42		super_obj: Option<ObjValue>,43		this_entries: Rc<HashMap<Rc<str>, ObjMember>>,44	) -> ObjValue {45		ObjValue(Rc::new(ObjValueInternals {46			super_obj,47			this_entries,48			value_cache: RefCell::new(HashMap::new()),49		}))50	}51	pub fn new_empty() -> ObjValue {52		Self::new(None, Rc::new(HashMap::new()))53	}54	pub fn with_super(&self, super_obj: ObjValue) -> ObjValue {55		match &self.0.super_obj {56			None => ObjValue::new(Some(super_obj), self.0.this_entries.clone()),57			Some(v) => ObjValue::new(Some(v.with_super(super_obj)), self.0.this_entries.clone()),58		}59	}60	pub fn enum_fields(&self, handler: &impl Fn(&Rc<str>, &Visibility)) {61		if let Some(s) = &self.0.super_obj {62			s.enum_fields(handler);63		}64		for (name, member) in self.0.this_entries.iter() {65			handler(&name, &member.visibility);66		}67	}68	pub fn fields_visibility(&self) -> IndexMap<Rc<str>, bool> {69		let out = Rc::new(RefCell::new(IndexMap::new()));70		self.enum_fields(&|name, visibility| {71			let mut out = out.borrow_mut();72			match visibility {73				Visibility::Normal => {74					if !out.contains_key(name) {75						out.insert(name.to_owned(), true);76					}77				}78				Visibility::Hidden => {79					out.insert(name.to_owned(), false);80				}81				Visibility::Unhide => {82					out.insert(name.to_owned(), true);83				}84			};85		});86		Rc::try_unwrap(out).unwrap().into_inner()87	}88	pub fn visible_fields(&self) -> Vec<Rc<str>> {89		let mut visible_fields: Vec<_> = self90			.fields_visibility()91			.into_iter()92			.filter(|(_k, v)| *v)93			.map(|(k, _)| k)94			.collect();95		visible_fields.sort();96		visible_fields97	}98	pub fn get(&self, key: Rc<str>) -> Result<Option<Val>> {99		if let Some(v) = self.0.value_cache.borrow().get(&key) {100			return Ok(Some(v.clone()));101		}102		if let Some(v) = self.get_raw(&key, self)? {103			let v = v.unwrap_if_lazy()?;104			self.0.value_cache.borrow_mut().insert(key, v.clone());105			Ok(Some(v))106		} else {107			Ok(None)108		}109	}110	pub(crate) fn get_raw(&self, key: &str, real_this: &ObjValue) -> Result<Option<Val>> {111		match (self.0.this_entries.get(key), &self.0.super_obj) {112			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),113			(Some(k), Some(s)) => {114				let our = self.evaluate_this(k, real_this)?;115				if k.add {116					s.get_raw(key, real_this)?117						.map_or(Ok(Some(our.clone())), |v| {118							Ok(Some(evaluate_add_op(&v, &our)?))119						})120				} else {121					Ok(Some(our))122				}123			}124			(None, Some(s)) => s.get_raw(key, real_this),125			(None, None) => Ok(None),126		}127	}128	fn evaluate_this(&self, v: &ObjMember, real_this: &ObjValue) -> Result<Val> {129		Ok(v.invoke130			.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?131			.evaluate()?)132	}133}134impl PartialEq for ObjValue {135	fn eq(&self, other: &Self) -> bool {136		Rc::ptr_eq(&self.0, &other.0)137	}138}