git.delta.rocks / jrsonnet / refs/commits / 6f6b79fd0e0d

difftreelog

source

crates/jrsonnet-evaluator/src/obj/oop.rs6.8 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>,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>,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) in &self.this_entries {63			if matches!(64				handler(65					*super_depth,66					member.original_index,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![],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_cores(&mut self, capacity: usize) -> &mut Self {139		self.sup.reserve_exact(capacity);140		self141	}142	pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {143		self.has_assertions |= super_obj.0.has_assertions;144		self.sup.clone_from(&super_obj.0.cores);145		self146	}147148	pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {149		assert!(150			self.new.assertion.is_none(),151			"one OopObject can only have one assertion"152		);153		self.has_assertions = true;154		self.new.assertion = Some(CcObjectAssertion::new(assertion));155		self156	}157	pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {158		let field_index = self.next_field_index;159		self.next_field_index = self.next_field_index.next();160		ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)161	}162	/// Preset for common method definiton pattern:163	/// Create a hidden field with the function value.164	///165	/// `.field(name).hide().value(Val::function(value))`166	pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {167		self.field(name).hide().value(Val::Func(value.into()));168		self169	}170	pub fn try_method(171		&mut self,172		name: impl Into<IStr>,173		value: impl Into<FuncVal>,174	) -> Result<&mut Self> {175		self.field(name).hide().try_value(Val::Func(value.into()))?;176		Ok(self)177	}178179	pub fn extend_with_core(&mut self, core: impl ObjectCore) {180		self.commit();181		self.sup.push(CcObjectCore::new(core));182	}183184	fn commit(&mut self) {185		if !self.new.is_empty() {186			self.sup.push(CcObjectCore::new(mem::take(&mut self.new)));187		}188		self.next_field_index = FieldIndex::default();189	}190191	pub fn with_fields_omitted(&mut self, omit: FxHashSet<IStr>) {192		self.commit();193		self.sup.push(CcObjectCore::new(OmitFieldsCore {194			omit,195			prev_layers: self.sup.len(),196		}));197	}198199	pub fn build(mut self) -> ObjValue {200		self.commit();201		if self.sup.is_empty() {202			return ObjValue::empty();203		}204		let has_assertions = self.has_assertions;205		ObjValue(Cc::new(ObjValueInner {206			cores: self.sup,207			assertions_ran: Cell::new(!has_assertions),208			has_assertions,209			value_cache: RefCell::default(),210		}))211	}212}213impl Default for ObjValueBuilder {214	fn default() -> Self {215		Self::with_capacity(0)216	}217}218219pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);220impl ObjMemberBuilder<ValueBuilder<'_>> {221	/// Inserts value, replacing if it is already defined222	pub fn value(self, value: impl Into<Val>) {223		let (receiver, name, member) =224			self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));225		let entry = receiver.0.new.this_entries.entry(name);226		entry.insert_entry(member);227	}228	/// Inserts thunk, replacing if it is already defined229	pub fn thunk(self, value: impl Into<Thunk<Val>>) {230		let (receiver, name, member) = self.build_member(MaybeUnbound::Bound(value.into()));231		let entry = receiver.0.new.this_entries.entry(name);232		entry.insert_entry(member);233	}234235	/// Tries to insert value, returns an error if it was already defined236	pub fn try_value(self, value: impl Into<Val>) -> Result<()> {237		self.try_thunk(Thunk::evaluated(value.into()))238	}239	pub fn try_thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {240		self.binding(MaybeUnbound::Bound(value.into()))241	}242	pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {243		self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)))244	}245	pub fn binding(self, binding: MaybeUnbound) -> Result<()> {246		let (receiver, name, member) = self.build_member(binding);247		let location = member.location.clone();248		let old = receiver.0.new.this_entries.insert(name.clone(), member);249		if old.is_some() {250			in_frame(251				CallLocation(location.as_ref()),252				|| format!("field <{}> initializtion", name.clone()),253				|| bail!(DuplicateFieldName(name.clone())),254			)?;255		}256		Ok(())257	}258}