1use std::{2 cell::RefCell,3 fmt::Debug,4 hash::{Hash, Hasher},5 ptr::addr_of,6};78use jrsonnet_gcmodule::{Cc, Trace, Weak};9use jrsonnet_interner::IStr;10use jrsonnet_parser::{ExprLocation, Visibility};11use rustc_hash::FxHashMap;1213use crate::{14 error::{Error::*, LocError},15 function::CallLocation,16 gc::{GcHashMap, GcHashSet, TraceBox},17 operator::evaluate_add_op,18 throw, MaybeUnbound, Result, State, Thunk, Unbound, Val,19};2021#[cfg(not(feature = "exp-preserve-order"))]22mod ordering {23 #![allow(24 25 clippy::unused_self,26 )]2728 use jrsonnet_gcmodule::Trace;2930 #[derive(Clone, Copy, Default, Debug, Trace)]31 pub struct FieldIndex;32 impl FieldIndex {33 pub const fn next(self) -> Self {34 Self35 }36 }3738 #[derive(Clone, Copy, Default, Debug, Trace)]39 pub struct SuperDepth;40 impl SuperDepth {41 pub const fn deeper(self) -> Self {42 Self43 }44 }4546 #[derive(Clone, Copy)]47 pub struct FieldSortKey;48 impl FieldSortKey {49 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {50 Self51 }52 }53}5455#[cfg(feature = "exp-preserve-order")]56mod ordering {57 use std::cmp::Reverse;5859 use jrsonnet_gcmodule::Trace;6061 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]62 pub struct FieldIndex(u32);63 impl FieldIndex {64 pub fn next(self) -> Self {65 Self(self.0 + 1)66 }67 }6869 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]70 pub struct SuperDepth(u32);71 impl SuperDepth {72 pub fn deeper(self) -> Self {73 Self(self.0 + 1)74 }75 }7677 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]78 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);79 impl FieldSortKey {80 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {81 Self(Reverse(depth), index)82 }83 pub fn collide(self, other: Self) -> Self {84 if self.0 .0 > other.0 .0 {85 self86 } else if self.0 .0 < other.0 .0 {87 other88 } else {89 unreachable!("object can't have two fields with same name")90 }91 }92 }93}9495use ordering::*;9697#[allow(clippy::module_name_repetitions)]98#[derive(Debug, Trace)]99pub struct ObjMember {100 pub add: bool,101 pub visibility: Visibility,102 original_index: FieldIndex,103 pub invoke: MaybeUnbound,104 pub location: Option<ExprLocation>,105}106107pub trait ObjectAssertion: Trace {108 fn run(&self, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;109}110111112113#[derive(Trace)]114enum CacheValue {115 Cached(Val),116 NotFound,117 Pending,118 Errored(LocError),119}120121#[allow(clippy::module_name_repetitions)]122#[derive(Trace)]123#[trace(tracking(force))]124pub struct ObjValueInternals {125 sup: Option<ObjValue>,126 this: Option<ObjValue>,127128 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,129 assertions_ran: RefCell<GcHashSet<ObjValue>>,130 this_entries: Cc<GcHashMap<IStr, ObjMember>>,131 value_cache: RefCell<GcHashMap<IStr, CacheValue>>,132}133134#[derive(Clone, Trace)]135pub struct WeakObjValue(#[trace(skip)] pub(crate) Weak<ObjValueInternals>);136137impl PartialEq for WeakObjValue {138 fn eq(&self, other: &Self) -> bool {139 Weak::ptr_eq(&self.0, &other.0)140 }141}142143impl Eq for WeakObjValue {}144impl Hash for WeakObjValue {145 fn hash<H: Hasher>(&self, hasher: &mut H) {146 147 let addr = unsafe { *std::ptr::addr_of!(self.0).cast() };148 hasher.write_usize(addr);149 }150}151152#[allow(clippy::module_name_repetitions)]153#[derive(Clone, Trace)]154pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);155impl Debug for ObjValue {156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {157 if let Some(super_obj) = self.0.sup.as_ref() {158 if f.alternate() {159 write!(f, "{super_obj:#?}")?;160 } else {161 write!(f, "{super_obj:?}")?;162 }163 write!(f, " + ")?;164 }165 let mut debug = f.debug_struct("ObjValue");166 for (name, member) in self.0.this_entries.iter() {167 debug.field(name, member);168 }169 debug.finish_non_exhaustive()170 }171}172173impl ObjValue {174 pub fn new(175 sup: Option<Self>,176 this_entries: Cc<GcHashMap<IStr, ObjMember>>,177 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,178 ) -> Self {179 Self(Cc::new(ObjValueInternals {180 sup,181 this: None,182 assertions,183 assertions_ran: RefCell::new(GcHashSet::new()),184 this_entries,185 value_cache: RefCell::new(GcHashMap::new()),186 }))187 }188 pub fn new_empty() -> Self {189 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))190 }191 #[must_use]192 pub fn extend_from(&self, sup: Self) -> Self {193 match &self.0.sup {194 None => Self::new(195 Some(sup),196 self.0.this_entries.clone(),197 self.0.assertions.clone(),198 ),199 Some(v) => Self::new(200 Some(v.extend_from(sup)),201 self.0.this_entries.clone(),202 self.0.assertions.clone(),203 ),204 }205 }206 pub(crate) fn extend_with_raw_member(self, key: IStr, value: ObjMember) -> Self {207 let mut new = GcHashMap::with_capacity(1);208 new.insert(key, value);209 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))210 }211 pub fn extend_field(&mut self, name: IStr) -> ObjMemberBuilder<ExtendBuilder<'_>> {212 ObjMemberBuilder::new(ExtendBuilder(self), name, FieldIndex::default())213 }214215 #[must_use]216 pub fn with_this(&self, this: Self) -> Self {217 Self(Cc::new(ObjValueInternals {218 sup: self.0.sup.clone(),219 assertions: self.0.assertions.clone(),220 assertions_ran: RefCell::new(GcHashSet::new()),221 this: Some(this),222 this_entries: self.0.this_entries.clone(),223 value_cache: RefCell::new(GcHashMap::new()),224 }))225 }226227 pub fn len(&self) -> usize {228 self.fields_visibility()229 .into_iter()230 .filter(|(_, (visible, _))| *visible)231 .count()232 }233234 pub fn is_empty(&self) -> bool {235 if !self.0.this_entries.is_empty() {236 return false;237 }238 self.0.sup.as_ref().map_or(true, Self::is_empty)239 }240241 242 243 244 pub(crate) fn enum_fields(245 &self,246 depth: SuperDepth,247 handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,248 ) -> bool {249 if let Some(s) = &self.0.sup {250 if s.enum_fields(depth.deeper(), handler) {251 return true;252 }253 }254 for (name, member) in self.0.this_entries.iter() {255 if handler(depth, name, member) {256 return true;257 }258 }259 false260 }261262 pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {263 let mut out = FxHashMap::default();264 self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {265 let new_sort_key = FieldSortKey::new(depth, member.original_index);266 let entry = out.entry(name.clone());267 let (visible, _) = entry.or_insert((true, new_sort_key));268 match member.visibility {269 Visibility::Normal => {}270 Visibility::Hidden => {271 *visible = false;272 }273 Visibility::Unhide => {274 *visible = true;275 }276 };277 false278 });279 out280 }281 pub fn fields_ex(282 &self,283 include_hidden: bool,284 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,285 ) -> Vec<IStr> {286 #[cfg(feature = "exp-preserve-order")]287 if preserve_order {288 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self289 .fields_visibility()290 .into_iter()291 .filter(|(_, (visible, _))| include_hidden || *visible)292 .enumerate()293 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))294 .unzip();295 keys.sort_unstable_by_key(|v| v.0);296 297 for i in 0..fields.len() {298 let x = fields[i].clone();299 let mut j = i;300 loop {301 let k = keys[j].1;302 keys[j].1 = j;303 if k == i {304 break;305 }306 fields[j] = fields[k].clone();307 j = k308 }309 fields[j] = x;310 }311 return fields;312 }313314 let mut fields: Vec<_> = self315 .fields_visibility()316 .into_iter()317 .filter(|(_, (visible, _))| include_hidden || *visible)318 .map(|(k, _)| k)319 .collect();320 fields.sort_unstable();321 fields322 }323 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {324 self.fields_ex(325 false,326 #[cfg(feature = "exp-preserve-order")]327 preserve_order,328 )329 }330331 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {332 if let Some(m) = self.0.this_entries.get(&name) {333 Some(match &m.visibility {334 Visibility::Normal => self335 .0336 .sup337 .as_ref()338 .and_then(|super_obj| super_obj.field_visibility(name))339 .unwrap_or(Visibility::Normal),340 v => *v,341 })342 } else if let Some(super_obj) = &self.0.sup {343 super_obj.field_visibility(name)344 } else {345 None346 }347 }348349 fn has_field_include_hidden(&self, name: IStr) -> bool {350 if self.0.this_entries.contains_key(&name) {351 true352 } else if let Some(super_obj) = &self.0.sup {353 super_obj.has_field_include_hidden(name)354 } else {355 false356 }357 }358359 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {360 if include_hidden {361 self.has_field_include_hidden(name)362 } else {363 self.has_field(name)364 }365 }366 pub fn has_field(&self, name: IStr) -> bool {367 self.field_visibility(name)368 .map_or(false, |v| v.is_visible())369 }370371 pub fn iter(372 &self,373 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,374 ) -> impl Iterator<Item = (IStr, Result<Val>)> + '_ {375 let fields = self.fields(376 #[cfg(feature = "exp-preserve-order")]377 preserve_order,378 );379 fields.into_iter().map(|field| {380 (381 field.clone(),382 self.get(field)383 .map(|opt| opt.expect("iterating over keys, field exists")),384 )385 })386 }387388 pub fn get(&self, key: IStr) -> Result<Option<Val>> {389 self.run_assertions()?;390 if let Some(v) = self.0.value_cache.borrow().get(&key) {391 return Ok(match v {392 CacheValue::Cached(v) => Some(v.clone()),393 CacheValue::NotFound => None,394 CacheValue::Pending => throw!(InfiniteRecursionDetected),395 CacheValue::Errored(e) => return Err(e.clone()),396 });397 }398 self.0399 .value_cache400 .borrow_mut()401 .insert(key.clone(), CacheValue::Pending);402 let value = self403 .get_raw(404 key.clone(),405 self.0.this.clone().unwrap_or_else(|| self.clone()),406 )407 .map_err(|e| {408 self.0409 .value_cache410 .borrow_mut()411 .insert(key.clone(), CacheValue::Errored(e.clone()));412 e413 })?;414 self.0.value_cache.borrow_mut().insert(415 key,416 value417 .as_ref()418 .map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),419 );420 Ok(value)421 }422423 fn get_raw(&self, key: IStr, real_this: Self) -> Result<Option<Val>> {424 match (self.0.this_entries.get(&key), &self.0.sup) {425 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),426 (Some(k), Some(super_obj)) => {427 let our = self.evaluate_this(k, real_this.clone())?;428 if k.add {429 super_obj430 .get_raw(key, real_this)?431 .map_or(Ok(Some(our.clone())), |v| {432 Ok(Some(evaluate_add_op(&v, &our)?))433 })434 } else {435 Ok(Some(our))436 }437 }438 (None, Some(super_obj)) => super_obj.get_raw(key, real_this),439 (None, None) => Ok(None),440 }441 }442 fn evaluate_this(&self, v: &ObjMember, real_this: Self) -> Result<Val> {443 v.invoke444 .evaluate(self.0.sup.clone(), Some(real_this))?445 .evaluate()446 }447448 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {449 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {450 for assertion in self.0.assertions.iter() {451 if let Err(e) = assertion.run(self.0.sup.clone(), Some(real_this.clone())) {452 self.0.assertions_ran.borrow_mut().remove(real_this);453 return Err(e);454 }455 }456 if let Some(super_obj) = &self.0.sup {457 super_obj.run_assertions_raw(real_this)?;458 }459 }460 Ok(())461 }462 pub fn run_assertions(&self) -> Result<()> {463 self.run_assertions_raw(self)464 }465466 pub fn ptr_eq(a: &Self, b: &Self) -> bool {467 Cc::ptr_eq(&a.0, &b.0)468 }469 pub fn downgrade(self) -> WeakObjValue {470 WeakObjValue(self.0.downgrade())471 }472}473474impl PartialEq for ObjValue {475 fn eq(&self, other: &Self) -> bool {476 Cc::ptr_eq(&self.0, &other.0)477 }478}479480impl Eq for ObjValue {}481impl Hash for ObjValue {482 fn hash<H: Hasher>(&self, hasher: &mut H) {483 hasher.write_usize(addr_of!(*self.0) as usize);484 }485}486487#[allow(clippy::module_name_repetitions)]488pub struct ObjValueBuilder {489 sup: Option<ObjValue>,490 map: GcHashMap<IStr, ObjMember>,491 assertions: Vec<TraceBox<dyn ObjectAssertion>>,492 next_field_index: FieldIndex,493}494impl ObjValueBuilder {495 pub fn new() -> Self {496 Self::with_capacity(0)497 }498 pub fn with_capacity(capacity: usize) -> Self {499 Self {500 sup: None,501 map: GcHashMap::with_capacity(capacity),502 assertions: Vec::new(),503 next_field_index: FieldIndex::default(),504 }505 }506 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {507 self.assertions.reserve_exact(capacity);508 self509 }510 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {511 self.sup = Some(super_obj);512 self513 }514515 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {516 self.assertions.push(assertion);517 self518 }519 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder<'_>> {520 let field_index = self.next_field_index;521 self.next_field_index = self.next_field_index.next();522 ObjMemberBuilder::new(ValueBuilder(self), name, field_index)523 }524525 pub fn build(self) -> ObjValue {526 ObjValue::new(self.sup, Cc::new(self.map), Cc::new(self.assertions))527 }528}529impl Default for ObjValueBuilder {530 fn default() -> Self {531 Self::with_capacity(0)532 }533}534535#[allow(clippy::module_name_repetitions)]536#[must_use = "value not added unless binding() was called"]537pub struct ObjMemberBuilder<Kind> {538 kind: Kind,539 name: IStr,540 add: bool,541 visibility: Visibility,542 original_index: FieldIndex,543 location: Option<ExprLocation>,544}545546#[allow(clippy::missing_const_for_fn)]547impl<Kind> ObjMemberBuilder<Kind> {548 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {549 Self {550 kind,551 name,552 original_index,553 add: false,554 visibility: Visibility::Normal,555 location: None,556 }557 }558559 pub const fn with_add(mut self, add: bool) -> Self {560 self.add = add;561 self562 }563 pub fn add(self) -> Self {564 self.with_add(true)565 }566 pub fn with_visibility(mut self, visibility: Visibility) -> Self {567 self.visibility = visibility;568 self569 }570 pub fn hide(self) -> Self {571 self.with_visibility(Visibility::Hidden)572 }573 pub fn with_location(mut self, location: ExprLocation) -> Self {574 self.location = Some(location);575 self576 }577 fn build_member(self, binding: MaybeUnbound) -> (Kind, IStr, ObjMember) {578 (579 self.kind,580 self.name,581 ObjMember {582 add: self.add,583 visibility: self.visibility,584 original_index: self.original_index,585 invoke: binding,586 location: self.location,587 },588 )589 }590}591592pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);593impl ObjMemberBuilder<ValueBuilder<'_>> {594 595 pub fn value_unchecked(self, value: Val) {596 let (receiver, name, member) =597 self.build_member(MaybeUnbound::Bound(Thunk::evaluated(value)));598 let entry = receiver.0.map.entry(name);599 entry.insert(member);600 }601602 pub fn value(self, value: Val) -> Result<()> {603 self.thunk(Thunk::evaluated(value))604 }605 pub fn thunk(self, value: Thunk<Val>) -> Result<()> {606 self.binding(MaybeUnbound::Bound(value))607 }608 pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) -> Result<()> {609 self.binding(MaybeUnbound::Unbound(Cc::new(bindable)))610 }611 pub fn binding(self, binding: MaybeUnbound) -> Result<()> {612 let (receiver, name, member) = self.build_member(binding);613 let location = member.location.clone();614 let old = receiver.0.map.insert(name.clone(), member);615 if old.is_some() {616 State::push(617 CallLocation(location.as_ref()),618 || format!("field <{}> initializtion", name.clone()),619 || throw!(DuplicateFieldName(name.clone())),620 )?;621 }622 Ok(())623 }624}625626pub struct ExtendBuilder<'v>(&'v mut ObjValue);627impl ObjMemberBuilder<ExtendBuilder<'_>> {628 pub fn value(self, value: Val) {629 self.binding(MaybeUnbound::Bound(Thunk::evaluated(value)));630 }631 pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) {632 self.binding(MaybeUnbound::Unbound(Cc::new(bindable)));633 }634 pub fn binding(self, binding: MaybeUnbound) {635 let (receiver, name, member) = self.build_member(binding);636 let new = receiver.0.clone();637 *receiver.0 = new.extend_with_raw_member(name, member);638 }639}