1use std::{2 cell::RefCell,3 fmt::Debug,4 hash::{Hash, Hasher},5 ptr::addr_of,6};78use gcmodule::{Cc, Trace, Weak};9use jrsonnet_interner::IStr;10use jrsonnet_parser::{ExprLocation, Visibility};11use rustc_hash::FxHashMap;1213use crate::{14 cc_ptr_eq,15 error::{Error::*, LocError},16 function::CallLocation,17 gc::{GcHashMap, GcHashSet, TraceBox},18 operator::evaluate_add_op,19 throw, weak_ptr_eq, weak_raw, LazyBinding, Result, State, Thunk, Unbound, Val,20};2122#[cfg(not(feature = "exp-preserve-order"))]23mod ordering {24 #![allow(25 26 clippy::unused_self,27 )]2829 use gcmodule::Trace;3031 #[derive(Clone, Copy, Default, Debug, Trace)]32 pub struct FieldIndex;33 impl FieldIndex {34 pub const fn next(self) -> Self {35 Self36 }37 }3839 #[derive(Clone, Copy, Default, Debug, Trace)]40 pub struct SuperDepth;41 impl SuperDepth {42 pub const fn deeper(self) -> Self {43 Self44 }45 }4647 #[derive(Clone, Copy)]48 pub struct FieldSortKey;49 impl FieldSortKey {50 pub const fn new(_: SuperDepth, _: FieldIndex) -> Self {51 Self52 }53 }54}5556#[cfg(feature = "exp-preserve-order")]57mod ordering {58 use std::cmp::Reverse;5960 use gcmodule::Trace;6162 #[derive(Clone, Copy, Default, Debug, Trace, PartialEq, Eq, PartialOrd, Ord)]63 pub struct FieldIndex(u32);64 impl FieldIndex {65 pub fn next(self) -> Self {66 Self(self.0 + 1)67 }68 }6970 #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Debug)]71 pub struct SuperDepth(u32);72 impl SuperDepth {73 pub fn deeper(self) -> Self {74 Self(self.0 + 1)75 }76 }7778 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]79 pub struct FieldSortKey(Reverse<SuperDepth>, FieldIndex);80 impl FieldSortKey {81 pub fn new(depth: SuperDepth, index: FieldIndex) -> Self {82 Self(Reverse(depth), index)83 }84 pub fn collide(self, other: Self) -> Self {85 if self.0 .0 > other.0 .0 {86 self87 } else if self.0 .0 < other.0 .0 {88 other89 } else {90 unreachable!("object can't have two fields with same name")91 }92 }93 }94}9596use ordering::*;9798#[allow(clippy::module_name_repetitions)]99#[derive(Debug, Trace)]100pub struct ObjMember {101 pub add: bool,102 pub visibility: Visibility,103 original_index: FieldIndex,104 pub invoke: LazyBinding,105 pub location: Option<ExprLocation>,106}107108pub trait ObjectAssertion: Trace {109 fn run(&self, s: State, super_obj: Option<ObjValue>, this: Option<ObjValue>) -> Result<()>;110}111112113type CacheKey = (IStr, WeakObjValue);114115#[derive(Trace)]116enum CacheValue {117 Cached(Val),118 NotFound,119 Pending,120 Errored(LocError),121}122123#[allow(clippy::module_name_repetitions)]124#[derive(Trace)]125#[force_tracking]126pub struct ObjValueInternals {127 sup: Option<ObjValue>,128 this: Option<ObjValue>,129130 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,131 assertions_ran: RefCell<GcHashSet<ObjValue>>,132 this_entries: Cc<GcHashMap<IStr, ObjMember>>,133 value_cache: RefCell<GcHashMap<CacheKey, CacheValue>>,134}135136#[derive(Clone, Trace)]137pub struct WeakObjValue(#[skip_trace] pub(crate) Weak<ObjValueInternals>);138139impl PartialEq for WeakObjValue {140 fn eq(&self, other: &Self) -> bool {141 weak_ptr_eq(self.0.clone(), other.0.clone())142 }143}144145impl Eq for WeakObjValue {}146impl Hash for WeakObjValue {147 fn hash<H: Hasher>(&self, hasher: &mut H) {148 hasher.write_usize(weak_raw(self.0.clone()) as usize);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 pub(crate) fn enum_fields(243 &self,244 depth: SuperDepth,245 handler: &mut impl FnMut(SuperDepth, &IStr, &ObjMember) -> bool,246 ) -> bool {247 if let Some(s) = &self.0.sup {248 if s.enum_fields(depth.deeper(), handler) {249 return true;250 }251 }252 for (name, member) in self.0.this_entries.iter() {253 if handler(depth, name, member) {254 return true;255 }256 }257 false258 }259260 pub fn fields_visibility(&self) -> FxHashMap<IStr, (bool, FieldSortKey)> {261 let mut out = FxHashMap::default();262 self.enum_fields(SuperDepth::default(), &mut |depth, name, member| {263 let new_sort_key = FieldSortKey::new(depth, member.original_index);264 let entry = out.entry(name.clone());265 let (visible, _) = entry.or_insert((true, new_sort_key));266 match member.visibility {267 Visibility::Normal => {}268 Visibility::Hidden => {269 *visible = false;270 }271 Visibility::Unhide => {272 *visible = true;273 }274 };275 false276 });277 out278 }279 pub fn fields_ex(280 &self,281 include_hidden: bool,282 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,283 ) -> Vec<IStr> {284 #[cfg(feature = "exp-preserve-order")]285 if preserve_order {286 let (mut fields, mut keys): (Vec<_>, Vec<_>) = self287 .fields_visibility()288 .into_iter()289 .filter(|(_, (visible, _))| include_hidden || *visible)290 .enumerate()291 .map(|(idx, (k, (_, sk)))| (k, (sk, idx)))292 .unzip();293 keys.sort_unstable_by_key(|v| v.0);294 295 for i in 0..fields.len() {296 let x = fields[i].clone();297 let mut j = i;298 loop {299 let k = keys[j].1;300 keys[j].1 = j;301 if k == i {302 break;303 }304 fields[j] = fields[k].clone();305 j = k306 }307 fields[j] = x;308 }309 return fields;310 }311312 let mut fields: Vec<_> = self313 .fields_visibility()314 .into_iter()315 .filter(|(_, (visible, _))| include_hidden || *visible)316 .map(|(k, _)| k)317 .collect();318 fields.sort_unstable();319 fields320 }321 pub fn fields(&self, #[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Vec<IStr> {322 self.fields_ex(323 false,324 #[cfg(feature = "exp-preserve-order")]325 preserve_order,326 )327 }328329 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {330 if let Some(m) = self.0.this_entries.get(&name) {331 Some(match &m.visibility {332 Visibility::Normal => self333 .0334 .sup335 .as_ref()336 .and_then(|super_obj| super_obj.field_visibility(name))337 .unwrap_or(Visibility::Normal),338 v => *v,339 })340 } else if let Some(super_obj) = &self.0.sup {341 super_obj.field_visibility(name)342 } else {343 None344 }345 }346347 fn has_field_include_hidden(&self, name: IStr) -> bool {348 if self.0.this_entries.contains_key(&name) {349 true350 } else if let Some(super_obj) = &self.0.sup {351 super_obj.has_field_include_hidden(name)352 } else {353 false354 }355 }356357 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {358 if include_hidden {359 self.has_field_include_hidden(name)360 } else {361 self.has_field(name)362 }363 }364 pub fn has_field(&self, name: IStr) -> bool {365 self.field_visibility(name)366 .map_or(false, |v| v.is_visible())367 }368369 pub fn get(&self, s: State, key: IStr) -> Result<Option<Val>> {370 self.run_assertions(s.clone())?;371 self.get_raw(s, key, self.0.this.clone().unwrap_or_else(|| self.clone()))372 }373374 375376 fn get_raw(&self, s: State, key: IStr, real_this: Self) -> Result<Option<Val>> {377 let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));378379 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {380 return Ok(match v {381 CacheValue::Cached(v) => Some(v.clone()),382 CacheValue::NotFound => None,383 CacheValue::Pending => throw!(InfiniteRecursionDetected),384 CacheValue::Errored(e) => return Err(e.clone()),385 });386 }387 self.0388 .value_cache389 .borrow_mut()390 .insert(cache_key.clone(), CacheValue::Pending);391 let fill_error = |e: LocError| {392 self.0393 .value_cache394 .borrow_mut()395 .insert(cache_key.clone(), CacheValue::Errored(e.clone()));396 e397 };398 let value = match (self.0.this_entries.get(&key), &self.0.sup) {399 (Some(k), None) => Ok(Some(400 self.evaluate_this(s, k, real_this).map_err(fill_error)?,401 )),402 (Some(k), Some(super_obj)) => {403 let our = self404 .evaluate_this(s.clone(), k, real_this.clone())405 .map_err(fill_error)?;406 if k.add {407 super_obj408 .get_raw(s.clone(), key, real_this)409 .map_err(fill_error)?410 .map_or(Ok(Some(our.clone())), |v| {411 Ok(Some(evaluate_add_op(s.clone(), &v, &our)?))412 })413 } else {414 Ok(Some(our))415 }416 }417 (None, Some(super_obj)) => super_obj.get_raw(s, key, real_this),418 (None, None) => Ok(None),419 }420 .map_err(fill_error)?;421 self.0.value_cache.borrow_mut().insert(422 cache_key,423 match &value {424 Some(v) => CacheValue::Cached(v.clone()),425 None => CacheValue::NotFound,426 },427 );428 Ok(value)429 }430 fn evaluate_this(&self, s: State, v: &ObjMember, real_this: Self) -> Result<Val> {431 v.invoke432 .evaluate(s.clone(), self.0.sup.clone(), Some(real_this))?433 .evaluate(s)434 }435436 fn run_assertions_raw(&self, s: State, real_this: &Self) -> Result<()> {437 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {438 for assertion in self.0.assertions.iter() {439 if let Err(e) =440 assertion.run(s.clone(), self.0.sup.clone(), Some(real_this.clone()))441 {442 self.0.assertions_ran.borrow_mut().remove(real_this);443 return Err(e);444 }445 }446 if let Some(super_obj) = &self.0.sup {447 super_obj.run_assertions_raw(s, real_this)?;448 }449 }450 Ok(())451 }452 pub fn run_assertions(&self, s: State) -> Result<()> {453 self.run_assertions_raw(s, self)454 }455456 pub fn ptr_eq(a: &Self, b: &Self) -> bool {457 cc_ptr_eq(&a.0, &b.0)458 }459 pub fn downgrade(self) -> WeakObjValue {460 WeakObjValue(self.0.downgrade())461 }462}463464impl PartialEq for ObjValue {465 fn eq(&self, other: &Self) -> bool {466 cc_ptr_eq(&self.0, &other.0)467 }468}469470impl Eq for ObjValue {}471impl Hash for ObjValue {472 fn hash<H: Hasher>(&self, hasher: &mut H) {473 hasher.write_usize(addr_of!(*self.0) as usize);474 }475}476477#[allow(clippy::module_name_repetitions)]478pub struct ObjValueBuilder {479 sup: Option<ObjValue>,480 map: GcHashMap<IStr, ObjMember>,481 assertions: Vec<TraceBox<dyn ObjectAssertion>>,482 next_field_index: FieldIndex,483}484impl ObjValueBuilder {485 pub fn new() -> Self {486 Self::with_capacity(0)487 }488 pub fn with_capacity(capacity: usize) -> Self {489 Self {490 sup: None,491 map: GcHashMap::with_capacity(capacity),492 assertions: Vec::new(),493 next_field_index: FieldIndex::default(),494 }495 }496 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {497 self.assertions.reserve_exact(capacity);498 self499 }500 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {501 self.sup = Some(super_obj);502 self503 }504505 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {506 self.assertions.push(assertion);507 self508 }509 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder<ValueBuilder> {510 let field_index = self.next_field_index;511 self.next_field_index = self.next_field_index.next();512 ObjMemberBuilder::new(ValueBuilder(self), name, field_index)513 }514515 pub fn build(self) -> ObjValue {516 ObjValue::new(self.sup, Cc::new(self.map), Cc::new(self.assertions))517 }518}519impl Default for ObjValueBuilder {520 fn default() -> Self {521 Self::with_capacity(0)522 }523}524525#[allow(clippy::module_name_repetitions)]526#[must_use = "value not added unless binding() was called"]527pub struct ObjMemberBuilder<Kind> {528 kind: Kind,529 name: IStr,530 add: bool,531 visibility: Visibility,532 original_index: FieldIndex,533 location: Option<ExprLocation>,534}535536#[allow(clippy::missing_const_for_fn)]537impl<Kind> ObjMemberBuilder<Kind> {538 pub(crate) fn new(kind: Kind, name: IStr, original_index: FieldIndex) -> Self {539 Self {540 kind,541 name,542 original_index,543 add: false,544 visibility: Visibility::Normal,545 location: None,546 }547 }548549 pub const fn with_add(mut self, add: bool) -> Self {550 self.add = add;551 self552 }553 pub fn add(self) -> Self {554 self.with_add(true)555 }556 pub fn with_visibility(mut self, visibility: Visibility) -> Self {557 self.visibility = visibility;558 self559 }560 pub fn hide(self) -> Self {561 self.with_visibility(Visibility::Hidden)562 }563 pub fn with_location(mut self, location: ExprLocation) -> Self {564 self.location = Some(location);565 self566 }567 fn build_member(self, binding: LazyBinding) -> (Kind, IStr, ObjMember) {568 (569 self.kind,570 self.name,571 ObjMember {572 add: self.add,573 visibility: self.visibility,574 original_index: self.original_index,575 invoke: binding,576 location: self.location,577 },578 )579 }580}581582pub struct ValueBuilder<'v>(&'v mut ObjValueBuilder);583impl<'v> ObjMemberBuilder<ValueBuilder<'v>> {584 pub fn value(self, s: State, value: Val) -> Result<()> {585 self.binding(s, LazyBinding::Bound(Thunk::evaluated(value)))586 }587 pub fn bindable(588 self,589 s: State,590 bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>,591 ) -> Result<()> {592 self.binding(s, LazyBinding::Bindable(Cc::new(bindable)))593 }594 pub fn binding(self, s: State, binding: LazyBinding) -> Result<()> {595 let (receiver, name, member) = self.build_member(binding);596 let location = member.location.clone();597 let old = receiver.0.map.insert(name.clone(), member);598 if old.is_some() {599 s.push(600 CallLocation(location.as_ref()),601 || format!("field <{}> initializtion", name.clone()),602 || throw!(DuplicateFieldName(name.clone())),603 )?;604 }605 Ok(())606 }607}608609pub struct ExtendBuilder<'v>(&'v mut ObjValue);610impl<'v> ObjMemberBuilder<ExtendBuilder<'v>> {611 pub fn value(self, value: Val) {612 self.binding(LazyBinding::Bound(Thunk::evaluated(value)));613 }614 pub fn bindable(self, bindable: TraceBox<dyn Unbound<Bound = Thunk<Val>>>) {615 self.binding(LazyBinding::Bindable(Cc::new(bindable)));616 }617 pub fn binding(self, binding: LazyBinding) {618 let (receiver, name, member) = self.build_member(binding);619 let new = receiver.0.clone();620 *receiver.0 = new.extend_with_raw_member(name, member);621 }622}