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

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, None)?)106	}107	pub(crate) fn get_raw(&self, key: Rc<str>, real_this: Option<&Self>) -> Result<Option<Val>> {108		let real_this = real_this.unwrap_or(self);109		let cache_key = (key.clone(), Rc::as_ptr(&real_this.0) as usize);110111		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {112			return Ok(v.clone());113		}114		let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {115			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),116			(Some(k), Some(s)) => {117				let our = self.evaluate_this(k, real_this)?;118				if k.add {119					s.get_raw(key, Some(real_this))?120						.map_or(Ok(Some(our.clone())), |v| {121							Ok(Some(evaluate_add_op(&v, &our)?))122						})123				} else {124					Ok(Some(our))125				}126			}127			(None, Some(s)) => s.get_raw(key, Some(real_this)),128			(None, None) => Ok(None),129		}?;130		self.0131			.value_cache132			.borrow_mut()133			.insert(cache_key, value.clone());134		Ok(value)135	}136	fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {137		Ok(v.invoke138			.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?139			.evaluate()?)140	}141}142impl PartialEq for ObjValue {143	fn eq(&self, other: &Self) -> bool {144		Rc::ptr_eq(&self.0, &other.0)145	}146}