1use std::{2 any::Any,3 cell::{Cell, RefCell},4 clone::Clone,5 cmp::Reverse,6 collections::hash_map::Entry,7 fmt::{self, Debug},8 hash::{Hash, Hasher},9 num::Saturating,10 ops::ControlFlow,11};1213use educe::Educe;14use im_rc::{Vector, vector};15use jrsonnet_gcmodule::{Acyclic, Cc, Trace, Weak, cc_dyn};16use jrsonnet_interner::IStr;17use jrsonnet_ir::Span;18use rustc_hash::{FxHashMap, FxHashSet};1920mod oop;2122pub use jrsonnet_ir::Visibility;23pub use oop::ObjValueBuilder;2425use crate::{26 CcUnbound, MaybeUnbound, Result, Thunk, Unbound, Val,27 arr::{PickObjectKeyValues, PickObjectValues},28 bail,29 error::{ErrorKind::*, suggest_object_fields},30 identity_hash,31 operator::evaluate_add_op,32 val::{ArrValue, ThunkValue},33};3435#[cfg(not(feature = "exp-preserve-order"))]36pub mod ordering {37 #![allow(38 39 clippy::unused_self,40 )]4142 use jrsonnet_gcmodule::Trace;4344 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]45 pub struct FieldIndex(());46 impl FieldIndex {47 pub fn absolute(_v: u32) -> Self {48 Self(())49 }50 #[must_use]51 pub const fn next(self) -> Self {52 Self(())53 }54 }5556 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]57 pub struct SuperDepth(());58 impl SuperDepth {59 pub(super) fn deepen(self) {}60 }61}6263#[cfg(feature = "exp-preserve-order")]64pub mod ordering {65 use jrsonnet_gcmodule::Trace;6667 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]68 pub struct FieldIndex(u32);69 impl FieldIndex {70 pub fn absolute(v: u32) -> Self {71 Self(v)72 }73 #[must_use]74 pub fn next(self) -> Self {75 Self(self.0 + 1)76 }77 }7879 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]80 pub struct SuperDepth(u32);81 impl SuperDepth {82 pub(super) fn deepen(&mut self) {83 self.0 += 1;84 }85 }86}8788use ordering::{FieldIndex, SuperDepth};8990#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]91pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);92impl FieldSortKey {93 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {94 Self(Reverse(depth), index)95 }96}979899100#[derive(Clone, Copy)]101pub struct ObjFieldFlags(u8);102impl ObjFieldFlags {103 fn new(add: bool, visibility: Visibility) -> Self {104 let mut v = 0;105 if add {106 v |= 1;107 }108 v |= match visibility {109 Visibility::Normal => 0b000,110 Visibility::Hidden => 0b010,111 Visibility::Unhide => 0b100,112 };113 Self(v)114 }115 pub fn add(&self) -> bool {116 self.0 & 1 != 0117 }118 pub fn visibility(&self) -> Visibility {119 match (self.0 & 0b110) >> 1 {120 0b00 => Visibility::Normal,121 0b01 => Visibility::Hidden,122 0b10 => Visibility::Unhide,123 _ => unreachable!(),124 }125 }126}127impl Debug for ObjFieldFlags {128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {129 f.debug_struct("ObjFieldFlags")130 .field("add", &self.add())131 .field("visibility", &self.visibility())132 .finish()133 }134}135136#[allow(clippy::module_name_repetitions)]137#[derive(Debug, Trace)]138pub struct ObjMember {139 #[trace(skip)]140 flags: ObjFieldFlags,141 original_index: FieldIndex,142 pub invoke: MaybeUnbound,143 pub location: Option<Span>,144}145146cc_dyn!(CcObjectAssertion, ObjectAssertion);147pub trait ObjectAssertion: Trace {148 fn run(&self, sup_this: SupThis) -> Result<()>;149}150151152153#[derive(Trace, Debug)]154enum CacheValue {155 Cached(Result<Option<Val>>),156 Pending,157}158159pub type EnumFieldsHandler<'a> =160 dyn FnMut(SuperDepth, FieldIndex, IStr, EnumFields) -> ControlFlow<()> + 'a;161162#[derive(Debug)]163pub enum EnumFields {164 Normal(Visibility),165 Omit(Skip),166}167168#[derive(Trace, Clone)]169pub enum GetFor {170 171 Final(Val),172 173 SuperPlus(Val),174 175 Omit(#[trace(skip)] Skip),176 NotFound,177}178179#[derive(Acyclic, Clone)]180pub enum FieldVisibility {181 Found(Visibility),182 Omit(Skip),183 NotFound,184}185186#[derive(Acyclic, Clone)]187pub enum HasFieldIncludeHidden {188 Exists,189 NotFound,190 Omit(Skip),191}192193type Skip = Saturating<usize>;194195pub trait ObjectCore: Trace + Any + Debug {196 197 fn enum_fields_core(198 &self,199 super_depth: &mut SuperDepth,200 handler: &mut EnumFieldsHandler<'_>,201 ) -> bool;202203 fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden;204205 fn get_for_core(&self, key: IStr, sup_this: SupThis, omit_only: bool) -> Result<GetFor>;206 fn field_visibility_core(&self, field: IStr) -> FieldVisibility;207208 fn run_assertions_core(&self, sup_this: SupThis) -> Result<()>;209}210211#[derive(Clone, Trace)]212pub struct WeakObjValue(#[trace(skip)] Weak<ObjValueInner>);213impl Debug for WeakObjValue {214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {215 f.debug_tuple("WeakObjValue").finish()216 }217}218219impl PartialEq for WeakObjValue {220 fn eq(&self, other: &Self) -> bool {221 Weak::ptr_eq(&self.0, &other.0)222 }223}224225impl Eq for WeakObjValue {}226impl Hash for WeakObjValue {227 fn hash<H: Hasher>(&self, hasher: &mut H) {228 229 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };230 hasher.write_usize(addr);231 }232}233234cc_dyn!(235 #[derive(Clone, Debug)]236 CcObjectCore, ObjectCore,237 pub fn new() {...}238);239240#[derive(Trace, Educe)]241#[educe(Debug)]242struct ObjValueInner {243 cores: Vector<CcObjectCore>,244 assertions_ran: Cell<bool>,245 has_assertions: bool,246 value_cache: RefCell<FxHashMap<(IStr, CoreIdx), CacheValue>>,247}248249thread_local! {250 static RUNNING_ASSERTIONS: RefCell<FxHashSet<ObjValue>> = RefCell::default();251}252fn is_asserting(obj: &ObjValue) -> bool {253 RUNNING_ASSERTIONS.with_borrow(|v| v.contains(obj))254}255256fn start_asserting(obj: &ObjValue) -> bool {257 RUNNING_ASSERTIONS.with_borrow_mut(|v| v.insert(obj.clone()))258}259fn finish_asserting(obj: &ObjValue) {260 RUNNING_ASSERTIONS.with_borrow_mut(|v| {261 let r = v.remove(obj);262 debug_assert!(263 r,264 "finish_asserting was called before start_asserting or twice"265 );266 });267}268269thread_local! {270 static EMPTY_OBJ: ObjValue = ObjValue(Cc::new(ObjValueInner {271 cores: vector![],272 assertions_ran: Cell::new(true),273 has_assertions: false,274 value_cache: RefCell::default(),275 }))276}277278#[allow(clippy::module_name_repetitions)]279#[derive(Clone, Trace, Debug, Educe)]280#[educe(PartialEq, Hash, Eq)]281pub struct ObjValue(282 #[educe(PartialEq(method(Cc::ptr_eq)), Hash(method(identity_hash)))] Cc<ObjValueInner>,283);284285impl ObjValue {286 pub fn empty() -> Self {287 EMPTY_OBJ.with(Clone::clone)288 }289 pub fn is_empty(&self) -> bool {290 self.0.cores.is_empty() || self.len() == 0291 }292}293294#[derive(Trace, Debug)]295pub(crate) struct StandaloneSuperCore {296 sup: CoreIdx,297 this: ObjValue,298}299impl ObjectCore for StandaloneSuperCore {300 fn enum_fields_core(301 &self,302 super_depth: &mut SuperDepth,303 handler: &mut EnumFieldsHandler<'_>,304 ) -> bool {305 self.this.enum_fields_idx(super_depth, handler, self.sup)306 }307308 fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {309 if self.this.has_field_include_hidden_idx(name, self.sup) {310 HasFieldIncludeHidden::Exists311 } else {312 HasFieldIncludeHidden::NotFound313 }314 }315316 fn get_for_core(&self, key: IStr, _sup_this: SupThis, omit_only: bool) -> Result<GetFor> {317 if omit_only {318 return Ok(GetFor::NotFound);319 }320 let v = self.this.get_idx(key, self.sup)?;321 Ok(v.map_or(GetFor::NotFound, GetFor::Final))322 }323324 fn field_visibility_core(&self, field: IStr) -> FieldVisibility {325 self.this326 .field_visibility_idx(field, self.sup)327 .map_or(FieldVisibility::NotFound, FieldVisibility::Found)328 }329330 fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {331 self.this.run_assertions()332 }333}334335#[derive(Debug, Acyclic)]336struct OmitFieldsCore {337 omit: FxHashSet<IStr>,338 prev_layers: usize,339}340impl ObjectCore for OmitFieldsCore {341 fn enum_fields_core(342 &self,343 super_depth: &mut SuperDepth,344 handler: &mut EnumFieldsHandler<'_>,345 ) -> bool {346 let mut fi = FieldIndex::default();347 for f in &self.omit {348 if handler(349 *super_depth,350 fi,351 f.clone(),352 EnumFields::Omit(Saturating(self.prev_layers)),353 ) == ControlFlow::Break(())354 {355 return false;356 }357 fi = fi.next();358 }359 true360 }361362 fn has_field_include_hidden_core(&self, name: IStr) -> HasFieldIncludeHidden {363 if self.omit.contains(&name) {364 return HasFieldIncludeHidden::Omit(Saturating(self.prev_layers));365 }366 HasFieldIncludeHidden::NotFound367 }368369 fn get_for_core(&self, key: IStr, _sup_this: SupThis, _omit_only: bool) -> Result<GetFor> {370 if self.omit.contains(&key) {371 return Ok(GetFor::Omit(Saturating(self.prev_layers)));372 }373 Ok(GetFor::NotFound)374 }375376 fn field_visibility_core(&self, field: IStr) -> FieldVisibility {377 if self.omit.contains(&field) {378 return FieldVisibility::Omit(Saturating(self.prev_layers));379 }380 FieldVisibility::NotFound381 }382383 fn run_assertions_core(&self, _sup_this: SupThis) -> Result<()> {384 Ok(())385 }386}387388#[derive(Hash, PartialEq, Eq, Trace, Clone, Copy, Debug)]389struct CoreIdx {390 idx: usize,391}392impl CoreIdx {393 fn super_exists(self) -> bool {394 self.idx != 0395 }396}397#[derive(Trace, Clone, PartialEq, Eq, Hash, Debug)]398pub struct SupThis {399 sup: CoreIdx,400 this: ObjValue,401}402impl SupThis {403 pub fn has_super(&self) -> bool {404 self.sup.super_exists()405 }406 407 408 409 410 pub fn field_in_super(&self, field: IStr) -> bool {411 self.this.has_field_include_hidden_idx(field, self.sup)412 }413 414 415 416 417 pub fn get_super(&self, field: IStr) -> Result<Option<Val>> {418 if !self.sup.super_exists() {419 bail!(NoSuperFound);420 }421 self.this.get_idx(field, self.sup)422 }423 424 425 426 427 428 pub fn standalone_super(&self) -> Result<ObjValue> {429 if !self.sup.super_exists() {430 bail!(NoSuperFound)431 }432 let mut out = ObjValue::builder();433 out.extend_with_core(StandaloneSuperCore {434 sup: self.sup,435 this: self.this.clone(),436 });437 Ok(out.build())438 }439 pub fn this(&self) -> &ObjValue {440 &self.this441 }442 pub fn downgrade(self) -> WeakSupThis {443 WeakSupThis {444 sup: self.sup,445 this: self.this.downgrade(),446 }447 }448}449#[derive(Trace, PartialEq, Eq, Hash, Debug)]450pub struct WeakSupThis {451 sup: CoreIdx,452 this: WeakObjValue,453}454455impl ObjValue {456 pub fn builder() -> ObjValueBuilder {457 ObjValueBuilder::new()458 }459 pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {460 ObjValueBuilder::with_capacity(capacity)461 }462 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {463 let mut out = ObjValueBuilder::with_capacity(1);464 out.with_super(self);465 let mut member = out.field(key);466 if value.flags.add() {467 member = member.add();468 }469 if let Some(loc) = value.location {470 member = member.with_location(loc);471 }472 let _ = member473 .with_visibility(value.flags.visibility())474 .binding(value.invoke);475 out.build()476 }477 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {478 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())479 }480481 pub fn extend(&mut self) -> ObjValueBuilder {482 let mut out = ObjValueBuilder::new();483 out.with_super(self.clone());484 out485 }486487 #[must_use]488 pub fn extend_from(&self, sup: Self) -> Self {489 let cores = sup.0.cores.clone() + self.0.cores.clone();490 let has_assertions = sup.0.has_assertions || self.0.has_assertions;491 ObjValue(Cc::new(ObjValueInner {492 cores,493 value_cache: RefCell::default(),494 assertions_ran: Cell::new(!has_assertions),495 has_assertions,496 }))497 }498 499 500 501 502 503 504 pub fn len(&self) -> usize {505 self.fields_visibility()506 .values()507 .filter(|d| d.visible())508 .count()509 }510 511 512 513 514 pub fn enum_fields(&self, handler: &mut EnumFieldsHandler<'_>) -> bool {515 let mut super_depth = SuperDepth::default();516 self.enum_fields_idx(517 &mut super_depth,518 handler,519 CoreIdx {520 idx: self.0.cores.len(),521 },522 )523 }524525 fn iter_cores(&self, idx: CoreIdx) -> impl Iterator<Item = &CcObjectCore> {526 self.0.cores.iter().take(idx.idx).rev()527 }528 fn iter_cores_enumerate(&self, idx: CoreIdx) -> impl Iterator<Item = (CoreIdx, &CcObjectCore)> {529 self.0530 .cores531 .iter()532 .take(idx.idx)533 .enumerate()534 .rev()535 .map(|(idx, o)| (CoreIdx { idx }, o))536 }537538 fn enum_fields_idx(539 &self,540 super_depth: &mut SuperDepth,541 handler: &mut EnumFieldsHandler<'_>,542 idx: CoreIdx,543 ) -> bool {544 for core in self.iter_cores(idx) {545 if !core.0.enum_fields_core(super_depth, handler) {546 return false;547 }548 super_depth.deepen();549 }550 true551 }552553 pub fn has_field_include_hidden(&self, name: IStr) -> bool {554 self.has_field_include_hidden_idx(555 name,556 CoreIdx {557 idx: self.0.cores.len(),558 },559 )560 }561 fn has_field_include_hidden_idx(&self, name: IStr, core: CoreIdx) -> bool {562 let mut skip = Saturating(0usize);563 for ele in self.iter_cores(core) {564 match ele.0.has_field_include_hidden_core(name.clone()) {565 HasFieldIncludeHidden::Exists => {566 if skip.0 == 0 {567 return true;568 }569 }570 HasFieldIncludeHidden::Omit(new_skip) => {571 572 skip = skip.max(new_skip + Saturating(1));573 }574 HasFieldIncludeHidden::NotFound => {}575 }576 skip -= 1;577 }578 false579 }580 pub fn has_field(&self, name: IStr) -> bool {581 match self.field_visibility(name) {582 Some(Visibility::Unhide | Visibility::Normal) => true,583 Some(Visibility::Hidden) | None => false,584 }585 }586 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {587 if include_hidden {588 self.has_field_include_hidden(name)589 } else {590 self.has_field(name)591 }592 }593 pub fn get(&self, key: IStr) -> Result<Option<Val>> {594 self.get_idx(595 key,596 CoreIdx {597 idx: self.0.cores.len(),598 },599 )600 }601602 fn get_idx(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {603 let cache_key = (key.clone(), core);604 {605 let mut cache = self.0.value_cache.borrow_mut();606 607 match cache.entry(cache_key.clone()) {608 Entry::Occupied(v) => match v.get() {609 CacheValue::Cached(v) => return v.clone(),610 CacheValue::Pending => {611 if !is_asserting(self) {612 bail!(InfiniteRecursionDetected);613 }614 }615 },616 Entry::Vacant(v) => {617 v.insert(CacheValue::Pending);618 }619 };620 }621 let result = self.get_idx_uncached(key, core);622 {623 let mut cache = self.0.value_cache.borrow_mut();624 cache.insert(cache_key, CacheValue::Cached(result.clone()));625 }626 result627 }628 fn get_idx_uncached(&self, key: IStr, core: CoreIdx) -> Result<Option<Val>> {629 self.run_assertions()?;630 let mut first_add = None;631 let mut add_stack: Vec<Val> = Vec::new();632 let mut skip = Saturating(0);633 for (sup, core) in self.iter_cores_enumerate(core) {634 let sup_this = SupThis {635 sup,636 this: self.clone(),637 };638 match core.0.get_for_core(key.clone(), sup_this, skip.0 != 0)? {639 GetFor::Final(val) if first_add.is_none() => {640 if skip.0 == 0 {641 return Ok(Some(val));642 }643 }644 GetFor::Final(val) => {645 if skip.0 == 0 {646 add_stack.push(val);647 break;648 }649 }650 GetFor::SuperPlus(val) => {651 if skip.0 == 0 {652 if first_add.is_none() {653 first_add = Some(val);654 } else {655 add_stack.push(val);656 }657 }658 }659 GetFor::Omit(new_skip) => {660 skip = skip.max(new_skip + Saturating(1));661 }662 GetFor::NotFound => {}663 }664 skip -= 1;665 }666 let Some(first) = first_add else {667 if add_stack.is_empty() {668 return Ok(None);669 }670 return Ok(Some(add_stack.pop().expect("single element on stack")));671 };672 if add_stack.is_empty() {673 return Ok(Some(first));674 }675 add_stack.insert(0, first);676 let mut values = add_stack.into_iter().rev();677 let init = values.next().expect("at least 2 elements");678679 values680 .try_fold(init, |a, b| evaluate_add_op(&a, &b))681 .map(Some)682 }683684 pub fn get_or_bail(&self, key: IStr) -> Result<Val> {685 let Some(value) = self.get(key.clone())? else {686 let suggestions = suggest_object_fields(self, key.clone());687 bail!(NoSuchField(key, suggestions))688 };689 Ok(value)690 }691692 fn field_visibility(&self, field: IStr) -> Option<Visibility> {693 self.field_visibility_idx(694 field,695 CoreIdx {696 idx: self.0.cores.len(),697 },698 )699 }700 fn field_visibility_idx(&self, field: IStr, core: CoreIdx) -> Option<Visibility> {701 let mut exists = false;702 let mut skip = Saturating(0usize);703 for ele in self.iter_cores(core) {704 let vis = ele.0.field_visibility_core(field.clone());705 match vis {706 FieldVisibility::Found(vis @ (Visibility::Unhide | Visibility::Hidden)) => {707 if skip.0 == 0 {708 return Some(vis);709 }710 }711 FieldVisibility::Found(Visibility::Normal) => {712 if skip.0 == 0 {713 exists = true;714 }715 }716 FieldVisibility::NotFound => {}717 FieldVisibility::Omit(new_skip) => {718 719 skip = skip.max(new_skip + Saturating(1));720 }721 }722 skip -= 1;723 }724 exists.then_some(Visibility::Normal)725 }726727 pub fn run_assertions(&self) -> Result<()> {728 if self.0.assertions_ran.get() {729 return Ok(());730 }731 if !start_asserting(self) {732 return Ok(());733 }734 for (idx, ele) in self.0.cores.iter().enumerate() {735 let sup_this = SupThis {736 sup: CoreIdx { idx },737 this: self.clone(),738 };739 ele.0.run_assertions_core(sup_this).inspect_err(|_e| {740 finish_asserting(self);741 })?;742 }743 finish_asserting(self);744 self.0.assertions_ran.set(true);745 Ok(())746 }747748 pub fn iter(749 &self,750 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,751 ) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {752 let fields = self.fields(753 #[cfg(feature = "exp-preserve-order")]754 preserve_order,755 );756 fields.into_iter().map(|field| {757 (758 field.clone(),759 self.get(field)760 .map(|opt| opt.expect("iterating over keys, field exists")),761 )762 })763 }764 pub fn get_lazy(&self, key: IStr) -> Option<Thunk<Val>> {765 #[derive(Trace)]766 struct ObjFieldThunk {767 obj: ObjValue,768 key: IStr,769 }770 impl ThunkValue for ObjFieldThunk {771 type Output = Val;772773 fn get(&self) -> Result<Self::Output> {774 self.obj775 .get(self.key.clone())776 .transpose()777 .expect("field existence checked")778 }779 }780781 if !self.has_field_ex(key.clone(), true) {782 return None;783 }784785 Some(Thunk::new(ObjFieldThunk {786 obj: self.clone(),787 key,788 }))789 }790 pub fn get_lazy_or_bail(&self, key: IStr) -> Thunk<Val> {791 #[derive(Trace)]792 struct ObjFieldThunk {793 obj: ObjValue,794 key: IStr,795 }796 impl ThunkValue for ObjFieldThunk {797 type Output = Val;798799 fn get(&self) -> Result<Self::Output> {800 self.obj.get_or_bail(self.key.clone())801 }802 }803804 Thunk::new(ObjFieldThunk {805 obj: self.clone(),806 key,807 })808 }809810 #[allow(dead_code, reason = "used in object ...rest destructuring")]811 pub(crate) fn as_standalone(&self) -> StandaloneSuperCore {812 StandaloneSuperCore {813 sup: CoreIdx {814 idx: self.0.cores.len(),815 },816 this: self.clone(),817 }818 }819 pub fn ptr_eq(a: &Self, b: &Self) -> bool {820 Cc::ptr_eq(&a.0, &b.0)821 }822 pub fn downgrade(self) -> WeakObjValue {823 WeakObjValue(self.0.downgrade())824 }825}826827#[derive(Debug)]828struct FieldVisibilityData {829 omitted_until: Saturating<usize>,830 exists_visible: Option<Visibility>,831 #[allow(dead_code, reason = "used for exp-object-ordering, ZST otherwise")]832 key: FieldSortKey,833}834impl FieldVisibilityData {835 fn visible(&self) -> bool {836 self.exists_visible837 .expect("non-existing fields shall be dropped at the end of fn fields_visibility()")838 .is_visible()839 }840 #[allow(dead_code, reason = "used for exp-object-ordering, ZST otherwise")]841 fn sort_key(&self) -> FieldSortKey {842 self.key843 }844}845846impl ObjValue {847 fn fields_visibility(&self) -> FxHashMap<IStr, FieldVisibilityData> {848 let mut out = FxHashMap::default();849850 let mut super_depth = SuperDepth::default();851 let mut omit_index = Saturating(0);852 for core in self.0.cores.iter().rev() {853 core.0854 .enum_fields_core(&mut super_depth, &mut |depth, index, name, visibility| {855 let entry = out.entry(name);856 let data = entry.or_insert_with(|| FieldVisibilityData {857 exists_visible: None,858 key: FieldSortKey::new(depth, index),859 omitted_until: omit_index,860 });861 match visibility {862 EnumFields::Omit(new_skip) => {863 864 data.omitted_until = data865 .omitted_until866 .max(omit_index + new_skip + Saturating(1));867 }868 EnumFields::Normal(Visibility::Normal) => {869 if data.omitted_until <= omit_index && data.exists_visible.is_none() {870 data.exists_visible = Some(Visibility::Normal);871 }872 }873 EnumFields::Normal(Visibility::Hidden) => {874 if data.omitted_until <= omit_index {875 data.exists_visible = Some(match data.exists_visible {876 877 Some(Visibility::Unhide) => Visibility::Unhide,878 _ => Visibility::Hidden,879 });880 }881 }882 EnumFields::Normal(Visibility::Unhide) => {883 if data.omitted_until <= omit_index {884 data.exists_visible = Some(match data.exists_visible {885 886 Some(Visibility::Hidden) => Visibility::Hidden,887 _ => Visibility::Unhide,888 });889 }890 }891 }892 ControlFlow::Continue(())893 });894895 super_depth.deepen();896 omit_index += 1;897 }898899 out.retain(|_, v| v.exists_visible.is_some());900901 out902 }903 pub fn fields_ex(904 &self,905 include_hidden: bool,906 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,907 ) -> Vec<IStr> {908 #[cfg(feature = "exp-preserve-order")]909 if preserve_order {910 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self911 .fields_visibility()912 .into_iter()913 .filter(|(_, d)| include_hidden || d.visible())914 .enumerate()915 .map(|(idx, (k, d))| (k, (d.sort_key(), idx)))916 .unzip();917 keys.sort_unstable_by_key(|v| v.0);918 919 for i in 0..fields.len() {920 let x = fields[i].clone();921 let mut j = i;922 loop {923 let k = keys[j].1;924 keys[j].1 = j;925 if k == i {926 break;927 }928 fields[j] = fields[k].clone();929 j = k;930 }931 fields[j] = x;932 }933 return fields;934 }935936 let mut fields: Vec<_> = self937 .fields_visibility()938 .into_iter()939 .filter(|(_, d)| include_hidden || d.visible())940 .map(|(k, _)| k)941 .collect();942 fields.sort_unstable();943 fields944 }945 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {946 self.fields_ex(947 false,948 #[cfg(feature = "exp-preserve-order")]949 preserve_order,950 )951 }952 pub fn values_ex(953 &self,954 include_hidden: bool,955 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,956 ) -> ArrValue {957 ArrValue::new(PickObjectValues::new(958 self.clone(),959 self.fields_ex(960 include_hidden,961 #[cfg(feature = "exp-preserve-order")]962 preserve_order,963 ),964 ))965 }966 pub fn values(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> ArrValue {967 self.values_ex(968 false,969 #[cfg(feature = "exp-preserve-order")]970 preserve_order,971 )972 }973 pub fn key_values_ex(974 &self,975 include_hidden: bool,976 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,977 ) -> ArrValue {978 ArrValue::new(PickObjectKeyValues::new(979 self.clone(),980 self.fields_ex(981 include_hidden,982 #[cfg(feature = "exp-preserve-order")]983 preserve_order,984 ),985 ))986 }987 pub fn key_values(988 &self,989 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,990 ) -> ArrValue {991 self.key_values_ex(992 false,993 #[cfg(feature = "exp-preserve-order")]994 preserve_order,995 )996 }997}998999#[allow(clippy::module_name_repetitions)]1000#[must_use = "value not added unless binding() was called"]1001pub struct ObjMemberBuilder<Kind> {1002 kind: Kind,1003 name: IStr,1004 add: bool,1005 visibility: Visibility,1006 original_index: FieldIndex,1007 location: Option<Span>,1008}10091010#[allow(clippy::missing_const_for_fn)]1011impl<Kind> ObjMemberBuilder<Kind> {1012 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {1013 Self {1014 kind,1015 name,1016 original_index,1017 add: false,1018 visibility: Visibility::Normal,1019 location: None,1020 }1021 }10221023 pub const fn with_add(mut self, add: bool) -> Self {1024 self.add = add;1025 self1026 }1027 pub fn add(self) -> Self {1028 self.with_add(true)1029 }1030 pub fn with_visibility(mut self, visibility: Visibility) -> Self {1031 self.visibility = visibility;1032 self1033 }1034 pub fn hide(self) -> Self {1035 self.with_visibility(Visibility::Hidden)1036 }1037 pub fn with_location(mut self, location: Span) -> Self {1038 self.location = Some(location);1039 self1040 }1041 fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {1042 (1043 self.kind,1044 self.name,1045 ObjMember {1046 flags: ObjFieldFlags::new(self.add, self.visibility),1047 original_index: self.original_index,1048 invoke: binding,1049 location: self.location,1050 },1051 )1052 }1053}10541055pub struct ExtendBuilder<'v>(&'v mut ObjValue);1056impl ObjMemberBuilder<ExtendBuilder<'_>> {1057 pub fn value(self, value: impl Into<Val>) {1058 self.binding(MaybeUnbound::Bound(Thunk::evaluated(value.into())));1059 }1060 pub fn bindable(self, bindable: impl Unbound<Bound = Val>) {1061 self.binding(MaybeUnbound::Unbound(CcUnbound::new(bindable)));1062 }1063 pub fn binding(self, binding: MaybeUnbound) {1064 let (receiver, name, member) = self.build_member(binding);1065 let new = receiver.0.clone();1066 *receiver.0 = new.extend_with_raw_member(name, member);1067 }1068}