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

difftreelog

source

crates/jrsonnet-evaluator/src/obj.rs7.1 KiBsourcehistory
1use crate::{evaluate_add_op, evaluate_assert, Context, LazyBinding, Result, Val};2use gc::{Finalize, Gc, GcCell, Trace};3use jrsonnet_interner::IStr;4use jrsonnet_parser::{AssertStmt, ExprLocation, Visibility};5use rustc_hash::{FxHashMap, FxHashSet};6use std::hash::{Hash, Hasher};7use std::{fmt::Debug, hash::BuildHasherDefault};89#[derive(Debug, Trace, Finalize)]10pub struct ObjMember {11	pub add: bool,12	pub visibility: Visibility,13	pub invoke: LazyBinding,14	pub location: Option<ExprLocation>,15}1617pub trait ObjectAssertion: Trace {18	fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;19}2021// Field => This22type CacheKey = (IStr, ObjValue);23#[derive(Trace, Finalize)]24pub struct ObjValueInternals {25	super_obj: Option<ObjValue>,26	assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,27	assertions_ran: GcCell<FxHashSet<ObjValue>>,28	this_obj: Option<ObjValue>,29	this_entries: Gc<FxHashMap<IStr, ObjMember>>,30	value_cache: GcCell<FxHashMap<CacheKey, Option<Val>>>,31}3233#[derive(Clone, Trace, Finalize)]34pub struct ObjValue(pub(crate) Gc<ObjValueInternals>);35impl Debug for ObjValue {36	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {37		if let Some(super_obj) = self.0.super_obj.as_ref() {38			if f.alternate() {39				write!(f, "{:#?}", super_obj)?;40			} else {41				write!(f, "{:?}", super_obj)?;42			}43			write!(f, " + ")?;44		}45		let mut debug = f.debug_struct("ObjValue");46		for (name, member) in self.0.this_entries.iter() {47			debug.field(name, member);48		}49		#[cfg(feature = "unstable")]50		{51			debug.finish_non_exhaustive()52		}53		#[cfg(not(feature = "unstable"))]54		{55			debug.finish()56		}57	}58}5960impl ObjValue {61	pub fn new(62		super_obj: Option<Self>,63		this_entries: Gc<FxHashMap<IStr, ObjMember>>,64		assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,65	) -> Self {66		Self(Gc::new(ObjValueInternals {67			super_obj,68			assertions,69			assertions_ran: GcCell::new(FxHashSet::default()),70			this_obj: None,71			this_entries,72			value_cache: GcCell::new(FxHashMap::default()),73		}))74	}75	pub fn new_empty() -> Self {76		Self::new(None, Gc::new(FxHashMap::default()), Gc::new(Vec::new()))77	}78	pub fn extend_from(&self, super_obj: Self) -> Self {79		match &self.0.super_obj {80			None => Self::new(81				Some(super_obj),82				self.0.this_entries.clone(),83				self.0.assertions.clone(),84			),85			Some(v) => Self::new(86				Some(v.extend_from(super_obj)),87				self.0.this_entries.clone(),88				self.0.assertions.clone(),89			),90		}91	}92	pub fn with_this(&self, this_obj: Self) -> Self {93		Self(Gc::new(ObjValueInternals {94			super_obj: self.0.super_obj.clone(),95			assertions: self.0.assertions.clone(),96			assertions_ran: GcCell::new(FxHashSet::default()),97			this_obj: Some(this_obj),98			this_entries: self.0.this_entries.clone(),99			value_cache: GcCell::new(FxHashMap::default()),100		}))101	}102103	/// Run callback for every field found in object104	pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &Visibility) -> bool) -> bool {105		if let Some(s) = &self.0.super_obj {106			if s.enum_fields(handler) {107				return true;108			}109		}110		for (name, member) in self.0.this_entries.iter() {111			if handler(name, &member.visibility) {112				return true;113			}114		}115		false116	}117118	pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {119		let mut out = FxHashMap::default();120		self.enum_fields(&mut |name, visibility| {121			match visibility {122				Visibility::Normal => {123					let entry = out.entry(name.to_owned());124					entry.or_insert(true);125				}126				Visibility::Hidden => {127					out.insert(name.to_owned(), false);128				}129				Visibility::Unhide => {130					out.insert(name.to_owned(), true);131				}132			};133			false134		});135		out136	}137	pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {138		let mut fields: Vec<_> = self139			.fields_visibility()140			.into_iter()141			.filter(|(_k, v)| include_hidden || *v)142			.map(|(k, _)| k)143			.collect();144		fields.sort_unstable();145		fields146	}147	pub fn fields(&self) -> Vec<IStr> {148		self.fields_ex(false)149	}150151	pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {152		if let Some(m) = self.0.this_entries.get(&name) {153			Some(match &m.visibility {154				Visibility::Normal => self155					.0156					.super_obj157					.as_ref()158					.and_then(|super_obj| super_obj.field_visibility(name))159					.unwrap_or(Visibility::Normal),160				v => *v,161			})162		} else if let Some(super_obj) = &self.0.super_obj {163			super_obj.field_visibility(name)164		} else {165			None166		}167	}168169	fn has_field_include_hidden(&self, name: IStr) -> bool {170		if self.0.this_entries.contains_key(&name) {171			true172		} else if let Some(super_obj) = &self.0.super_obj {173			super_obj.has_field_include_hidden(name)174		} else {175			false176		}177	}178179	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {180		if include_hidden {181			self.has_field_include_hidden(name)182		} else {183			self.has_field(name)184		}185	}186	pub fn has_field(&self, name: IStr) -> bool {187		self.field_visibility(name)188			.map(|v| v.is_visible())189			.unwrap_or(false)190	}191192	pub fn get(&self, key: IStr) -> Result<Option<Val>> {193		self.run_assertions()?;194		self.get_raw(key, self.0.this_obj.as_ref())195	}196197	pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {198		let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());199		new.insert(key, value);200		Self::new(Some(self), Gc::new(new), Gc::new(Vec::new()))201	}202203	fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {204		let real_this = real_this.unwrap_or(self);205		let cache_key = (key.clone(), real_this.clone());206207		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {208			return Ok(v.clone());209		}210		let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {211			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),212			(Some(k), Some(s)) => {213				let our = self.evaluate_this(k, real_this)?;214				if k.add {215					s.get_raw(key, Some(real_this))?216						.map_or(Ok(Some(our.clone())), |v| {217							Ok(Some(evaluate_add_op(&v, &our)?))218						})219				} else {220					Ok(Some(our))221				}222			}223			(None, Some(s)) => s.get_raw(key, Some(real_this)),224			(None, None) => Ok(None),225		}?;226		self.0227			.value_cache228			.borrow_mut()229			.insert(cache_key, value.clone());230		Ok(value)231	}232	fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {233		v.invoke234			.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?235			.evaluate()236	}237238	fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {239		if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {240			for assertion in self.0.assertions.iter() {241				if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {242					self.0.assertions_ran.borrow_mut().remove(real_this);243					return Err(e);244				}245			}246			if let Some(super_obj) = &self.0.super_obj {247				super_obj.run_assertions_raw(real_this)?;248			}249		}250		Ok(())251	}252	pub fn run_assertions(&self) -> Result<()> {253		self.run_assertions_raw(self)254	}255256	pub fn ptr_eq(a: &Self, b: &Self) -> bool {257		Gc::ptr_eq(&a.0, &b.0)258	}259}260261impl PartialEq for ObjValue {262	fn eq(&self, other: &Self) -> bool {263		Gc::ptr_eq(&self.0, &other.0)264	}265}266267impl Eq for ObjValue {}268impl Hash for ObjValue {269	fn hash<H: Hasher>(&self, hasher: &mut H) {270		hasher.write_usize(&*self.0 as *const _ as usize)271	}272}