1use crate::operator::evaluate_add_op;2use crate::{Bindable, LazyBinding, LazyVal, Result, Val};3use jrsonnet_gc::{Gc, GcCell, Trace};4use jrsonnet_interner::IStr;5use jrsonnet_parser::{ExprLocation, Visibility};6use rustc_hash::{FxHashMap, FxHashSet, FxHasher};7use std::collections::HashMap;8use std::hash::{Hash, Hasher};9use std::{fmt::Debug, hash::BuildHasherDefault};1011#[derive(Debug, Trace)]12#[trivially_drop]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, ObjValue);26#[derive(Trace)]27#[trivially_drop]28pub struct ObjValueInternals {29 super_obj: Option<ObjValue>,30 assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,31 assertions_ran: GcCell<FxHashSet<ObjValue>>,32 this_obj: Option<ObjValue>,33 this_entries: Gc<FxHashMap<IStr, ObjMember>>,34 value_cache: GcCell<FxHashMap<CacheKey, Option<Val>>>,35}3637#[derive(Clone, Trace)]38#[trivially_drop]39pub struct ObjValue(pub(crate) Gc<ObjValueInternals>);40impl Debug for ObjValue {41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {42 if let Some(super_obj) = self.0.super_obj.as_ref() {43 if f.alternate() {44 write!(f, "{:#?}", super_obj)?;45 } else {46 write!(f, "{:?}", super_obj)?;47 }48 write!(f, " + ")?;49 }50 let mut debug = f.debug_struct("ObjValue");51 for (name, member) in self.0.this_entries.iter() {52 debug.field(name, member);53 }54 #[cfg(feature = "unstable")]55 {56 debug.finish_non_exhaustive()57 }58 #[cfg(not(feature = "unstable"))]59 {60 debug.finish()61 }62 }63}6465impl ObjValue {66 pub fn new(67 super_obj: Option<Self>,68 this_entries: Gc<FxHashMap<IStr, ObjMember>>,69 assertions: Gc<Vec<Box<dyn ObjectAssertion>>>,70 ) -> Self {71 Self(Gc::new(ObjValueInternals {72 super_obj,73 assertions,74 assertions_ran: GcCell::new(FxHashSet::default()),75 this_obj: None,76 this_entries,77 value_cache: GcCell::new(FxHashMap::default()),78 }))79 }80 pub fn new_empty() -> Self {81 Self::new(None, Gc::new(FxHashMap::default()), Gc::new(Vec::new()))82 }83 pub fn extend_from(&self, super_obj: Self) -> Self {84 match &self.0.super_obj {85 None => Self::new(86 Some(super_obj),87 self.0.this_entries.clone(),88 self.0.assertions.clone(),89 ),90 Some(v) => Self::new(91 Some(v.extend_from(super_obj)),92 self.0.this_entries.clone(),93 self.0.assertions.clone(),94 ),95 }96 }97 pub fn with_this(&self, this_obj: Self) -> Self {98 Self(Gc::new(ObjValueInternals {99 super_obj: self.0.super_obj.clone(),100 assertions: self.0.assertions.clone(),101 assertions_ran: GcCell::new(FxHashSet::default()),102 this_obj: Some(this_obj),103 this_entries: self.0.this_entries.clone(),104 value_cache: GcCell::new(FxHashMap::default()),105 }))106 }107108 pub fn is_empty(&self) -> bool {109 if !self.0.this_entries.is_empty() {110 return false;111 }112 self.0113 .super_obj114 .as_ref()115 .map(|s| s.is_empty())116 .unwrap_or(true)117 }118119 120 pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &Visibility) -> bool) -> bool {121 if let Some(s) = &self.0.super_obj {122 if s.enum_fields(handler) {123 return true;124 }125 }126 for (name, member) in self.0.this_entries.iter() {127 if handler(name, &member.visibility) {128 return true;129 }130 }131 false132 }133134 pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {135 let mut out = FxHashMap::default();136 self.enum_fields(&mut |name, visibility| {137 match visibility {138 Visibility::Normal => {139 let entry = out.entry(name.to_owned());140 entry.or_insert(true);141 }142 Visibility::Hidden => {143 out.insert(name.to_owned(), false);144 }145 Visibility::Unhide => {146 out.insert(name.to_owned(), true);147 }148 };149 false150 });151 out152 }153 pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {154 let mut fields: Vec<_> = self155 .fields_visibility()156 .into_iter()157 .filter(|(_k, v)| include_hidden || *v)158 .map(|(k, _)| k)159 .collect();160 fields.sort_unstable();161 fields162 }163 pub fn fields(&self) -> Vec<IStr> {164 self.fields_ex(false)165 }166167 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {168 if let Some(m) = self.0.this_entries.get(&name) {169 Some(match &m.visibility {170 Visibility::Normal => self171 .0172 .super_obj173 .as_ref()174 .and_then(|super_obj| super_obj.field_visibility(name))175 .unwrap_or(Visibility::Normal),176 v => *v,177 })178 } else if let Some(super_obj) = &self.0.super_obj {179 super_obj.field_visibility(name)180 } else {181 None182 }183 }184185 fn has_field_include_hidden(&self, name: IStr) -> bool {186 if self.0.this_entries.contains_key(&name) {187 true188 } else if let Some(super_obj) = &self.0.super_obj {189 super_obj.has_field_include_hidden(name)190 } else {191 false192 }193 }194195 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {196 if include_hidden {197 self.has_field_include_hidden(name)198 } else {199 self.has_field(name)200 }201 }202 pub fn has_field(&self, name: IStr) -> bool {203 self.field_visibility(name)204 .map(|v| v.is_visible())205 .unwrap_or(false)206 }207208 pub fn get(&self, key: IStr) -> Result<Option<Val>> {209 self.run_assertions()?;210 self.get_raw(key, self.0.this_obj.as_ref())211 }212213 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {214 let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());215 new.insert(key, value);216 Self::new(Some(self), Gc::new(new), Gc::new(Vec::new()))217 }218219 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {220 let real_this = real_this.unwrap_or(self);221 let cache_key = (key.clone(), real_this.clone());222223 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {224 return Ok(v.clone());225 }226 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {227 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),228 (Some(k), Some(s)) => {229 let our = self.evaluate_this(k, real_this)?;230 if k.add {231 s.get_raw(key, Some(real_this))?232 .map_or(Ok(Some(our.clone())), |v| {233 Ok(Some(evaluate_add_op(&v, &our)?))234 })235 } else {236 Ok(Some(our))237 }238 }239 (None, Some(s)) => s.get_raw(key, Some(real_this)),240 (None, None) => Ok(None),241 }?;242 self.0243 .value_cache244 .borrow_mut()245 .insert(cache_key, value.clone());246 Ok(value)247 }248 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {249 v.invoke250 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?251 .evaluate()252 }253254 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {255 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {256 for assertion in self.0.assertions.iter() {257 if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {258 self.0.assertions_ran.borrow_mut().remove(real_this);259 return Err(e);260 }261 }262 if let Some(super_obj) = &self.0.super_obj {263 super_obj.run_assertions_raw(real_this)?;264 }265 }266 Ok(())267 }268 pub fn run_assertions(&self) -> Result<()> {269 self.run_assertions_raw(self)270 }271272 pub fn ptr_eq(a: &Self, b: &Self) -> bool {273 Gc::ptr_eq(&a.0, &b.0)274 }275}276277impl PartialEq for ObjValue {278 fn eq(&self, other: &Self) -> bool {279 Gc::ptr_eq(&self.0, &other.0)280 }281}282283impl Eq for ObjValue {}284impl Hash for ObjValue {285 fn hash<H: Hasher>(&self, hasher: &mut H) {286 hasher.write_usize(&*self.0 as *const _ as usize)287 }288}289290pub struct ObjValueBuilder {291 super_obj: Option<ObjValue>,292 map: FxHashMap<IStr, ObjMember>,293 assertions: Vec<Box<dyn ObjectAssertion>>,294}295impl ObjValueBuilder {296 pub fn new() -> Self {297 Self::with_capacity(0)298 }299 pub fn with_capacity(capacity: usize) -> Self {300 Self {301 super_obj: None,302 map: HashMap::with_capacity_and_hasher(303 capacity,304 BuildHasherDefault::<FxHasher>::default(),305 ),306 assertions: Vec::new(),307 }308 }309 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {310 self.assertions.reserve_exact(capacity);311 self312 }313 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {314 self.super_obj = Some(super_obj);315 self316 }317318 pub fn assert(&mut self, assertion: Box<dyn ObjectAssertion>) -> &mut Self {319 self.assertions.push(assertion);320 self321 }322 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder {323 ObjMemberBuilder {324 value: self,325 name,326 add: false,327 visibility: Visibility::Normal,328 location: None,329 }330 }331332 pub fn build(self) -> ObjValue {333 ObjValue::new(self.super_obj, Gc::new(self.map), Gc::new(self.assertions))334 }335}336impl Default for ObjValueBuilder {337 fn default() -> Self {338 Self::with_capacity(0)339 }340}341342#[must_use = "value not added unless binding() was called"]343pub struct ObjMemberBuilder<'v> {344 value: &'v mut ObjValueBuilder,345 name: IStr,346 add: bool,347 visibility: Visibility,348 location: Option<ExprLocation>,349}350351#[allow(clippy::missing_const_for_fn)]352impl<'v> ObjMemberBuilder<'v> {353 pub const fn with_add(mut self, add: bool) -> Self {354 self.add = add;355 self356 }357 pub fn add(self) -> Self {358 self.with_add(true)359 }360 pub fn with_visibility(mut self, visibility: Visibility) -> Self {361 self.visibility = visibility;362 self363 }364 pub fn hide(self) -> Self {365 self.with_visibility(Visibility::Hidden)366 }367 pub fn with_location(mut self, location: Option<ExprLocation>) -> Self {368 self.location = location;369 self370 }371 pub fn value(self, value: Val) -> &'v mut ObjValueBuilder {372 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))373 }374 pub fn bindable(self, bindable: Box<dyn Bindable>) -> &'v mut ObjValueBuilder {375 self.binding(LazyBinding::Bindable(Gc::new(bindable)))376 }377 pub fn binding(self, binding: LazyBinding) -> &'v mut ObjValueBuilder {378 self.value.map.insert(379 self.name,380 ObjMember {381 add: self.add,382 visibility: self.visibility,383 invoke: binding,384 location: self.location,385 },386 );387 self.value388 }389}