1use std::{2 any::Any,3 cell::RefCell,4 fmt::Debug,5 hash::{Hash, Hasher},6 ptr::addr_of,7};89use jrsonnet_gcmodule::{Cc, Trace, Weak};10use jrsonnet_interner::IStr;11use jrsonnet_parser::{ExprLocation, Visibility};12use rustc_hash::FxHashMap;1314use crate::{15 arr::{PickObjectKeyValues, PickObjectValues},16 bail,17 error::{suggest_object_fields, Error, ErrorKind::*},18 function::{CallLocation, FuncVal},19 gc::{GcHashMap, GcHashSet, TraceBox},20 operator::evaluate_add_op,21 tb,22 val::{ArrValue, ThunkValue},23 MaybeUnbound, Result, State, Thunk, Unbound, Val,24};2526#[cfg(not(feature = "exp-preserve-order"))]27mod ordering {28 #![allow(29 30 clippy::unused_self,31 )]3233 use jrsonnet_gcmodule::Trace;3435 #[derive(Clone, Copy, Default, Debug, Trace)]36 pub struct FieldIndex(());37 impl FieldIndex {38 pub const fn next(self) -> Self {39 Self(())40 }41 }4243 #[derive(Clone, Copy, Default, Debug, Trace)]44 pub struct SuperDepth(());45 impl SuperDepth {46 pub const fn deeper(self) -> Self {47 Self(())48 }49 }5051 #[derive(Clone, Copy)]52 pub struct FieldSortKey(());53 impl FieldSortKey {54 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {55 Self(())56 }57 }58}5960#[cfg(feature = "exp-preserve-order")]61mod ordering {62 use std::cmp::Reverse;6364 use jrsonnet_gcmodule::Trace;6566 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]67 pub struct FieldIndex(u32);68 impl FieldIndex {69 pub fn next(self) -> Self {70 Self(self.0 + 1)71 }72 }7374 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]75 pub struct SuperDepth(u32);76 impl SuperDepth {77 pub fn deeper(self) -> Self {78 Self(self.0 + 1)79 }80 }8182 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]83 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);84 impl FieldSortKey {85 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {86 Self(Reverse(depth), index)87 }88 }89}9091use ordering::{FieldIndex, FieldSortKey, SuperDepth};92939495#[derive(Clone, Copy)]96pub struct ObjFieldFlags(u8);97impl ObjFieldFlags {98 fn new(add: bool, visibility: Visibility) -> Self {99 let mut v = 0;100 if add {101 v |= 1;102 }103 v |= match visibility {104 Visibility::Normal => 0b000,105 Visibility::Hidden => 0b010,106 Visibility::Unhide => 0b100,107 };108 Self(v)109 }110 pub fn add(&self) -> bool {111 self.0 & 1 != 0112 }113 pub fn visibility(&self) -> Visibility {114 match (self.0 & 0b110) >> 1 {115 0b00 => Visibility::Normal,116 0b01 => Visibility::Hidden,117 0b10 => Visibility::Unhide,118 _ => unreachable!(),119 }120 }121}122impl Debug for ObjFieldFlags {123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {124 f.debug_struct("ObjFieldFlags")125 .field("add", &self.add())126 .field("visibility", &self.visibility())127 .finish()128 }129}130131#[allow(clippy::module_name_repetitions)]132#[derive(Debug, Trace)]133pub struct ObjMember {134 #[trace(skip)]135 flags: ObjFieldFlags,136 original_index: FieldIndex,137 pub invoke: MaybeUnbound,138 pub location: Option<ExprLocation>,139}140141pub trait ObjectAssertion: Trace {142 fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;143}144145146147#[derive(Trace)]148enum CacheValue {149 Cached(Val),150 NotFound,151 Pending,152 Errored(Error),153}154155#[allow(clippy::module_name_repetitions)]156#[derive(Trace)]157#[trace(tracking(force))]158pub struct OopObject {159 sup: Option<ObjValue>,160 161 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,162 assertions_ran: RefCell<GcHashSet<ObjValue>>,163 this_entries: Cc<GcHashMap<IStr, ObjMember>>,164 value_cache: RefCell<GcHashMap<(IStr, Option<WeakObjValue>), CacheValue>>,165}166impl Debug for OopObject {167 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {168 f.debug_struct("OopObject")169 .field("sup", &self.sup)170 171 172 .field("this_entries", &self.this_entries)173 174 .finish_non_exhaustive()175 }176}177178type EnumFieldsHandler<'a> = dyn FnMut(SuperDepth, FieldIndex, IStr, Visibility) -> bool + 'a;179180pub trait ObjectLike: Trace + Any + Debug {181 fn extend_from(&self, sup: ObjValue) -> ObjValue;182 183 fn with_this(&self, me: ObjValue, this: ObjValue) -> ObjValue {184 ObjValue::new(ThisOverride { inner: me, this })185 }186 fn this(&self) -> Option<ObjValue> {187 None188 }189 fn len(&self) -> usize;190 fn is_empty(&self) -> bool;191 192 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool;193194 fn has_field_include_hidden(&self, name: IStr) -> bool;195 fn has_field(&self, name: IStr) -> bool;196197 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;198 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>>;199 fn field_visibility(&self, field: IStr) -> Option<Visibility>;200201 fn run_assertions_raw(&self, this: ObjValue) -> Result<()>;202}203204#[derive(Clone, Trace)]205pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<TraceBox<dyn ObjectLike>>);206207impl PartialEq for WeakObjValue {208 fn eq(&self, other: &Self) -> bool {209 Weak::ptr_eq(&self.0, &other.0)210 }211}212213impl Eq for WeakObjValue {}214impl Hash for WeakObjValue {215 fn hash<H: Hasher>(&self, hasher: &mut H) {216 217 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };218 hasher.write_usize(addr);219 }220}221222#[allow(clippy::module_name_repetitions)]223#[derive(Clone, Trace, Debug)]224pub struct ObjValue(pub(crate) Cc<TraceBox<dyn ObjectLike>>);225226#[derive(Debug, Trace)]227struct EmptyObject;228impl ObjectLike for EmptyObject {229 fn extend_from(&self, sup: ObjValue) -> ObjValue {230 231 sup232 }233234 fn this(&self) -> Option<ObjValue> {235 None236 }237238 fn len(&self) -> usize {239 0240 }241242 fn is_empty(&self) -> bool {243 true244 }245246 fn enum_fields(&self, _depth: SuperDepth, _handler: &mut EnumFieldsHandler<'_>) -> bool {247 false248 }249250 fn has_field_include_hidden(&self, _name: IStr) -> bool {251 false252 }253254 fn has_field(&self, _name: IStr) -> bool {255 false256 }257258 fn get_for(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {259 Ok(None)260 }261 fn get_for_uncached(&self, _key: IStr, _this: ObjValue) -> Result<Option<Val>> {262 Ok(None)263 }264265 fn run_assertions_raw(&self, _this: ObjValue) -> Result<()> {266 Ok(())267 }268269 fn field_visibility(&self, _field: IStr) -> Option<Visibility> {270 None271 }272}273274#[derive(Trace, Debug)]275struct ThisOverride {276 inner: ObjValue,277 this: ObjValue,278}279impl ObjectLike for ThisOverride {280 fn with_this(&self, _me: ObjValue, this: ObjValue) -> ObjValue {281 ObjValue::new(Self {282 inner: self.inner.clone(),283 this,284 })285 }286287 fn extend_from(&self, sup: ObjValue) -> ObjValue {288 self.inner.extend_from(sup).with_this(self.this.clone())289 }290291 fn this(&self) -> Option<ObjValue> {292 Some(self.this.clone())293 }294295 fn len(&self) -> usize {296 self.inner.len()297 }298299 fn is_empty(&self) -> bool {300 self.inner.is_empty()301 }302303 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {304 self.inner.enum_fields(depth, handler)305 }306307 fn has_field_include_hidden(&self, name: IStr) -> bool {308 self.inner.has_field_include_hidden(name)309 }310311 fn has_field(&self, name: IStr) -> bool {312 self.inner.has_field(name)313 }314315 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {316 self.inner.get_for(key, this)317 }318319 fn get_for_uncached(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {320 self.inner.get_raw(key, this)321 }322323 fn field_visibility(&self, field: IStr) -> Option<Visibility> {324 self.inner.field_visibility(field)325 }326327 fn run_assertions_raw(&self, this: ObjValue) -> Result<()> {328 self.inner.run_assertions_raw(this)329 }330}331332impl ObjValue {333 pub fn new(v: impl ObjectLike) -> Self {334 Self(Cc::new(tb!(v)))335 }336 pub fn new_empty() -> Self {337 Self::new(EmptyObject)338 }339 pub fn builder() -> ObjValueBuilder {340 ObjValueBuilder::new()341 }342 pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {343 ObjValueBuilder::with_capacity(capacity)344 }345 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {346 let mut out = ObjValueBuilder::with_capacity(1);347 out.with_super(self);348 let mut member = out.field(key);349 if value.flags.add() {350 member = member.add();351 }352 if let Some(loc) = value.location {353 member = member.with_location(loc);354 }355 let _ = member356 .with_visibility(value.flags.visibility())357 .binding(value.invoke);358 out.build()359 }360 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {361 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())362 }363364 #[must_use]365 pub fn extend_from(&self, sup: Self) -> Self {366 self.0.extend_from(sup)367 }368 #[must_use]369 pub fn with_this(&self, this: Self) -> Self {370 self.0.with_this(self.clone(), this)371 }372 pub fn len(&self) -> usize {373 self.0.len()374 }375 pub fn is_empty(&self) -> bool {376 self.0.is_empty()377 }378 pub fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {379 self.0.enum_fields(depth, handler)380 }381382 pub fn has_field_include_hidden(&self, name: IStr) -> bool {383 self.0.has_field_include_hidden(name)384 }385 pub fn has_field(&self, name: IStr) -> bool {386 self.0.has_field(name)387 }388 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {389 if include_hidden {390 self.has_field_include_hidden(name)391 } else {392 self.has_field(name)393 }394 }395396 pub fn get(&self, key: IStr) -> Result<Option<Val>> {397 self.run_assertions()?;398 self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))399 }400401 pub fn get_for(&self, key: IStr, this: Self) -> Result<Option<Val>> {402 self.0.get_for(key, this)403 }404405 pub fn get_or_bail(&self, key: IStr) -> Result<Val> {406 let Some(value) = self.get(key.clone())? else {407 let suggestions = suggest_object_fields(self, key.clone());408 bail!(NoSuchField(key, suggestions))409 };410 Ok(value)411 }412413 fn get_raw(&self, key: IStr, this: Self) -> Result<Option<Val>> {414 self.0.get_for_uncached(key, this)415 }416417 fn field_visibility(&self, field: IStr) -> Option<Visibility> {418 self.0.field_visibility(field)419 }420421 pub fn run_assertions(&self) -> Result<()> {422 423 self.run_assertions_raw(self.clone())424 }425 fn run_assertions_raw(&self, this: Self) -> Result<()> {426 self.0.run_assertions_raw(this)427 }428429 pub fn iter(430 &self,431 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,432 ) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {433 let fields = self.fields(434 #[cfg(feature = "exp-preserve-order")]435 preserve_order,436 );437 fields.into_iter().map(|field| {438 (439 field.clone(),440 self.get(field)441 .map(|opt| opt.expect("iterating over keys, field exists")),442 )443 })444 }445 pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {446 #[derive(Trace)]447 struct ThunkGet {448 obj: ObjValue,449 key: IStr,450 }451 impl ThunkValue for ThunkGet {452 type Output = Val;453454 fn get(self: Box<Self>) -> Result<Self::Output> {455 Ok(self.obj.get(self.key)?.expect("field exists"))456 }457 }458459 if !self.has_field_ex(key.clone(), true) {460 return None;461 }462 Some(Thunk::new(ThunkGet {463 obj: self.clone(),464 key,465 }))466 }467 pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {468 #[derive(Trace)]469 struct ThunkGet {470 obj: ObjValue,471 key: IStr,472 }473 impl ThunkValue for ThunkGet {474 type Output = Val;475476 fn get(self: Box<Self>) -> Result<Self::Output> {477 self.obj.get_or_bail(self.key)478 }479 }480481 Thunk::new(ThunkGet {482 obj: self.clone(),483 key,484 })485 }486 pub fn ptr_eq(a: &Self, b: &Self) -> bool {487 Cc::ptr_eq(&a.0, &b.0)488 }489 pub fn downgrade(self) -> WeakObjValue {490 WeakObjValue(self.0.downgrade())491 }492 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {493 let mut out = FxHashMap::default();494 self.enum_fields(495 SuperDepth::default(),496 &mut |depth, index, name, visibility| {497 let new_sort_key = FieldSortKey::new(depth, index);498 let entry = out.entry(name);499 let (visible, _) = entry.or_insert((true, new_sort_key));500 match visibility {501 Visibility::Normal => {}502 Visibility::Hidden => {503 *visible = false;504 }505 Visibility::Unhide => {506 *visible = true;507 }508 };509 false510 },511 );512 out513 }514 pub fn fields_ex(515 &self,516 include_hidden: bool,517 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,518 ) -> Vec<IStr> {519 #[cfg(feature = "exp-preserve-order")]520 if preserve_order {521 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self522 .fields_visibility()523 .into_iter()524 .filter(|(_, (visible, _))| include_hidden || *visible)525 .enumerate()526 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))527 .unzip();528 keys.sort_unstable_by_key(|v| v.0);529 530 for i in 0..fields.len() {531 let x = fields[i].clone();532 let mut j = i;533 loop {534 let k = keys[j].1;535 keys[j].1 = j;536 if k == i {537 break;538 }539 fields[j] = fields[k].clone();540 j = k;541 }542 fields[j] = x;543 }544 return fields;545 }546547 let mut fields: Vec<_> = self548 .fields_visibility()549 .into_iter()550 .filter(|(_, (visible, _))| include_hidden || *visible)551 .map(|(k, _)| k)552 .collect();553 fields.sort_unstable();554 fields555 }556 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {557 self.fields_ex(558 false,559 #[cfg(feature = "exp-preserve-order")]560 preserve_order,561 )562 }563 pub fn values_ex(564 &self,565 include_hidden: bool,566 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,567 ) -> ArrValue {568 ArrValue::new(PickObjectValues::new(569 self.clone(),570 self.fields_ex(571 include_hidden,572 #[cfg(feature = "exp-preserve-order")]573 preserve_order,574 ),575 ))576 }577 pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {578 self.values_ex(579 false,580 #[cfg(feature = "exp-preserve-order")]581 preserve_order,582 )583 }584 pub fn key_values_ex(585 &self,586 include_hidden: bool,587 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,588 ) -> ArrValue {589 ArrValue::new(PickObjectKeyValues::new(590 self.clone(),591 self.fields_ex(592 include_hidden,593 #[cfg(feature = "exp-preserve-order")]594 preserve_order,595 ),596 ))597 }598 pub fn key_values(599 &self,600 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,601 ) -> ArrValue {602 self.key_values_ex(603 false,604 #[cfg(feature = "exp-preserve-order")]605 preserve_order,606 )607 }608}609610impl OopObject {611 pub fn new(612 sup: Option<ObjValue>,613 this_entries: Cc<GcHashMap<IStr, ObjMember>>,614 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,615 ) -> Self {616 Self {617 sup,618 619 assertions,620 assertions_ran: RefCell::new(GcHashSet::new()),621 this_entries,622 value_cache: RefCell::new(GcHashMap::new()),623 }624 }625626 fn evaluate_this(&self, v: &ObjMember, real_this: ObjValue) -> Result<Val> {627 v.invoke.evaluate(self.sup.clone(), Some(real_this))628 }629630 631 fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {632 let mut out = FxHashMap::default();633 self.enum_fields(634 SuperDepth::default(),635 &mut |depth, index, name, visibility| {636 let new_sort_key = FieldSortKey::new(depth, index);637 let entry = out.entry(name);638 let (visible, _) = entry.or_insert((true, new_sort_key));639 match visibility {640 Visibility::Normal => {}641 Visibility::Hidden => {642 *visible = false;643 }644 Visibility::Unhide => {645 *visible = true;646 }647 };648 false649 },650 );651 out652 }653}654655impl ObjectLike for OopObject {656 fn extend_from(&self, sup: ObjValue) -> ObjValue {657 ObjValue::new(match &self.sup {658 None => Self::new(659 Some(sup),660 self.this_entries.clone(),661 self.assertions.clone(),662 ),663 Some(v) => Self::new(664 Some(v.extend_from(sup)),665 self.this_entries.clone(),666 self.assertions.clone(),667 ),668 })669 }670671 fn len(&self) -> usize {672 673 self.fields_visibility()674 .into_iter()675 .filter(|(_, (visible, _))| *visible)676 .count()677 }678679 680 681 682 fn is_empty(&self) -> bool {683 self.len() != 0684 }685686 687 688 689 fn enum_fields(&self, depth: SuperDepth, handler: &mut EnumFieldsHandler<'_>) -> bool {690 if let Some(s) = &self.sup {691 if s.enum_fields(depth.deeper(), handler) {692 return true;693 }694 }695 for (name, member) in self.this_entries.iter() {696 if handler(697 depth,698 member.original_index,699 name.clone(),700 member.flags.visibility(),701 ) {702 return true;703 }704 }705 false706 }707708 fn has_field_include_hidden(&self, name: IStr) -> bool {709 if self.this_entries.contains_key(&name) {710 true711 } else if let Some(super_obj) = &self.sup {712 super_obj.has_field_include_hidden(name)713 } else {714 false715 }716 }717 fn has_field(&self, name: IStr) -> bool {718 self.field_visibility(name)719 .map_or(false, |v| v.is_visible())720 }721722 fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {723 let cache_key = (key.clone(), Some(this.clone().downgrade()));724 if let Some(v) = self.value_cache.borrow().get(&cache_key) {725 return Ok(match v {726 CacheValue::Cached(v) => Some(v.clone()),727 CacheValue::NotFound => None,728 CacheValue::Pending => bail!(InfiniteRecursionDetected),729 CacheValue::Errored(e) => return Err(e.clone()),730 });731 }732 self.value_cache733 .borrow_mut()734 .insert(cache_key.clone(), CacheValue::Pending);735 let value = self.get_for_uncached(key, this).map_err(|e| {736 self.value_cache737 .borrow_mut()738 .insert(cache_key.clone(), CacheValue::Errored(e.clone()));739 e740 })?;741 self.value_cache.borrow_mut().insert(742 cache_key,743 value744 .as_ref()745 .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),746 );747 Ok(value)748 }749 fn get_for_uncached(&self, key: IStr, real_this: ObjValue) -> Result<Option<Val>> {750 match (self.this_entries.get(&key), &self.sup) {751 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),752 (Some(k), Some(super_obj)) => {753 let our = self.evaluate_this(k, real_this.clone())?;754 if k.flags.add() {755 super_obj756 .get_raw(key, real_this)?757 .map_or(Ok(Some(our.clone())), |v| {758 Ok(Some(evaluate_add_op(&v, &our)?))759 })760 } else {761 Ok(Some(our))762 }763 }764 (None, Some(super_obj)) => super_obj.get_raw(key, real_this),765 (None, None) => Ok(None),766 }767 }768 fn field_visibility(&self, name: IStr) -> Option<Visibility> {769 if let Some(m) = self.this_entries.get(&name) {770 Some(match &m.flags.visibility() {771 Visibility::Normal => self772 .sup773 .as_ref()774 .and_then(|super_obj| super_obj.field_visibility(name))775 .unwrap_or(Visibility::Normal),776 v => *v,777 })778 } else if let Some(super_obj) = &self.sup {779 super_obj.field_visibility(name)780 } else {781 None782 }783 }784785 fn run_assertions_raw(&self, real_this: ObjValue) -> Result<()> {786 if self.assertions.is_empty() {787 if let Some(super_obj) = &self.sup {788 super_obj.run_assertions_raw(real_this)?;789 }790 return Ok(());791 }792 if self.assertions_ran.borrow_mut().insert(real_this.clone()) {793 for assertion in self.assertions.iter() {794 if let Err(e) = assertion.run(self.sup.clone(), Some(real_this.clone())) {795 self.assertions_ran.borrow_mut().remove(&real_this);796 return Err(e);797 }798 }799 if let Some(super_obj) = &self.sup {800 super_obj.run_assertions_raw(real_this)?;801 }802 }803 Ok(())804 }805}806807impl PartialEq for ObjValue {808 fn eq(&self, other: &Self) -> bool {809 Cc::ptr_eq(&self.0, &other.0)810 }811}812813impl Eq for ObjValue {}814impl Hash for ObjValue {815 fn hash<H: Hasher>(&self, hasher: &mut H) {816 hasher.write_usize(addr_of!(*self.0) as usize);817 }818}819820#[allow(clippy::module_name_repetitions)]821pub struct ObjValueBuilder {822 sup: Option<ObjValue>,823 map: GcHashMap<IStr, ObjMember>,824 assertions: Vec<TraceBox<dyn ObjectAssertion>>,825 next_field_index: FieldIndex,826}827impl ObjValueBuilder {828 pub fn new() -> Self {829 Self::with_capacity(0)830 }831 pub fn with_capacity(capacity: usize) -> Self {832 Self {833 sup: None,834 map: GcHashMap::with_capacity(capacity),835 assertions: Vec::new(),836 next_field_index: FieldIndex::default(),837 }838 }839 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {840 self.assertions.reserve_exact(capacity);841 self842 }843 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {844 self.sup = Some(super_obj);845 self846 }847848 pub fn assert(&mut self, assertion: impl ObjectAssertion + 'static) -> &mut Self {849 self.assertions.push(tb!(assertion));850 self851 }852 pub fn field(&mut self, name: impl Into<IStr>) -> ObjMemberBuilder<ValueBuilder<'_>> {853 let field_index = self.next_field_index;854 self.next_field_index = self.next_field_index.next();855 ObjMemberBuilder::new(ValueBuilder(self), name.into(), field_index)856 }857 858 859 860 861 pub fn method(&mut self, name: impl Into<IStr>, value: impl Into<FuncVal>) -> &mut Self {862 self.field(name).hide().value(Val::Func(value.into()));863 self864 }865 pub fn try_method(866 &mut self,867 name: impl Into<IStr>,868 value: impl Into<FuncVal>,869 ) -> Result<&mut Self> {870 self.field(name).hide().try_value(Val::Func(value.into()))?;871 Ok(self)872 }873874 pub fn build(self) -> ObjValue {875 if self.sup.is_none() && self.map.is_empty() && self.assertions.is_empty() {876 return ObjValue::new_empty();877 }878 ObjValue::new(OopObject::new(879 self.sup,880 Cc::new(self.map),881 Cc::new(self.assertions),882 ))883 }884}885impl Default for ObjValueBuilder {886 fn default() -> Self {887 Self::with_capacity(0)888 }889}890891#[allow(clippy::module_name_repetitions)]892#[must_use = "value not added unless binding() was called"]893pub struct ObjMemberBuilder<Kind> {894 kind: Kind,895 name: IStr,896 add: bool,897 visibility: Visibility,898 original_index: FieldIndex,899 location: Option<ExprLocation>,900}901902#[allow(clippy::missing_const_for_fn)]903impl<Kind> ObjMemberBuilder<Kind> {904 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {905 Self {906 kind,907 name,908 original_index,909 add: false,910 visibility: Visibility::Normal,911 location: None,912 }913 }914915 pub const fn with_add(mut self, add: bool) -> Self {916 self.add = add;917 self918 }919 pub fn add(self) -> Self {920 self.with_add(true)921 }922 pub fn with_visibility(mut self, visibility: Visibility) -> Self {923 self.visibility = visibility;924 self925 }926 pub fn hide(self) -> Self {927 self.with_visibility(Visibility::Hidden)928 }929 pub fn with_location(mut self, location: ExprLocation) -> Self {930 self.location = Some(location);931 self932 }933 fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {934 (935 self.kind,936 self.name,937 ObjMember {938 flags: ObjFieldFlags::new(self.add, self.visibility),939 original_index: self.original_index,940 invoke: binding,941 location: self.location,942 },943 )944 }945}946947pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);948impl ObjMemberBuilder<ValueBuilder<'_>> {949 950 pub fn value(self, value: impl Into<Val>) {951 let (receiver, name, member) =952 self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value.into())));953 let entry = receiver.0.map.entry(name);954 entry.insert(member);955 }956957 958 pub fn try_value(self, value: impl Into<Val>) -> Result<()> {959 self.thunk(Thunk::evaluated(value.into()))960 }961 pub fn thunk(self, value: impl Into<Thunk<Val>>) -> Result<()> {962 self.binding(MaybeUnbound::Bound(value.into()))963 }964 pub fn bindable(self, bindable: impl Unbound<Bound = Val>) -> Result<()> {965 self.binding(MaybeUnbound::Unbound(Cc::new(tb!(bindable))))966 }967 pub fn binding(self, binding: MaybeUnbound) -> Result<()> {968 let (receiver, name, member) = self.build_member(binding);969 let location = member.location.clone();970 let old = receiver.0.map.insert(name.clone(), member);971 if old.is_some() {972 State::push(973 CallLocation(location.as_ref()),974 || format!("field <{}> initializtion", name.clone()),975 || bail!(DuplicateFieldName(name.clone())),976 )?;977 }978 Ok(())979 }980}981982pub struct ExtendBuilder<'v>(&'v mut ObjValue);983impl ObjMemberBuilder<ExtendBuilder<'_>> {984 pub fn value(self, value: impl Into<Val>) {985 self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));986 }987 pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Val>>) {988 self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));989 }990 pub fn binding(self, binding: MaybeUnbound) {991 let (receiver, name, member) = self.build_member(binding);992 let new = receiver.0.clone();993 *receiver.0 = new.extend_with_raw_member(name, member);994 }995}