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

difftreelog

source

crates/jrsonnet-evaluator/src/obj/oop.rs6.9 KiBsourcehistory
1use std::{2	cell::{Cell, RefCell},3	fmt, mem,4	ops::ControlFlow,5};67use jrsonnet_gcmodule::{Cc, Trace};8use jrsonnet_ir::IStr;9use rustc_hash::{FxHashMap, FxHashSet};1011use super::{12	CcObjectAssertion, CcObjectCore, EnumFields, EnumFieldsHandler, FieldVisibility, GetFor,13	HasFieldIncludeHidden, ObjMember, ObjMemberBuilder, ObjValue, ObjValueInner, ObjectAssertion,14	ObjectCore, OmitFieldsCore, SupThis,15	ordering::{FieldIndex, SuperDepth},16};17use crate::{18	CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val, bail,19	error::ErrorKind::*,20	function::{CallLocation, FuncVal},21	gc::WithCapacityExt as _,22	in_frame,23};2425#[allow(clippy::module_name_repetitions)]26#[derive(Trace, Default)]27#[trace(tracking(force))]28pub struct OopObject {29	assertion: Option<CcObjectAssertion>,30	this_entries: FxHashMap<IStr, (ObjMember, FieldIndex)>,31}32impl fmt::Debug for OopObject {33	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {34		f.debug_struct("OopObject")35			.field("this_entries", &self.this_entries)36			.finish_non_exhaustive()37	}38}39impl OopObject {40	fn is_empty(&self) -> bool {41		self.assertion.is_none() && self.this_entries.is_empty()42	}43}44impl OopObject {45	pub fn new(46		this_entries: FxHashMap<IStr, (ObjMember, FieldIndex)>,47		assertion: Option<CcObjectAssertion>,48	) -> Self {49		Self {50			assertion,51			this_entries,52		}53	}54}5556impl ObjectCore for OopObject {57	fn enum_fields_core(58		&self,59		super_depth: &mut SuperDepth,60		handler: &mut EnumFieldsHandler<'_>,61	) -> bool {62		for (name, (member, idx)) in &self.this_entries {63			if matches!(64				handler(65					*super_depth,66					*idx,67					name.clone(),68					EnumFields::Normal(member.flags.visibility()),69				),70				ControlFlow::Break(())71			) {72				return false;73			}74		}75		true76	}7778	fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {79		if self.this_entries.contains_key(&name) {80			HasFieldIncludeHidden::Exists81		} else {82			HasFieldIncludeHidden::NotFound83		}84	}8586	fn get_for_core(&self, key: IStr, sup_this: SupThis, omit_only: bool) -> Result<GetFor> {87		if omit_only {88			return Ok(GetFor::NotFound);89		}90		match self.this_entries.get(&key) {91			Some((k, _)) => {92				let v = k.invoke.evaluate(sup_this)?;93				Ok(if k.flags.add() {94					GetFor::SuperPlus(v)95				} else {96					GetFor::Final(v)97				})98			}99			None => Ok(GetFor::NotFound),100		}101	}102	fn field_visibility_core(&self, name: IStr) -> FieldVisibility {103		self.this_entries104			.get(&name)105			.map_or(FieldVisibility::NotFound, |(f, _)| {106				FieldVisibility::Found(f.flags.visibility())107			})108	}109110	fn run_assertions_core(&self, sup_this: SupThis) -> Result<()> {111		if let Some(assertion) = &self.assertion {112			assertion.0.run(sup_this)?;113		}114		Ok(())115	}116}117118#[allow(clippy::module_name_repetitions)]119pub struct ObjValueBuilder {120	sup: Vec<CcObjectCore>,121	has_assertions: bool,122123	new: OopObject,124	next_field_index: FieldIndex,125}126impl ObjValueBuilder {127	pub fn new() -> Self {128		Self::with_capacity(0)129	}130	pub fn with_capacity(capacity: usize) -> Self {131		Self {132			sup: Vec::new(),133			has_assertions: false,134			new: OopObject::new(FxHashMap::with_capacity(capacity), None),135			next_field_index: FieldIndex::default(),136		}137	}138	pub fn reserve_fields(&mut self, capacity: usize) {139		self.new.this_entries.reserve(capacity);140	}141	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {142		self.has_assertions |= super_obj.0.has_assertions;143		self.sup.clone_from(&super_obj.0.cores);144		self145	}146147	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {148		assert!(149			self.new.assertion.is_none(),150			"one OopObject can only have one assertion"151		);152		self.has_assertions = true;153		self.new.assertion = Some(CcObjectAssertion::new(assertion));154		self155	}156	pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {157		let field_index = self.next_field_index;158		self.next_field_index = self.next_field_index.next();159		ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)160	}161	/// Preset for common method definiton pattern:162	/// Create a hidden field with the function value.163	///164	/// `.field(name).hide().value(Val::function(value))`165	pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {166		self.field(name).hide().value(Val::Func(value.into()));167		self168	}169	pub fn try_method(170		&mut self,171		name: impl Into<IStr>,172		value: impl Into<FuncVal>,173	) -> Result<&mut Self> {174		self.field(name).hide().try_value(Val::Func(value.into()))?;175		Ok(self)176	}177178	pub fn extend_with_core(&mut self, core: impl ObjectCore) {179		self.commit();180		self.sup.push(CcObjectCore::new(core));181	}182183	fn commit(&mut self) {184		if !self.new.is_empty() {185			self.sup.push(CcObjectCore::new(mem::take(&mut self.new)));186		}187		self.next_field_index = FieldIndex::default();188	}189190	pub fn with_fields_omitted(&mut self, omit: FxHashSet<IStr>) {191		self.commit();192		self.sup.push(CcObjectCore::new(OmitFieldsCore {193			omit,194			prev_layers: self.sup.len(),195		}));196	}197198	pub fn build(mut self) -> ObjValue {199		self.commit();200		if self.sup.is_empty() {201			return ObjValue::empty();202		}203		let has_assertions = self.has_assertions;204		ObjValue(Cc::new(ObjValueInner {205			cores: self.sup,206			assertions_ran: Cell::new(!has_assertions),207			has_assertions,208			value_cache: RefCell::default(),209		}))210	}211}212impl Default for ObjValueBuilder {213	fn default() -> Self {214		Self::with_capacity(0)215	}216}217218pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);219impl ObjMemberBuilder<ValueBuilder<'_>> {220	/// Inserts value, replacing if it is already defined221	pub fn value(self, value: impl Into<Val>) {222		let (receiver, name, idx, member) =223			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));224		let entry = receiver.0.new.this_entries.entry(name);225		entry.insert_entry((member, idx));226	}227	/// Inserts thunk, replacing if it is already defined228	pub fn thunk(self, value: impl Into<Thunk<Val>>) {229		let (receiver, name, idx, member) = self.build_member(MaybeUnbound::Bound(value.into()));230		let entry = receiver.0.new.this_entries.entry(name);231		entry.insert_entry((member, idx));232	}233234	/// Tries to insert value, returns an error if it was already defined235	pub fn try_value(self, value: impl Into<Val>) -> Result<()> {236		self.try_thunk(Thunk::evaluated(value.into()))237	}238	pub fn try_thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {239		self.binding(MaybeUnbound::Bound(value.into()))240	}241	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {242		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)))243	}244	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {245		let (receiver, name, idx, member) = self.build_member(binding);246		let location = member.location.clone();247		let old = receiver248			.0249			.new250			.this_entries251			.insert(name.clone(), (member, idx));252		if old.is_some() {253			in_frame(254				CallLocation(location.as_ref()),255				|| format!("field <{}> initializtion", name.clone()),256				|| bail!(DuplicateFieldName(name.clone())),257			)?;258		}259		Ok(())260	}261}