1use crate::gc::{GcHashMap, GcHashSet, TraceBox};2use crate::operator::evaluate_add_op;3use crate::{cc_ptr_eq, weak_ptr_eq, weak_raw, Bindable, LazyBinding, LazyVal, Result, Val};4use gcmodule::{Cc, Trace, Weak};5use jrsonnet_interner::IStr;6use jrsonnet_parser::{ExprLocation, Visibility};7use rustc_hash::FxHashMap;8use std::cell::RefCell;9use std::fmt::Debug;10use std::hash::{Hash, Hasher};1112#[derive(Debug, Trace)]13pub struct ObjMember {14 pub add: bool,15 pub visibility: Visibility,16 pub invoke: LazyBinding,17 pub location: Option<ExprLocation>,18}1920pub trait ObjectAssertion: Trace {21 fn run(&self, this: Option<ObjValue>, super_obj: Option<ObjValue>) -> Result<()>;22}232425type CacheKey = (IStr, WeakObjValue);26#[derive(Trace)]27#[force_tracking]28pub struct ObjValueInternals {29 super_obj: Option<ObjValue>,30 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,31 assertions_ran: RefCell<GcHashSet<ObjValue>>,32 this_obj: Option<ObjValue>,33 this_entries: Cc<GcHashMap<IStr, ObjMember>>,34 value_cache: RefCell<GcHashMap<CacheKey, Option<Val>>>,35}3637#[derive(Clone, Trace)]38pub struct WeakObjValue(#[skip_trace] pub(crate) Weak<ObjValueInternals>);3940impl PartialEq for WeakObjValue {41 fn eq(&self, other: &Self) -> bool {42 weak_ptr_eq(self.0.clone(), other.0.clone())43 }44}4546impl Eq for WeakObjValue {}47impl Hash for WeakObjValue {48 fn hash<H: Hasher>(&self, hasher: &mut H) {49 hasher.write_usize(weak_raw(self.0.clone()) as usize)50 }51}5253#[derive(Clone, Trace)]54pub struct ObjValue(pub(crate) Cc<ObjValueInternals>);55impl Debug for ObjValue {56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {57 if let Some(super_obj) = self.0.super_obj.as_ref() {58 if f.alternate() {59 write!(f, "{:#?}", super_obj)?;60 } else {61 write!(f, "{:?}", super_obj)?;62 }63 write!(f, " + ")?;64 }65 let mut debug = f.debug_struct("ObjValue");66 for (name, member) in self.0.this_entries.iter() {67 debug.field(name, member);68 }69 debug.finish_non_exhaustive()70 }71}7273impl ObjValue {74 pub fn new(75 super_obj: Option<Self>,76 this_entries: Cc<GcHashMap<IStr, ObjMember>>,77 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,78 ) -> Self {79 Self(Cc::new(ObjValueInternals {80 super_obj,81 assertions,82 assertions_ran: RefCell::new(GcHashSet::new()),83 this_obj: None,84 this_entries,85 value_cache: RefCell::new(GcHashMap::new()),86 }))87 }88 pub fn new_empty() -> Self {89 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))90 }91 pub fn extend_from(&self, super_obj: Self) -> Self {92 match &self.0.super_obj {93 None => Self::new(94 Some(super_obj),95 self.0.this_entries.clone(),96 self.0.assertions.clone(),97 ),98 Some(v) => Self::new(99 Some(v.extend_from(super_obj)),100 self.0.this_entries.clone(),101 self.0.assertions.clone(),102 ),103 }104 }105 pub fn with_this(&self, this_obj: Self) -> Self {106 Self(Cc::new(ObjValueInternals {107 super_obj: self.0.super_obj.clone(),108 assertions: self.0.assertions.clone(),109 assertions_ran: RefCell::new(GcHashSet::new()),110 this_obj: Some(this_obj),111 this_entries: self.0.this_entries.clone(),112 value_cache: RefCell::new(GcHashMap::new()),113 }))114 }115116 pub fn is_empty(&self) -> bool {117 if !self.0.this_entries.is_empty() {118 return false;119 }120 self.0121 .super_obj122 .as_ref()123 .map(|s| s.is_empty())124 .unwrap_or(true)125 }126127 128 pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &ObjMember) -> bool) -> bool {129 if let Some(s) = &self.0.super_obj {130 if s.enum_fields(handler) {131 return true;132 }133 }134 for (name, member) in self.0.this_entries.iter() {135 if handler(name, member) {136 return true;137 }138 }139 false140 }141142 pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {143 let mut out = FxHashMap::default();144 self.enum_fields(&mut |name, member| {145 match member.visibility {146 Visibility::Normal => {147 let entry = out.entry(name.to_owned());148 entry.or_insert(true);149 }150 Visibility::Hidden => {151 out.insert(name.to_owned(), false);152 }153 Visibility::Unhide => {154 out.insert(name.to_owned(), true);155 }156 };157 false158 });159 out160 }161 pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {162 let mut fields: Vec<_> = self163 .fields_visibility()164 .into_iter()165 .filter(|(_k, v)| include_hidden || *v)166 .map(|(k, _)| k)167 .collect();168 fields.sort_unstable();169 fields170 }171 pub fn fields(&self) -> Vec<IStr> {172 self.fields_ex(false)173 }174175 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {176 if let Some(m) = self.0.this_entries.get(&name) {177 Some(match &m.visibility {178 Visibility::Normal => self179 .0180 .super_obj181 .as_ref()182 .and_then(|super_obj| super_obj.field_visibility(name))183 .unwrap_or(Visibility::Normal),184 v => *v,185 })186 } else if let Some(super_obj) = &self.0.super_obj {187 super_obj.field_visibility(name)188 } else {189 None190 }191 }192193 fn has_field_include_hidden(&self, name: IStr) -> bool {194 if self.0.this_entries.contains_key(&name) {195 true196 } else if let Some(super_obj) = &self.0.super_obj {197 super_obj.has_field_include_hidden(name)198 } else {199 false200 }201 }202203 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {204 if include_hidden {205 self.has_field_include_hidden(name)206 } else {207 self.has_field(name)208 }209 }210 pub fn has_field(&self, name: IStr) -> bool {211 self.field_visibility(name)212 .map(|v| v.is_visible())213 .unwrap_or(false)214 }215216 pub fn get(&self, key: IStr) -> Result<Option<Val>> {217 self.run_assertions()?;218 self.get_raw(key, self.0.this_obj.as_ref())219 }220221 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {222 let mut new = GcHashMap::with_capacity(1);223 new.insert(key, value);224 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))225 }226227 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {228 let real_this = real_this.unwrap_or(self);229 let cache_key = (key.clone(), WeakObjValue(real_this.0.downgrade()));230231 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {232 return Ok(v.clone());233 }234 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {235 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),236 (Some(k), Some(s)) => {237 let our = self.evaluate_this(k, real_this)?;238 if k.add {239 s.get_raw(key, Some(real_this))?240 .map_or(Ok(Some(our.clone())), |v| {241 Ok(Some(evaluate_add_op(&v, &our)?))242 })243 } else {244 Ok(Some(our))245 }246 }247 (None, Some(s)) => s.get_raw(key, Some(real_this)),248 (None, None) => Ok(None),249 }?;250 self.0251 .value_cache252 .borrow_mut()253 .insert(cache_key, value.clone());254 Ok(value)255 }256 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {257 v.invoke258 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?259 .evaluate()260 }261262 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {263 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {264 for assertion in self.0.assertions.iter() {265 if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {266 self.0.assertions_ran.borrow_mut().remove(real_this);267 return Err(e);268 }269 }270 if let Some(super_obj) = &self.0.super_obj {271 super_obj.run_assertions_raw(real_this)?;272 }273 }274 Ok(())275 }276 pub fn run_assertions(&self) -> Result<()> {277 self.run_assertions_raw(self)278 }279280 pub fn ptr_eq(a: &Self, b: &Self) -> bool {281 cc_ptr_eq(&a.0, &b.0)282 }283}284285impl PartialEq for ObjValue {286 fn eq(&self, other: &Self) -> bool {287 cc_ptr_eq(&self.0, &other.0)288 }289}290291impl Eq for ObjValue {}292impl Hash for ObjValue {293 fn hash<H: Hasher>(&self, hasher: &mut H) {294 hasher.write_usize(&*self.0 as *const _ as usize)295 }296}297298pub struct ObjValueBuilder {299 super_obj: Option<ObjValue>,300 map: GcHashMap<IStr, ObjMember>,301 assertions: Vec<TraceBox<dyn ObjectAssertion>>,302}303impl ObjValueBuilder {304 pub fn new() -> Self {305 Self::with_capacity(0)306 }307 pub fn with_capacity(capacity: usize) -> Self {308 Self {309 super_obj: None,310 map: GcHashMap::with_capacity(capacity),311 assertions: Vec::new(),312 }313 }314 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {315 self.assertions.reserve_exact(capacity);316 self317 }318 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {319 self.super_obj = Some(super_obj);320 self321 }322323 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {324 self.assertions.push(assertion);325 self326 }327 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder {328 ObjMemberBuilder {329 value: self,330 name,331 add: false,332 visibility: Visibility::Normal,333 location: None,334 }335 }336337 pub fn build(self) -> ObjValue {338 ObjValue::new(self.super_obj, Cc::new(self.map), Cc::new(self.assertions))339 }340}341impl Default for ObjValueBuilder {342 fn default() -> Self {343 Self::with_capacity(0)344 }345}346347#[must_use = "value not added unless binding() was called"]348pub struct ObjMemberBuilder<'v> {349 value: &'v mut ObjValueBuilder,350 name: IStr,351 add: bool,352 visibility: Visibility,353 location: Option<ExprLocation>,354}355356#[allow(clippy::missing_const_for_fn)]357impl<'v> ObjMemberBuilder<'v> {358 pub const fn with_add(mut self, add: bool) -> Self {359 self.add = add;360 self361 }362 pub fn add(self) -> Self {363 self.with_add(true)364 }365 pub fn with_visibility(mut self, visibility: Visibility) -> Self {366 self.visibility = visibility;367 self368 }369 pub fn hide(self) -> Self {370 self.with_visibility(Visibility::Hidden)371 }372 pub fn with_location(mut self, location: ExprLocation) -> Self {373 self.location = Some(location);374 self375 }376 pub fn value(self, value: Val) -> &'v mut ObjValueBuilder {377 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))378 }379 pub fn bindable(self, bindable: TraceBox<dyn Bindable>) -> &'v mut ObjValueBuilder {380 self.binding(LazyBinding::Bindable(Cc::new(bindable)))381 }382 pub fn binding(self, binding: LazyBinding) -> &'v mut ObjValueBuilder {383 self.value.map.insert(384 self.name,385 ObjMember {386 add: self.add,387 visibility: self.visibility,388 invoke: binding,389 location: self.location,390 },391 );392 self.value393 }394}