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

difftreelog

source

crates/jrsonnet-evaluator/src/obj.rs7.2 KiBsourcehistory
1use crate::{evaluate_add_op, evaluate_assert, Context, LazyBinding, Result, Val};2use jrsonnet_interner::IStr;3use jrsonnet_parser::{AssertStmt, ExprLocation, Visibility};4use rustc_hash::{FxHashMap, FxHashSet};5use std::hash::{Hash, Hasher};6use std::{cell::RefCell, fmt::Debug, hash::BuildHasherDefault, rc::Rc};78#[derive(Debug)]9pub struct ObjMember {10	pub add: bool,11	pub visibility: Visibility,12	pub invoke: LazyBinding,13	pub location: Option<ExprLocation>,14}1516// Field => This17type CacheKey = (IStr, ObjValue);18#[derive(Debug)]19pub struct ObjValueInternals {20	context: Context,21	super_obj: Option<ObjValue>,22	assertions: Rc<Vec<AssertStmt>>,23	assertions_ran: RefCell<FxHashSet<ObjValue>>,24	this_obj: Option<ObjValue>,25	this_entries: Rc<FxHashMap<IStr, ObjMember>>,26	value_cache: RefCell<FxHashMap<CacheKey, Option<Val>>>,27}2829#[derive(Clone)]30pub struct ObjValue(pub(crate) Rc<ObjValueInternals>);31impl Debug for ObjValue {32	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {33		if let Some(super_obj) = self.0.super_obj.as_ref() {34			if f.alternate() {35				write!(f, "{:#?}", super_obj)?;36			} else {37				write!(f, "{:?}", super_obj)?;38			}39			write!(f, " + ")?;40		}41		let mut debug = f.debug_struct("ObjValue");42		for (name, member) in self.0.this_entries.iter() {43			debug.field(name, member);44		}45		#[cfg(feature = "unstable")]46		{47			debug.finish_non_exhaustive()48		}49		#[cfg(not(feature = "unstable"))]50		{51			debug.finish()52		}53	}54}5556impl ObjValue {57	pub fn new(58		context: Context,59		super_obj: Option<Self>,60		this_entries: Rc<FxHashMap<IStr, ObjMember>>,61		assertions: Rc<Vec<AssertStmt>>,62	) -> Self {63		Self(Rc::new(ObjValueInternals {64			context,65			super_obj,66			assertions,67			assertions_ran: RefCell::new(FxHashSet::default()),68			this_obj: None,69			this_entries,70			value_cache: RefCell::new(FxHashMap::default()),71		}))72	}73	pub fn new_empty() -> Self {74		Self::new(75			Context::new(),76			None,77			Rc::new(FxHashMap::default()),78			Rc::new(Vec::new()),79		)80	}81	pub fn extend_from(&self, super_obj: Self) -> Self {82		match &self.0.super_obj {83			None => Self::new(84				self.0.context.clone(),85				Some(super_obj),86				self.0.this_entries.clone(),87				self.0.assertions.clone(),88			),89			Some(v) => Self::new(90				self.0.context.clone(),91				Some(v.extend_from(super_obj)),92				self.0.this_entries.clone(),93				self.0.assertions.clone(),94			),95		}96	}97	pub fn with_this(&self, this_obj: Self) -> Self {98		Self(Rc::new(ObjValueInternals {99			context: self.0.context.clone(),100			super_obj: self.0.super_obj.clone(),101			assertions: self.0.assertions.clone(),102			assertions_ran: RefCell::new(FxHashSet::default()),103			this_obj: Some(this_obj),104			this_entries: self.0.this_entries.clone(),105			value_cache: RefCell::new(FxHashMap::default()),106		}))107	}108109	/// Run callback for every field found in object110	pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &Visibility) -> bool) -> bool {111		if let Some(s) = &self.0.super_obj {112			if s.enum_fields(handler) {113				return true;114			}115		}116		for (name, member) in self.0.this_entries.iter() {117			if handler(name, &member.visibility) {118				return true;119			}120		}121		false122	}123124	pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {125		let mut out = FxHashMap::default();126		self.enum_fields(&mut |name, visibility| {127			match visibility {128				Visibility::Normal => {129					let entry = out.entry(name.to_owned());130					entry.or_insert(true);131				}132				Visibility::Hidden => {133					out.insert(name.to_owned(), false);134				}135				Visibility::Unhide => {136					out.insert(name.to_owned(), true);137				}138			};139			false140		});141		out142	}143	pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {144		let mut fields: Vec<_> = self145			.fields_visibility()146			.into_iter()147			.filter(|(_k, v)| include_hidden || *v)148			.map(|(k, _)| k)149			.collect();150		fields.sort_unstable();151		fields152	}153	pub fn fields(&self) -> Vec<IStr> {154		self.fields_ex(false)155	}156157	pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {158		if let Some(m) = self.0.this_entries.get(&name) {159			Some(match &m.visibility {160				Visibility::Normal => self161					.0162					.super_obj163					.as_ref()164					.and_then(|super_obj| super_obj.field_visibility(name))165					.unwrap_or(Visibility::Normal),166				v => *v,167			})168		} else if let Some(super_obj) = &self.0.super_obj {169			super_obj.field_visibility(name)170		} else {171			None172		}173	}174175	fn has_field_include_hidden(&self, name: IStr) -> bool {176		if self.0.this_entries.contains_key(&name) {177			true178		} else if let Some(super_obj) = &self.0.super_obj {179			super_obj.has_field_include_hidden(name)180		} else {181			false182		}183	}184185	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {186		if include_hidden {187			self.has_field_include_hidden(name)188		} else {189			self.has_field(name)190		}191	}192	pub fn has_field(&self, name: IStr) -> bool {193		self.field_visibility(name)194			.map(|v| v.is_visible())195			.unwrap_or(false)196	}197198	pub fn get(&self, key: IStr) -> Result<Option<Val>> {199		self.run_assertions()?;200		self.get_raw(key, self.0.this_obj.as_ref())201	}202203	pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {204		let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());205		new.insert(key, value);206		Self::new(207			Context::new(),208			Some(self),209			Rc::new(new),210			Rc::new(Vec::new()),211		)212	}213214	fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {215		let real_this = real_this.unwrap_or(self);216		let cache_key = (key.clone(), real_this.clone());217218		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {219			return Ok(v.clone());220		}221		let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {222			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),223			(Some(k), Some(s)) => {224				let our = self.evaluate_this(k, real_this)?;225				if k.add {226					s.get_raw(key, Some(real_this))?227						.map_or(Ok(Some(our.clone())), |v| {228							Ok(Some(evaluate_add_op(&v, &our)?))229						})230				} else {231					Ok(Some(our))232				}233			}234			(None, Some(s)) => s.get_raw(key, Some(real_this)),235			(None, None) => Ok(None),236		}?;237		self.0238			.value_cache239			.borrow_mut()240			.insert(cache_key, value.clone());241		Ok(value)242	}243	fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {244		v.invoke245			.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?246			.evaluate()247	}248249	fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {250		if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {251			for assertion in self.0.assertions.iter() {252				if let Err(e) = evaluate_assert(253					self.0254						.context255						.clone()256						.with_this_super(real_this.clone(), self.0.super_obj.clone()),257					assertion,258				) {259					self.0.assertions_ran.borrow_mut().remove(real_this);260					return Err(e);261				}262			}263			if let Some(super_obj) = &self.0.super_obj {264				super_obj.run_assertions_raw(real_this)?;265			}266		}267		Ok(())268	}269	pub fn run_assertions(&self) -> Result<()> {270		self.run_assertions_raw(self)271	}272273	pub fn ptr_eq(a: &Self, b: &Self) -> bool {274		Rc::ptr_eq(&a.0, &b.0)275	}276}277278impl PartialEq for ObjValue {279	fn eq(&self, other: &Self) -> bool {280		Rc::ptr_eq(&self.0, &other.0)281	}282}283284impl Eq for ObjValue {}285impl Hash for ObjValue {286	fn hash<H: Hasher>(&self, state: &mut H) {287		state.write_usize(Rc::as_ptr(&self.0) as usize)288	}289}