1use crate::error::LocError;2use crate::function::CallLocation;3use crate::gc::{GcHashMap, GcHashSet, TraceBox};4use crate::operator::evaluate_add_op;5use crate::push_frame;6use crate::{7 cc_ptr_eq, error::Error::*, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal,8 Result, Val,9};10use gcmodule::{Cc, Trace, Weak};11use jrsonnet_interner::IStr;12use jrsonnet_parser::{ExprLocation, Visibility};13use rustc_hash::FxHashMap;14use std::cell::RefCell;15use std::fmt::Debug;16use std::hash::{Hash, Hasher};1718#[derive(Debug, Trace)]19pub struct ObjMember {20 pub add: bool,21 pub visibility: Visibility,22 pub invoke: LazyBinding,23 pub location: Option<ExprLocation>,24}2526pub trait ObjectAssertion: Trace {27 fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;28}293031type CacheKey = (IStr, WeakObjValue);3233#[derive(Trace)]34enum CacheValue {35 Cached(Val),36 NotFound,37 Pending,38 Errored(LocError),39}4041#[derive(Trace)]42#[force_tracking]43pub struct ObjValueInternals {44 super_obj: Option<ObjValue>,45 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,46 assertions_ran: RefCell<GcHashSet<ObjValue>>,47 this_obj: Option<ObjValue>,48 this_entries: Cc<GcHashMap<IStr, ObjMember>>,49 value_cache: RefCell<GcHashMap<CacheKey, CacheValue>>,50}5152#[derive(Clone, Trace)]53pub struct WeakObjValue(#[skip_trace] pub(crate) Weak<ObjValueInternals>);5455impl PartialEq for WeakObjValue {56 fn eq(&self, other: &Self) -> bool {57 weak_ptr_eq(self.0.clone(), other.0.clone())58 }59}6061impl Eq for WeakObjValue {}62impl Hash for WeakObjValue {63 fn hash<H: Hasher>(&self, hasher: &mut H) {64 hasher.write_usize(weak_raw(self.0.clone()) as usize)65 }66}6768#[derive(Clone, Trace)]69pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);70impl Debug for ObjValue {71 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {72 if let Some(super_obj) = self.0.super_obj.as_ref() {73 if f.alternate() {74 write!(f, "{:#?}", super_obj)?;75 } else {76 write!(f, "{:?}", super_obj)?;77 }78 write!(f, " + ")?;79 }80 let mut debug = f.debug_struct("ObjValue");81 for (name, member) in self.0.this_entries.iter() {82 debug.field(name, member);83 }84 debug.finish_non_exhaustive()85 }86}8788impl ObjValue {89 pub fn new(90 super_obj: Option<Self>,91 this_entries: Cc<GcHashMap<IStr, ObjMember>>,92 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,93 ) -> Self {94 Self(Cc::new(ObjValueInternals {95 super_obj,96 assertions,97 assertions_ran: RefCell::new(GcHashSet::new()),98 this_obj: None,99 this_entries,100 value_cache: RefCell::new(GcHashMap::new()),101 }))102 }103 pub fn new_empty() -> Self {104 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))105 }106 pub fn extend_from(&self, super_obj: Self) -> Self {107 match &self.0.super_obj {108 None => Self::new(109 Some(super_obj),110 self.0.this_entries.clone(),111 self.0.assertions.clone(),112 ),113 Some(v) => Self::new(114 Some(v.extend_from(super_obj)),115 self.0.this_entries.clone(),116 self.0.assertions.clone(),117 ),118 }119 }120 pub fn with_this(&self, this_obj: Self) -> Self {121 Self(Cc::new(ObjValueInternals {122 super_obj: self.0.super_obj.clone(),123 assertions: self.0.assertions.clone(),124 assertions_ran: RefCell::new(GcHashSet::new()),125 this_obj: Some(this_obj),126 this_entries: self.0.this_entries.clone(),127 value_cache: RefCell::new(GcHashMap::new()),128 }))129 }130131 pub fn is_empty(&self) -> bool {132 if !self.0.this_entries.is_empty() {133 return false;134 }135 self.0136 .super_obj137 .as_ref()138 .map(|s| s.is_empty())139 .unwrap_or(true)140 }141142 143 pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &ObjMember) -> bool) -> bool {144 if let Some(s) = &self.0.super_obj {145 if s.enum_fields(handler) {146 return true;147 }148 }149 for (name, member) in self.0.this_entries.iter() {150 if handler(name, member) {151 return true;152 }153 }154 false155 }156157 pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {158 let mut out = FxHashMap::default();159 self.enum_fields(&mut |name, member| {160 match member.visibility {161 Visibility::Normal => {162 let entry = out.entry(name.to_owned());163 entry.or_insert(true);164 }165 Visibility::Hidden => {166 out.insert(name.to_owned(), false);167 }168 Visibility::Unhide => {169 out.insert(name.to_owned(), true);170 }171 };172 false173 });174 out175 }176 pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {177 let mut fields: Vec<_> = self178 .fields_visibility()179 .into_iter()180 .filter(|(_k, v)| include_hidden || *v)181 .map(|(k, _)| k)182 .collect();183 fields.sort_unstable();184 fields185 }186 pub fn fields(&self) -> Vec<IStr> {187 self.fields_ex(false)188 }189190 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {191 if let Some(m) = self.0.this_entries.get(&name) {192 Some(match &m.visibility {193 Visibility::Normal => self194 .0195 .super_obj196 .as_ref()197 .and_then(|super_obj| super_obj.field_visibility(name))198 .unwrap_or(Visibility::Normal),199 v => *v,200 })201 } else if let Some(super_obj) = &self.0.super_obj {202 super_obj.field_visibility(name)203 } else {204 None205 }206 }207208 fn has_field_include_hidden(&self, name: IStr) -> bool {209 if self.0.this_entries.contains_key(&name) {210 true211 } else if let Some(super_obj) = &self.0.super_obj {212 super_obj.has_field_include_hidden(name)213 } else {214 false215 }216 }217218 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {219 if include_hidden {220 self.has_field_include_hidden(name)221 } else {222 self.has_field(name)223 }224 }225 pub fn has_field(&self, name: IStr) -> bool {226 self.field_visibility(name)227 .map(|v| v.is_visible())228 .unwrap_or(false)229 }230231 pub fn get(&self, key: IStr) -> Result<Option<Val>> {232 self.run_assertions()?;233 self.get_raw(key, self.0.this_obj.as_ref())234 }235236 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {237 let mut new = GcHashMap::with_capacity(1);238 new.insert(key, value);239 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))240 }241242 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {243 let real_this = real_this.unwrap_or(self);244 let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));245246 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {247 return Ok(match v {248 CacheValue::Cached(v) => Some(v.clone()),249 CacheValue::NotFound => None,250 CacheValue::Pending => throw!(InfiniteRecursionDetected),251 CacheValue::Errored(e) => return Err(e.clone()),252 });253 }254 self.0255 .value_cache256 .borrow_mut()257 .insert(cache_key.clone(), CacheValue::Pending);258 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {259 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),260 (Some(k), Some(s)) => {261 let our = self.evaluate_this(k, real_this)?;262 if k.add {263 s.get_raw(key, Some(real_this))?264 .map_or(Ok(Some(our.clone())), |v| {265 Ok(Some(evaluate_add_op(&v, &our)?))266 })267 } else {268 Ok(Some(our))269 }270 }271 (None, Some(s)) => s.get_raw(key, Some(real_this)),272 (None, None) => Ok(None),273 };274 let value = match value {275 Ok(v) => v,276 Err(e) => {277 self.0278 .value_cache279 .borrow_mut()280 .insert(cache_key, CacheValue::Errored(e.clone()));281 return Err(e);282 }283 };284 self.0.value_cache.borrow_mut().insert(285 cache_key,286 match &value {287 Some(v) => CacheValue::Cached(v.clone()),288 None => CacheValue::NotFound,289 },290 );291 Ok(value)292 }293 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {294 v.invoke295 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?296 .evaluate()297 }298299 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {300 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {301 for assertion in self.0.assertions.iter() {302 if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {303 self.0.assertions_ran.borrow_mut().remove(real_this);304 return Err(e);305 }306 }307 if let Some(super_obj) = &self.0.super_obj {308 super_obj.run_assertions_raw(real_this)?;309 }310 }311 Ok(())312 }313 pub fn run_assertions(&self) -> Result<()> {314 self.run_assertions_raw(self)315 }316317 pub fn ptr_eq(a: &Self, b: &Self) -> bool {318 cc_ptr_eq(&a.0, &b.0)319 }320}321322impl PartialEq for ObjValue {323 fn eq(&self, other: &Self) -> bool {324 cc_ptr_eq(&self.0, &other.0)325 }326}327328impl Eq for ObjValue {}329impl Hash for ObjValue {330 fn hash<H: Hasher>(&self, hasher: &mut H) {331 hasher.write_usize(&*self.0 as *const _ as usize)332 }333}334335pub struct ObjValueBuilder {336 super_obj: Option<ObjValue>,337 map: GcHashMap<IStr, ObjMember>,338 assertions: Vec<TraceBox<dyn ObjectAssertion>>,339}340impl ObjValueBuilder {341 pub fn new() -> Self {342 Self::with_capacity(0)343 }344 pub fn with_capacity(capacity: usize) -> Self {345 Self {346 super_obj: None,347 map: GcHashMap::with_capacity(capacity),348 assertions: Vec::new(),349 }350 }351 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {352 self.assertions.reserve_exact(capacity);353 self354 }355 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {356 self.super_obj = Some(super_obj);357 self358 }359360 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {361 self.assertions.push(assertion);362 self363 }364 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder {365 ObjMemberBuilder {366 value: self,367 name,368 add: false,369 visibility: Visibility::Normal,370 location: None,371 }372 }373374 pub fn build(self) -> ObjValue {375 ObjValue::new(self.super_obj, Cc::new(self.map), Cc::new(self.assertions))376 }377}378impl Default for ObjValueBuilder {379 fn default() -> Self {380 Self::with_capacity(0)381 }382}383384#[must_use = "value not added unless binding() was called"]385pub struct ObjMemberBuilder<'v> {386 value: &'v mut ObjValueBuilder,387 name: IStr,388 add: bool,389 visibility: Visibility,390 location: Option<ExprLocation>,391}392393#[allow(clippy::missing_const_for_fn)]394impl<'v> ObjMemberBuilder<'v> {395 pub const fn with_add(mut self, add: bool) -> Self {396 self.add = add;397 self398 }399 pub fn add(self) -> Self {400 self.with_add(true)401 }402 pub fn with_visibility(mut self, visibility: Visibility) -> Self {403 self.visibility = visibility;404 self405 }406 pub fn hide(self) -> Self {407 self.with_visibility(Visibility::Hidden)408 }409 pub fn with_location(mut self, location: ExprLocation) -> Self {410 self.location = Some(location);411 self412 }413 pub fn value(self, value: Val) -> Result<()> {414 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))415 }416 pub fn bindable(self, bindable: TraceBox<dyn Bindable>) -> Result<()> {417 self.binding(LazyBinding::Bindable(Cc::new(bindable)))418 }419 pub fn binding(self, binding: LazyBinding) -> Result<()> {420 let old = self.value.map.insert(421 self.name.clone(),422 ObjMember {423 add: self.add,424 visibility: self.visibility,425 invoke: binding,426 location: self.location.clone(),427 },428 );429 if old.is_some() {430 push_frame(431 CallLocation(self.location.as_ref()),432 || format!("field <{}> initializtion", self.name.clone()),433 || throw!(DuplicateFieldName(self.name.clone())),434 )?435 }436 Ok(())437 }438}