1use crate::gc::{GcHashMap, GcHashSet, TraceBox};2use crate::operator::evaluate_add_op;3use crate::{cc_ptr_eq, Bindable, LazyBinding, LazyVal, Result, Val};4use gcmodule::{Cc, Trace};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, ObjValue);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 ObjValue(pub(crate) Cc<ObjValueInternals>);39impl Debug for ObjValue {40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {41 if let Some(super_obj) = self.0.super_obj.as_ref() {42 if f.alternate() {43 write!(f, "{:#?}", super_obj)?;44 } else {45 write!(f, "{:?}", super_obj)?;46 }47 write!(f, " + ")?;48 }49 let mut debug = f.debug_struct("ObjValue");50 for (name, member) in self.0.this_entries.iter() {51 debug.field(name, member);52 }53 #[cfg(feature = "unstable")]54 {55 debug.finish_non_exhaustive()56 }57 #[cfg(not(feature = "unstable"))]58 {59 debug.finish()60 }61 }62}6364impl ObjValue {65 pub fn new(66 super_obj: Option<Self>,67 this_entries: Cc<GcHashMap<IStr, ObjMember>>,68 assertions: Cc<Vec<TraceBox<dyn ObjectAssertion>>>,69 ) -> Self {70 Self(Cc::new(ObjValueInternals {71 super_obj,72 assertions,73 assertions_ran: RefCell::new(GcHashSet::new()),74 this_obj: None,75 this_entries,76 value_cache: RefCell::new(GcHashMap::new()),77 }))78 }79 pub fn new_empty() -> Self {80 Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))81 }82 pub fn extend_from(&self, super_obj: Self) -> Self {83 match &self.0.super_obj {84 None => Self::new(85 Some(super_obj),86 self.0.this_entries.clone(),87 self.0.assertions.clone(),88 ),89 Some(v) => Self::new(90 Some(v.extend_from(super_obj)),91 self.0.this_entries.clone(),92 self.0.assertions.clone(),93 ),94 }95 }96 pub fn with_this(&self, this_obj: Self) -> Self {97 Self(Cc::new(ObjValueInternals {98 super_obj: self.0.super_obj.clone(),99 assertions: self.0.assertions.clone(),100 assertions_ran: RefCell::new(GcHashSet::new()),101 this_obj: Some(this_obj),102 this_entries: self.0.this_entries.clone(),103 value_cache: RefCell::new(GcHashMap::new()),104 }))105 }106107 pub fn is_empty(&self) -> bool {108 if !self.0.this_entries.is_empty() {109 return false;110 }111 self.0112 .super_obj113 .as_ref()114 .map(|s| s.is_empty())115 .unwrap_or(true)116 }117118 119 pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &ObjMember) -> bool) -> bool {120 if let Some(s) = &self.0.super_obj {121 if s.enum_fields(handler) {122 return true;123 }124 }125 for (name, member) in self.0.this_entries.iter() {126 if handler(name, &member) {127 return true;128 }129 }130 false131 }132133 pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {134 let mut out = FxHashMap::default();135 self.enum_fields(&mut |name, member| {136 match member.visibility {137 Visibility::Normal => {138 let entry = out.entry(name.to_owned());139 entry.or_insert(true);140 }141 Visibility::Hidden => {142 out.insert(name.to_owned(), false);143 }144 Visibility::Unhide => {145 out.insert(name.to_owned(), true);146 }147 };148 false149 });150 out151 }152 pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {153 let mut fields: Vec<_> = self154 .fields_visibility()155 .into_iter()156 .filter(|(_k, v)| include_hidden || *v)157 .map(|(k, _)| k)158 .collect();159 fields.sort_unstable();160 fields161 }162 pub fn fields(&self) -> Vec<IStr> {163 self.fields_ex(false)164 }165166 pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {167 if let Some(m) = self.0.this_entries.get(&name) {168 Some(match &m.visibility {169 Visibility::Normal => self170 .0171 .super_obj172 .as_ref()173 .and_then(|super_obj| super_obj.field_visibility(name))174 .unwrap_or(Visibility::Normal),175 v => *v,176 })177 } else if let Some(super_obj) = &self.0.super_obj {178 super_obj.field_visibility(name)179 } else {180 None181 }182 }183184 fn has_field_include_hidden(&self, name: IStr) -> bool {185 if self.0.this_entries.contains_key(&name) {186 true187 } else if let Some(super_obj) = &self.0.super_obj {188 super_obj.has_field_include_hidden(name)189 } else {190 false191 }192 }193194 pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {195 if include_hidden {196 self.has_field_include_hidden(name)197 } else {198 self.has_field(name)199 }200 }201 pub fn has_field(&self, name: IStr) -> bool {202 self.field_visibility(name)203 .map(|v| v.is_visible())204 .unwrap_or(false)205 }206207 pub fn get(&self, key: IStr) -> Result<Option<Val>> {208 self.run_assertions()?;209 self.get_raw(key, self.0.this_obj.as_ref())210 }211212 pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {213 let mut new = GcHashMap::with_capacity(1);214 new.insert(key, value);215 Self::new(Some(self), Cc::new(new), Cc::new(Vec::new()))216 }217218 fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {219 let real_this = real_this.unwrap_or(self);220 let cache_key = (key.clone(), real_this.clone());221222 if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {223 return Ok(v.clone());224 }225 let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {226 (Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),227 (Some(k), Some(s)) => {228 let our = self.evaluate_this(k, real_this)?;229 if k.add {230 s.get_raw(key, Some(real_this))?231 .map_or(Ok(Some(our.clone())), |v| {232 Ok(Some(evaluate_add_op(&v, &our)?))233 })234 } else {235 Ok(Some(our))236 }237 }238 (None, Some(s)) => s.get_raw(key, Some(real_this)),239 (None, None) => Ok(None),240 }?;241 self.0242 .value_cache243 .borrow_mut()244 .insert(cache_key, value.clone());245 Ok(value)246 }247 fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {248 v.invoke249 .evaluate(Some(real_this.clone()), self.0.super_obj.clone())?250 .evaluate()251 }252253 fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {254 if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {255 for assertion in self.0.assertions.iter() {256 if let Err(e) = assertion.run(Some(real_this.clone()), self.0.super_obj.clone()) {257 self.0.assertions_ran.borrow_mut().remove(real_this);258 return Err(e);259 }260 }261 if let Some(super_obj) = &self.0.super_obj {262 super_obj.run_assertions_raw(real_this)?;263 }264 }265 Ok(())266 }267 pub fn run_assertions(&self) -> Result<()> {268 self.run_assertions_raw(self)269 }270271 pub fn ptr_eq(a: &Self, b: &Self) -> bool {272 cc_ptr_eq(&a.0, &b.0)273 }274}275276impl PartialEq for ObjValue {277 fn eq(&self, other: &Self) -> bool {278 cc_ptr_eq(&self.0, &other.0)279 }280}281282impl Eq for ObjValue {}283impl Hash for ObjValue {284 fn hash<H: Hasher>(&self, hasher: &mut H) {285 hasher.write_usize(&*self.0 as *const _ as usize)286 }287}288289pub struct ObjValueBuilder {290 super_obj: Option<ObjValue>,291 map: GcHashMap<IStr, ObjMember>,292 assertions: Vec<TraceBox<dyn ObjectAssertion>>,293}294impl ObjValueBuilder {295 pub fn new() -> Self {296 Self::with_capacity(0)297 }298 pub fn with_capacity(capacity: usize) -> Self {299 Self {300 super_obj: None,301 map: GcHashMap::with_capacity(capacity),302 assertions: Vec::new(),303 }304 }305 pub fn reserve_asserts(&mut self, capacity: usize) -> &mut Self {306 self.assertions.reserve_exact(capacity);307 self308 }309 pub fn with_super(&mut self, super_obj: ObjValue) -> &mut Self {310 self.super_obj = Some(super_obj);311 self312 }313314 pub fn assert(&mut self, assertion: TraceBox<dyn ObjectAssertion>) -> &mut Self {315 self.assertions.push(assertion);316 self317 }318 pub fn member(&mut self, name: IStr) -> ObjMemberBuilder {319 ObjMemberBuilder {320 value: self,321 name,322 add: false,323 visibility: Visibility::Normal,324 location: None,325 }326 }327328 pub fn build(self) -> ObjValue {329 ObjValue::new(self.super_obj, Cc::new(self.map), Cc::new(self.assertions))330 }331}332impl Default for ObjValueBuilder {333 fn default() -> Self {334 Self::with_capacity(0)335 }336}337338#[must_use = "value not added unless binding() was called"]339pub struct ObjMemberBuilder<'v> {340 value: &'v mut ObjValueBuilder,341 name: IStr,342 add: bool,343 visibility: Visibility,344 location: Option<ExprLocation>,345}346347#[allow(clippy::missing_const_for_fn)]348impl<'v> ObjMemberBuilder<'v> {349 pub const fn with_add(mut self, add: bool) -> Self {350 self.add = add;351 self352 }353 pub fn add(self) -> Self {354 self.with_add(true)355 }356 pub fn with_visibility(mut self, visibility: Visibility) -> Self {357 self.visibility = visibility;358 self359 }360 pub fn hide(self) -> Self {361 self.with_visibility(Visibility::Hidden)362 }363 pub fn with_location(mut self, location: ExprLocation) -> Self {364 self.location = Some(location);365 self366 }367 pub fn value(self, value: Val) -> &'v mut ObjValueBuilder {368 self.binding(LazyBinding::Bound(LazyVal::new_resolved(value)))369 }370 pub fn bindable(self, bindable: TraceBox<dyn Bindable>) -> &'v mut ObjValueBuilder {371 self.binding(LazyBinding::Bindable(Cc::new(bindable)))372 }373 pub fn binding(self, binding: LazyBinding) -> &'v mut ObjValueBuilder {374 self.value.map.insert(375 self.name,376 ObjMember {377 add: self.add,378 visibility: self.visibility,379 invoke: binding,380 location: self.location,381 },382 );383 self.value384 }385}