1use std::{2 cell::RefCell,3 fmt::Debug,4 hash::{Hash, Hasher},5};67use gcmodule::{Cc, Trace, Weak};8use jrsonnet_interner::IStr;9use jrsonnet_parser::{ExprLocation, Visibility};10use rustc_hash::FxHashMap;1112use crate::{13 cc_ptr_eq,14 error::{Error::*, LocError},15 function::CallLocation,16 gc::{GcHashMap, GcHashSet, TraceBox},17 operator::evaluate_add_op,18 push_frame, throw, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val,19};2021#[derive(Debug, Trace)]22pub struct ObjMember {23 pub add: bool,24 pub visibility: Visibility,25 pub invoke: LazyBinding,26 pub location: Option<ExprLocation>,27}2829pub trait ObjectAssertion: Trace {30 fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;31}323334type CacheKey = (IStr, WeakObjValue);3536#[derive(Trace)]37enum CacheValue {38 Cached(Val),39 NotFound,40 Pending,41 Errored(LocError),42}4344#[derive(Trace)]45#[force_tracking]46pub struct ObjValueInternals {47 super_obj: Option<ObjValue>,48 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,49 assertions_ran: RefCell<GcHashSet<ObjValue>>,50 this_obj: Option<ObjValue>,51 this_entries: Cc<GcHashMap<IStr, ObjMember>>,52 value_cache: RefCell<GcHashMap<CacheKey, CacheValue>>,53}5455#[derive(Clone, Trace)]56pub struct WeakObjValue(#[skip_trace] pub(crate) Weak<ObjValueInternals>);5758impl PartialEq for WeakObjValue {59 fn eq(&self, other: &Self) -> bool {60 weak_ptr_eq(self.0.clone(), other.0.clone())61 }62}6364impl Eq for WeakObjValue {}65impl Hash for WeakObjValue {66 fn hash<H: Hasher>(&self, hasher: &mut H) {67 hasher.write_usize(weak_raw(self.0.clone()) as usize)68 }69}7071#[derive(Clone, Trace)]72pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);73impl Debug for ObjValue {74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {75 if let Some(super_obj) = self.0.super_obj.as_ref() {76 if f.alternate() {77 write!(f, "{:#?}", super_obj)?;78 } else {79 write!(f, "{:?}", super_obj)?;80 }81 write!(f, " + ")?;82 }83 let mut debug = f.debug_struct("ObjValue");84 for (name, member) in self.0.this_entries.iter() {85 debug.field(name, member);86 }87 debug.finish_non_exhaustive()88 }89}9091impl ObjValue {92 pub fn new(93 super_obj: Option<Self>,94 this_entries: Cc<GcHashMap<IStr, ObjMember>>,95 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,96 ) -> Self {97 Self(Cc::new(ObjValueInternals {98 super_obj,99 assertions,100 assertions_ran: RefCell::new(GcHashSet::new()),101 this_obj: None,102 this_entries,103 value_cache: RefCell::new(GcHashMap::new()),104 }))105 }106 pub fn new_empty() -> Self {107 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))108 }109 pub fn extend_from(&self, super_obj: Self) -> Self {110 match &self.0.super_obj {111 None => Self::new(112 Some(super_obj),113 self.0.this_entries.clone(),114 self.0.assertions.clone(),115 ),116 Some(v) => Self::new(117 Some(v.extend_from(super_obj)),118 self.0.this_entries.clone(),119 self.0.assertions.clone(),120 ),121 }122 }123 pub fn with_this(&self, this_obj: Self) -> Self {124 Self(Cc::new(ObjValueInternals {125 super_obj: self.0.super_obj.clone(),126 assertions: self.0.assertions.clone(),127 assertions_ran: RefCell::new(GcHashSet::new()),128 this_obj: Some(this_obj),129 this_entries: self.0.this_entries.clone(),130 value_cache: RefCell::new(GcHashMap::new()),131 }))132 }133134 pub fn is_empty(&self) -> bool {135 if !self.0.this_entries.is_empty() {136 return false;137 }138 self.0139 .super_obj140 .as_ref()141 .map(|s| s.is_empty())142 .unwrap_or(true)143 }144145 146 pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &ObjMember) -> bool) -> bool {147 if let Some(s) = &self.0.super_obj {148 if s.enum_fields(handler) {149 return true;150 }151 }152 for (name, member) in self.0.this_entries.iter() {153 if handler(name, member) {154 return true;155 }156 }157 false158 }159160 pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {161 let mut out = FxHashMap::default();162 self.enum_fields(&mut |name, member| {163 match member.visibility {164 Visibility::Normal => {165 let entry = out.entry(name.to_owned());166 entry.or_insert(true);167 }168 Visibility::Hidden => {169 out.insert(name.to_owned(), false);170 }171 Visibility::Unhide => {172 out.insert(name.to_owned(), true);173 }174 };175 false176 });177 out178 }179 pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {180 let mut fields: Vec<_> = self181 .fields_visibility()182 .into_iter()183 .filter(|(_k, v)| include_hidden || *v)184 .map(|(k, _)| k)185 .collect();186 fields.sort_unstable();187 fields188 }189 pub fn fields(&self) -> Vec<IStr> {190 self.fields_ex(false)191 }192193 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {194 if let Some(m) = self.0.this_entries.get(&name) {195 Some(match &m.visibility {196 Visibility::Normal => self197 .0198 .super_obj199 .as_ref()200 .and_then(|super_obj| super_obj.field_visibility(name))201 .unwrap_or(Visibility::Normal),202 v => *v,203 })204 } else if let Some(super_obj) = &self.0.super_obj {205 super_obj.field_visibility(name)206 } else {207 None208 }209 }210211 fn has_field_include_hidden(&self, name: IStr) -> bool {212 if self.0.this_entries.contains_key(&name) {213 true214 } else if let Some(super_obj) = &self.0.super_obj {215 super_obj.has_field_include_hidden(name)216 } else {217 false218 }219 }220221 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {222 if include_hidden {223 self.has_field_include_hidden(name)224 } else {225 self.has_field(name)226 }227 }228 pub fn has_field(&self, name: IStr) -> bool {229 self.field_visibility(name)230 .map(|v| v.is_visible())231 .unwrap_or(false)232 }233234 pub fn get(&self, key: IStr) -> Result<Option<Val>> {235 self.run_assertions()?;236 self.get_raw(key, self.0.this_obj.as_ref())237 }238239 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {240 let mut new = GcHashMap::with_capacity(1);241 new.insert(key, value);242 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))243 }244245 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {246 let real_this = real_this.unwrap_or(self);247 let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));248249 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {250 return Ok(match v {251 CacheValue::Cached(v) => Some(v.clone()),252 CacheValue::NotFound => None,253 CacheValue::Pending => throw!(InfiniteRecursionDetected),254 CacheValue::Errored(e) => return Err(e.clone()),255 });256 }257 self.0258 .value_cache259 .borrow_mut()260 .insert(cache_key.clone(), CacheValue::Pending);261 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {262 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),263 (Some(k), Some(s)) => {264 let our = self.evaluate_this(k, real_this)?;265 if k.add {266 s.get_raw(key, Some(real_this))?267 .map_or(Ok(Some(our.clone())), |v| {268 Ok(Some(evaluate_add_op(&v, &our)?))269 })270 } else {271 Ok(Some(our))272 }273 }274 (None, Some(s)) => s.get_raw(key, Some(real_this)),275 (None, None) => Ok(None),276 };277 let value = match value {278 Ok(v) => v,279 Err(e) => {280 self.0281 .value_cache282 .borrow_mut()283 .insert(cache_key, CacheValue::Errored(e.clone()));284 return Err(e);285 }286 };287 self.0.value_cache.borrow_mut().insert(288 cache_key,289 match &value {290 Some(v) => CacheValue::Cached(v.clone()),291 None => CacheValue::NotFound,292 },293 );294 Ok(value)295 }296 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {297 v.invoke298 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?299 .evaluate()300 }301302 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {303 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {304 for assertion in self.0.assertions.iter() {305 if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {306 self.0.assertions_ran.borrow_mut().remove(real_this);307 return Err(e);308 }309 }310 if let Some(super_obj) = &self.0.super_obj {311 super_obj.run_assertions_raw(real_this)?;312 }313 }314 Ok(())315 }316 pub fn run_assertions(&self) -> Result<()> {317 self.run_assertions_raw(self)318 }319320 pub fn ptr_eq(a: &Self, b: &Self) -> bool {321 cc_ptr_eq(&a.0, &b.0)322 }323}324325impl PartialEq for ObjValue {326 fn eq(&self, other: &Self) -> bool {327 cc_ptr_eq(&self.0, &other.0)328 }329}330331impl Eq for ObjValue {}332impl Hash for ObjValue {333 fn hash<H: Hasher>(&self, hasher: &mut H) {334 hasher.write_usize(&*self.0 as *const _ as usize)335 }336}337338pub struct ObjValueBuilder {339 super_obj: Option<ObjValue>,340 map: GcHashMap<IStr, ObjMember>,341 assertions: Vec<TraceBox<dyn ObjectAssertion>>,342}343impl ObjValueBuilder {344 pub fn new() -> Self {345 Self::with_capacity(0)346 }347 pub fn with_capacity(capacity: usize) -> Self {348 Self {349 super_obj: None,350 map: GcHashMap::with_capacity(capacity),351 assertions: Vec::new(),352 }353 }354 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {355 self.assertions.reserve_exact(capacity);356 self357 }358 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {359 self.super_obj = Some(super_obj);360 self361 }362363 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {364 self.assertions.push(assertion);365 self366 }367 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder {368 ObjMemberBuilder {369 value: self,370 name,371 add: false,372 visibility: Visibility::Normal,373 location: None,374 }375 }376377 pub fn build(self) -> ObjValue {378 ObjValue::new(self.super_obj, Cc::new(self.map), Cc::new(self.assertions))379 }380}381impl Default for ObjValueBuilder {382 fn default() -> Self {383 Self::with_capacity(0)384 }385}386387#[must_use = "value not added unless binding() was called"]388pub struct ObjMemberBuilder<'v> {389 value: &'v mut ObjValueBuilder,390 name: IStr,391 add: bool,392 visibility: Visibility,393 location: Option<ExprLocation>,394}395396#[allow(clippy::missing_const_for_fn)]397impl<'v> ObjMemberBuilder<'v> {398 pub const fn with_add(mut self, add: bool) -> Self {399 self.add = add;400 self401 }402 pub fn add(self) -> Self {403 self.with_add(true)404 }405 pub fn with_visibility(mut self, visibility: Visibility) -> Self {406 self.visibility = visibility;407 self408 }409 pub fn hide(self) -> Self {410 self.with_visibility(Visibility::Hidden)411 }412 pub fn with_location(mut self, location: ExprLocation) -> Self {413 self.location = Some(location);414 self415 }416 pub fn value(self, value: Val) -> Result<()> {417 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))418 }419 pub fn bindable(self, bindable: TraceBox<dyn Bindable>) -> Result<()> {420 self.binding(LazyBinding::Bindable(Cc::new(bindable)))421 }422 pub fn binding(self, binding: LazyBinding) -> Result<()> {423 let old = self.value.map.insert(424 self.name.clone(),425 ObjMember {426 add: self.add,427 visibility: self.visibility,428 invoke: binding,429 location: self.location.clone(),430 },431 );432 if old.is_some() {433 push_frame(434 CallLocation(self.location.as_ref()),435 || format!("field <{}> initializtion", self.name.clone()),436 || throw!(DuplicateFieldName(self.name.clone())),437 )?438 }439 Ok(())440 }441}