1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use crate::{evaluate_add_op, evaluate_assert, Context, LazyBinding, Result, Val};
use jrsonnet_interner::IStr;
use jrsonnet_parser::{AssertStmt, ExprLocation, Visibility};
use rustc_hash::{FxHashMap, FxHashSet};
use std::hash::{Hash, Hasher};
use std::{cell::RefCell, fmt::Debug, hash::BuildHasherDefault, rc::Rc};

#[derive(Debug)]
pub struct ObjMember {
	pub add: bool,
	pub visibility: Visibility,
	pub invoke: LazyBinding,
	pub location: Option<ExprLocation>,
}

// Field => This
type CacheKey = (IStr, ObjValue);
#[derive(Debug)]
pub struct ObjValueInternals {
	context: Context,
	super_obj: Option<ObjValue>,
	assertions: Rc<Vec<AssertStmt>>,
	assertions_ran: RefCell<FxHashSet<ObjValue>>,
	this_obj: Option<ObjValue>,
	this_entries: Rc<FxHashMap<IStr, ObjMember>>,
	value_cache: RefCell<FxHashMap<CacheKey, Option<Val>>>,
}

#[derive(Clone)]
pub struct ObjValue(pub(crate) Rc<ObjValueInternals>);
impl Debug for ObjValue {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		if let Some(super_obj) = self.0.super_obj.as_ref() {
			if f.alternate() {
				write!(f, "{:#?}", super_obj)?;
			} else {
				write!(f, "{:?}", super_obj)?;
			}
			write!(f, " + ")?;
		}
		let mut debug = f.debug_struct("ObjValue");
		for (name, member) in self.0.this_entries.iter() {
			debug.field(name, member);
		}
		#[cfg(feature = "unstable")]
		{
			debug.finish_non_exhaustive()
		}
		#[cfg(not(feature = "unstable"))]
		{
			debug.finish()
		}
	}
}

impl ObjValue {
	pub fn new(
		context: Context,
		super_obj: Option<Self>,
		this_entries: Rc<FxHashMap<IStr, ObjMember>>,
		assertions: Rc<Vec<AssertStmt>>,
	) -> Self {
		Self(Rc::new(ObjValueInternals {
			context,
			super_obj,
			assertions,
			assertions_ran: RefCell::new(FxHashSet::default()),
			this_obj: None,
			this_entries,
			value_cache: RefCell::new(FxHashMap::default()),
		}))
	}
	pub fn new_empty() -> Self {
		Self::new(
			Context::new(),
			None,
			Rc::new(FxHashMap::default()),
			Rc::new(Vec::new()),
		)
	}
	pub fn extend_from(&self, super_obj: Self) -> Self {
		match &self.0.super_obj {
			None => Self::new(
				self.0.context.clone(),
				Some(super_obj),
				self.0.this_entries.clone(),
				self.0.assertions.clone(),
			),
			Some(v) => Self::new(
				self.0.context.clone(),
				Some(v.extend_from(super_obj)),
				self.0.this_entries.clone(),
				self.0.assertions.clone(),
			),
		}
	}
	pub fn with_this(&self, this_obj: Self) -> Self {
		Self(Rc::new(ObjValueInternals {
			context: self.0.context.clone(),
			super_obj: self.0.super_obj.clone(),
			assertions: self.0.assertions.clone(),
			assertions_ran: RefCell::new(FxHashSet::default()),
			this_obj: Some(this_obj),
			this_entries: self.0.this_entries.clone(),
			value_cache: RefCell::new(FxHashMap::default()),
		}))
	}

	/// Run callback for every field found in object
	pub(crate) fn enum_fields(&self, handler: &mut impl FnMut(&IStr, &Visibility) -> bool) -> bool {
		if let Some(s) = &self.0.super_obj {
			if s.enum_fields(handler) {
				return true;
			}
		}
		for (name, member) in self.0.this_entries.iter() {
			if handler(name, &member.visibility) {
				return true;
			}
		}
		false
	}

	pub fn fields_visibility(&self) -> FxHashMap<IStr, bool> {
		let mut out = FxHashMap::default();
		self.enum_fields(&mut |name, visibility| {
			match visibility {
				Visibility::Normal => {
					let entry = out.entry(name.to_owned());
					entry.or_insert(true);
				}
				Visibility::Hidden => {
					out.insert(name.to_owned(), false);
				}
				Visibility::Unhide => {
					out.insert(name.to_owned(), true);
				}
			};
			false
		});
		out
	}
	pub fn fields_ex(&self, include_hidden: bool) -> Vec<IStr> {
		let mut fields: Vec<_> = self
			.fields_visibility()
			.into_iter()
			.filter(|(_k, v)| include_hidden || *v)
			.map(|(k, _)| k)
			.collect();
		fields.sort_unstable();
		fields
	}
	pub fn fields(&self) -> Vec<IStr> {
		self.fields_ex(false)
	}

	pub fn field_visibility(&self, name: IStr) -> Option<Visibility> {
		if let Some(m) = self.0.this_entries.get(&name) {
			Some(match &m.visibility {
				Visibility::Normal => self
					.0
					.super_obj
					.as_ref()
					.and_then(|super_obj| super_obj.field_visibility(name))
					.unwrap_or(Visibility::Normal),
				v => *v,
			})
		} else if let Some(super_obj) = &self.0.super_obj {
			super_obj.field_visibility(name)
		} else {
			None
		}
	}

	fn has_field_include_hidden(&self, name: IStr) -> bool {
		if self.0.this_entries.contains_key(&name) {
			true
		} else if let Some(super_obj) = &self.0.super_obj {
			super_obj.has_field_include_hidden(name)
		} else {
			false
		}
	}

	pub fn has_field_ex(&self, name: IStr, include_hidden: bool) -> bool {
		if include_hidden {
			self.has_field_include_hidden(name)
		} else {
			self.has_field(name)
		}
	}
	pub fn has_field(&self, name: IStr) -> bool {
		self.field_visibility(name)
			.map(|v| v.is_visible())
			.unwrap_or(false)
	}

	pub fn get(&self, key: IStr) -> Result<Option<Val>> {
		self.run_assertions()?;
		self.get_raw(key, self.0.this_obj.as_ref())
	}

	pub fn extend_with_field(self, key: IStr, value: ObjMember) -> Self {
		let mut new = FxHashMap::with_capacity_and_hasher(1, BuildHasherDefault::default());
		new.insert(key, value);
		Self::new(
			Context::new(),
			Some(self),
			Rc::new(new),
			Rc::new(Vec::new()),
		)
	}

	fn get_raw(&self, key: IStr, real_this: Option<&Self>) -> Result<Option<Val>> {
		let real_this = real_this.unwrap_or(self);
		let cache_key = (key.clone(), real_this.clone());

		if let Some(v) = self.0.value_cache.borrow().get(&cache_key) {
			return Ok(v.clone());
		}
		let value = match (self.0.this_entries.get(&key), &self.0.super_obj) {
			(Some(k), None) => Ok(Some(self.evaluate_this(k, real_this)?)),
			(Some(k), Some(s)) => {
				let our = self.evaluate_this(k, real_this)?;
				if k.add {
					s.get_raw(key, Some(real_this))?
						.map_or(Ok(Some(our.clone())), |v| {
							Ok(Some(evaluate_add_op(&v, &our)?))
						})
				} else {
					Ok(Some(our))
				}
			}
			(None, Some(s)) => s.get_raw(key, Some(real_this)),
			(None, None) => Ok(None),
		}?;
		self.0
			.value_cache
			.borrow_mut()
			.insert(cache_key, value.clone());
		Ok(value)
	}
	fn evaluate_this(&self, v: &ObjMember, real_this: &Self) -> Result<Val> {
		v.invoke
			.evaluate(Some(real_this.clone()), self.0.super_obj.clone())?
			.evaluate()
	}

	fn run_assertions_raw(&self, real_this: &Self) -> Result<()> {
		if self.0.assertions_ran.borrow_mut().insert(real_this.clone()) {
			for assertion in self.0.assertions.iter() {
				if let Err(e) = evaluate_assert(
					self.0
						.context
						.clone()
						.with_this_super(real_this.clone(), self.0.super_obj.clone()),
					assertion,
				) {
					self.0.assertions_ran.borrow_mut().remove(real_this);
					return Err(e);
				}
			}
			if let Some(super_obj) = &self.0.super_obj {
				super_obj.run_assertions_raw(real_this)?;
			}
		}
		Ok(())
	}
	pub fn run_assertions(&self) -> Result<()> {
		self.run_assertions_raw(self)
	}

	pub fn ptr_eq(a: &Self, b: &Self) -> bool {
		Rc::ptr_eq(&a.0, &b.0)
	}
}

impl PartialEq for ObjValue {
	fn eq(&self, other: &Self) -> bool {
		Rc::ptr_eq(&self.0, &other.0)
	}
}

impl Eq for ObjValue {}
impl Hash for ObjValue {
	fn hash<H: Hasher>(&self, state: &mut H) {
		state.write_usize(Rc::as_ptr(&self.0) as usize)
	}
}