difftreelog
refactor unify throw & throw_runtime
in: master
13 files changed
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -266,14 +266,13 @@
#[macro_export]
macro_rules! throw {
- ($e: expr) => {
- return Err($e.into())
+ ($w:ident$(::$i:ident)*$(($($tt:tt)*))?) => {
+ return Err($w$(::$i)*$(($($tt)*))?.into())
};
-}
-
-#[macro_export]
-macro_rules! throw_runtime {
- ($($tt:tt)*) => {
- return Err($crate::error::Error::RuntimeError(format!($($tt)*).into()).into())
+ ($l:literal) => {
+ return Err($crate::error::Error::RuntimeError($l.into()).into())
+ };
+ ($l:literal, $($tt:tt)*) => {
+ return Err($crate::error::Error::RuntimeError(format!($l, $($tt)*).into()).into())
};
}
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -32,7 +32,7 @@
Destruct::Array { start, rest, end } => {
use jrsonnet_parser::DestructRest;
- use crate::{throw_runtime, val::ArrValue};
+ use crate::{throw, val::ArrValue};
#[derive(Trace)]
struct DataThunk {
@@ -47,14 +47,14 @@
let v = self.parent.evaluate(s)?;
let arr = match v {
Val::Arr(a) => a,
- _ => throw_runtime!("expected array"),
+ _ => throw!("expected array"),
};
if !self.has_rest {
if arr.len() != self.min_len {
- throw_runtime!("expected {} elements, got {}", self.min_len, arr.len())
+ throw!("expected {} elements, got {}", self.min_len, arr.len())
}
} else if arr.len() < self.min_len {
- throw_runtime!(
+ throw!(
"expected at least {} elements, but array was only {}",
self.min_len,
arr.len()
@@ -163,7 +163,7 @@
}
#[cfg(feature = "exp-destruct")]
Destruct::Object { fields, rest } => {
- use crate::{obj::ObjValue, throw_runtime};
+ use crate::{obj::ObjValue, throw};
#[derive(Trace)]
struct DataThunk {
@@ -178,17 +178,17 @@
let v = self.parent.evaluate(s)?;
let obj = match v {
Val::Obj(o) => o,
- _ => throw_runtime!("expected object"),
+ _ => throw!("expected object"),
};
for field in &self.field_names {
if !obj.has_field_ex(field.clone(), true) {
- throw_runtime!("missing field: {}", field);
+ throw!("missing field: {}", field);
}
}
if !self.has_rest {
let len = obj.len();
if len != self.field_names.len() {
- throw_runtime!("too many fields, and rest not found");
+ throw!("too many fields, and rest not found");
}
}
Ok(obj)
crates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -150,13 +150,13 @@
(Num(v1), BitXor, Num(v2)) => Num(f64::from((*v1 as i32) ^ (*v2 as i32))),
(Num(v1), Lhs, Num(v2)) => {
if *v2 < 0.0 {
- throw!(RuntimeError("shift by negative exponent".into()))
+ throw!("shift by negative exponent")
}
Num(f64::from((*v1 as i32) << (*v2 as i32)))
}
(Num(v1), Rhs, Num(v2)) => {
if *v2 < 0.0 {
- throw!(RuntimeError("shift by negative exponent".into()))
+ throw!("shift by negative exponent")
}
Num(f64::from((*v1 as i32) >> (*v2 as i32)))
}
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -72,7 +72,7 @@
}
Self::Object(out)
}
- Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+ Val::Func(_) => throw!("tried to manifest function"),
})
}
}
crates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -591,9 +591,7 @@
),
Val::Str(s) => {
if s.chars().count() != 1 {
- throw!(RuntimeError(
- format!("%c expected 1 char string, got {}", s.chars().count()).into(),
- ));
+ throw!("%c expected 1 char string, got {}", s.chars().count(),);
}
tmp_out.push_str(&s);
}
crates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -341,7 +341,7 @@
}
}
}
- Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
+ Val::Func(_) => throw!("tried to manifest function"),
}
Ok(())
}
crates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -6,7 +6,7 @@
use jrsonnet_types::{ComplexValType, ValType};
use crate::{
- error::{Error::*, Result},
+ error::Result,
function::{FuncDesc, FuncVal},
throw,
typed::CheckType,
@@ -41,13 +41,10 @@
Val::Num(n) => {
#[allow(clippy::float_cmp)]
if n.trunc() != n {
- throw!(RuntimeError(
- format!(
- "cannot convert number with fractional part to {}",
- stringify!($ty)
- )
- .into()
- ))
+ throw!(
+ "cannot convert number with fractional part to {}",
+ stringify!($ty)
+ )
}
Ok(n as Self)
}
@@ -99,13 +96,10 @@
Val::Num(n) => {
#[allow(clippy::float_cmp)]
if n.trunc() != n {
- throw!(RuntimeError(
- format!(
- "cannot convert number with fractional part to {}",
- stringify!($ty)
- )
- .into()
- ))
+ throw!(
+ "cannot convert number with fractional part to {}",
+ stringify!($ty)
+ )
}
Ok(Self(n as $ty))
}
@@ -167,7 +161,7 @@
fn into_untyped(value: Self, _: State) -> Result<Val> {
if value > u32::MAX as Self {
- throw!(RuntimeError("number is too large".into()))
+ throw!("number is too large")
}
Ok(Val::Num(value as f64))
}
@@ -178,9 +172,7 @@
Val::Num(n) => {
#[allow(clippy::float_cmp)]
if n.trunc() != n {
- throw!(RuntimeError(
- "cannot convert number with fractional part to usize".into()
- ))
+ throw!("cannot convert number with fractional part to usize")
}
Ok(n as Self)
}
@@ -440,7 +432,7 @@
<Self as Typed>::TYPE.check(s, &value)?;
match value {
Val::Func(FuncVal::Normal(desc)) => Ok(desc),
- Val::Func(_) => throw!(RuntimeError("expected normal function, not builtin".into())),
+ Val::Func(_) => throw!("expected normal function, not builtin"),
_ => unreachable!(),
}
}
crates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_types::ValType;67use crate::{8 error::{Error::*, LocError},9 function::FuncVal,10 gc::{GcHashMap, TraceBox},11 stdlib::manifest::{12 manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,13 },14 throw,15 typed::BoundedUsize,16 ObjValue, Result, State, Unbound, WeakObjValue,17};1819pub trait ThunkValue: Trace {20 type Output;21 fn get(self: Box<Self>, s: State) -> Result<Self::Output>;22}2324#[derive(Trace)]25enum ThunkInner<T: Trace> {26 Computed(T),27 Errored(LocError),28 Waiting(TraceBox<dyn ThunkValue<Output = T>>),29 Pending,30}3132#[allow(clippy::module_name_repetitions)]33#[derive(Clone, Trace)]34pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);3536impl<T> Thunk<T>37where38 T: Clone + Trace,39{40 pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {41 Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))42 }43 pub fn evaluated(val: T) -> Self {44 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))45 }46 pub fn force(&self, s: State) -> Result<()> {47 self.evaluate(s)?;48 Ok(())49 }50 pub fn evaluate(&self, s: State) -> Result<T> {51 match &*self.0.borrow() {52 ThunkInner::Computed(v) => return Ok(v.clone()),53 ThunkInner::Errored(e) => return Err(e.clone()),54 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),55 ThunkInner::Waiting(..) => (),56 };57 let value = if let ThunkInner::Waiting(value) =58 std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)59 {60 value61 } else {62 unreachable!()63 };64 let new_value = match value.0.get(s) {65 Ok(v) => v,66 Err(e) => {67 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());68 return Err(e);69 }70 };71 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());72 Ok(new_value)73 }74}7576type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);7778#[derive(Trace, Clone)]79pub struct CachedUnbound<I, T>80where81 I: Unbound<Bound = T>,82 T: Trace,83{84 cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,85 value: I,86}87impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {88 pub fn new(value: I) -> Self {89 Self {90 cache: Cc::new(RefCell::new(GcHashMap::new())),91 value,92 }93 }94}95impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {96 type Bound = T;97 fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {98 let cache_key = (99 sup.as_ref().map(|s| s.clone().downgrade()),100 this.as_ref().map(|t| t.clone().downgrade()),101 );102 {103 if let Some(t) = self.cache.borrow().get(&cache_key) {104 return Ok(t.clone());105 }106 }107 let bound = self.value.bind(s, sup, this)?;108109 {110 let mut cache = self.cache.borrow_mut();111 cache.insert(cache_key, bound.clone());112 }113114 Ok(bound)115 }116}117118impl<T: Debug + Trace> Debug for Thunk<T> {119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {120 write!(f, "Lazy")121 }122}123impl<T: Trace> PartialEq for Thunk<T> {124 fn eq(&self, other: &Self) -> bool {125 Cc::ptr_eq(&self.0, &other.0)126 }127}128129#[derive(Clone)]130pub enum ManifestFormat {131 YamlStream(Box<ManifestFormat>),132 Yaml {133 padding: usize,134 #[cfg(feature = "exp-preserve-order")]135 preserve_order: bool,136 },137 Json {138 padding: usize,139 #[cfg(feature = "exp-preserve-order")]140 preserve_order: bool,141 },142 ToString,143 String,144}145impl ManifestFormat {146 #[cfg(feature = "exp-preserve-order")]147 fn preserve_order(&self) -> bool {148 match self {149 ManifestFormat::YamlStream(s) => s.preserve_order(),150 ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,151 ManifestFormat::Json { preserve_order, .. } => *preserve_order,152 ManifestFormat::ToString => false,153 ManifestFormat::String => false,154 }155 }156}157158#[derive(Debug, Clone, Trace)]159pub struct Slice {160 pub(crate) inner: ArrValue,161 pub(crate) from: u32,162 pub(crate) to: u32,163 pub(crate) step: u32,164}165impl Slice {166 const fn from(&self) -> usize {167 self.from as usize168 }169 const fn to(&self) -> usize {170 self.to as usize171 }172 const fn step(&self) -> usize {173 self.step as usize174 }175 const fn len(&self) -> usize {176 // TODO: use div_ceil177 let diff = self.to() - self.from();178 let rem = diff % self.step();179 let div = diff / self.step();180181 if rem == 0 {182 div183 } else {184 div + 1185 }186 }187}188189/// Represents a Jsonnet array value.190#[derive(Debug, Clone, Trace)]191// may contrain other ArrValue192#[trace(tracking(force))]193pub enum ArrValue {194 /// Layout optimized byte array.195 Bytes(#[trace(skip)] IBytes),196 /// Every element is lazy evaluated.197 Lazy(Cc<Vec<Thunk<Val>>>),198 /// Every field is already evaluated.199 Eager(Cc<Vec<Val>>),200 /// Concatenation of two arrays of any kind.201 Extended(Box<(Self, Self)>),202 /// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.203 /// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.204 Range(i32, i32),205 /// Sliced array view.206 Slice(Box<Slice>),207 /// Reversed array view.208 /// Returned by `std.reverse(other)` call209 Reversed(Box<Self>),210}211212#[cfg(target_pointer_width = "64")]213static_assertions::assert_eq_size!(ArrValue, [u8; 16]);214215impl ArrValue {216 pub fn new_eager() -> Self {217 Self::Eager(Cc::new(Vec::new()))218 }219 pub fn empty() -> Self {220 Self::new_range(0, 0)221 }222223 /// # Panics224 /// If a > b225 #[inline]226 pub fn new_range(a: i32, b: i32) -> Self {227 assert!(a <= b);228 Self::Range(a, b)229 }230231 /// # Panics232 /// If passed numbers are incorrect233 #[must_use]234 pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {235 let len = self.len();236 let from = from.unwrap_or(0);237 let to = to.unwrap_or(len).min(len);238 let step = step.unwrap_or(1);239 assert!(from < to);240 assert!(step > 0);241242 Self::Slice(Box::new(Slice {243 inner: self,244 from: from as u32,245 to: to as u32,246 step: step as u32,247 }))248 }249250 /// Array length.251 pub fn len(&self) -> usize {252 match self {253 Self::Bytes(i) => i.len(),254 Self::Lazy(l) => l.len(),255 Self::Eager(e) => e.len(),256 Self::Extended(v) => v.0.len() + v.1.len(),257 Self::Range(a, b) => a.abs_diff(*b) as usize + 1,258 Self::Reversed(i) => i.len(),259 Self::Slice(s) => s.len(),260 }261 }262263 /// Is array contains no elements?264 pub fn is_empty(&self) -> bool {265 self.len() == 0266 }267268 /// Get array element by index, evaluating it, if it is lazy.269 ///270 /// Returns `None` on out-of-bounds condition.271 pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {272 match self {273 Self::Bytes(i) => i274 .get(index)275 .map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),276 Self::Lazy(vec) => {277 if let Some(v) = vec.get(index) {278 Ok(Some(v.evaluate(s)?))279 } else {280 Ok(None)281 }282 }283 Self::Eager(vec) => Ok(vec.get(index).cloned()),284 Self::Extended(v) => {285 let a_len = v.0.len();286 if a_len > index {287 v.0.get(s, index)288 } else {289 v.1.get(s, index - a_len)290 }291 }292 Self::Range(a, _) => {293 if index >= self.len() {294 return Ok(None);295 }296 Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))297 }298 Self::Reversed(v) => {299 let len = v.len();300 if index >= len {301 return Ok(None);302 }303 v.get(s, len - index - 1)304 }305 Self::Slice(v) => {306 let index = v.from() + index * v.step();307 if index >= v.to() {308 return Ok(None);309 }310 v.inner.get(s, index)311 }312 }313 }314315 /// Get array element by index, without evaluation.316 ///317 /// Returns `None` on out-of-bounds condition.318 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {319 match self {320 Self::Bytes(i) => i321 .get(index)322 .map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),323 Self::Lazy(vec) => vec.get(index).cloned(),324 Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),325 Self::Extended(v) => {326 let a_len = v.0.len();327 if a_len > index {328 v.0.get_lazy(index)329 } else {330 v.1.get_lazy(index - a_len)331 }332 }333 Self::Range(a, _) => {334 if index >= self.len() {335 return None;336 }337 Some(Thunk::evaluated(Val::Num(338 ((*a as isize) + index as isize) as f64,339 )))340 }341 Self::Reversed(v) => {342 let len = v.len();343 if index >= len {344 return None;345 }346 v.get_lazy(len - index - 1)347 }348 Self::Slice(s) => {349 let index = s.from() + index * s.step();350 if index >= s.to() {351 return None;352 }353 s.inner.get_lazy(index)354 }355 }356 }357358 /// Evaluate all array elements, returning new array.359 pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {360 Ok(match self {361 Self::Bytes(i) => {362 let mut out = Vec::with_capacity(i.len());363 for v in i.iter() {364 out.push(Val::Num(f64::from(*v)));365 }366 Cc::new(out)367 }368 Self::Lazy(vec) => {369 let mut out = Vec::with_capacity(vec.len());370 for item in vec.iter() {371 out.push(item.evaluate(s.clone())?);372 }373 Cc::new(out)374 }375 Self::Eager(vec) => vec.clone(),376 Self::Extended(_v) => {377 let mut out = Vec::with_capacity(self.len());378 for item in self.iter(s) {379 out.push(item?);380 }381 Cc::new(out)382 }383 Self::Range(a, b) => {384 let mut out = Vec::with_capacity(self.len());385 for i in *a..*b {386 out.push(Val::Num(f64::from(i)));387 }388 Cc::new(out)389 }390 Self::Reversed(r) => {391 let mut r = r.evaluated(s)?;392 Cc::update_with(&mut r, |v| v.reverse());393 r394 }395 Self::Slice(v) => {396 let mut out = Vec::with_capacity(v.inner.len());397 for v in v398 .inner399 .iter_lazy()400 .skip(v.from())401 .take(v.to() - v.from())402 .step_by(v.step())403 {404 out.push(v.evaluate(s.clone())?);405 }406 Cc::new(out)407 }408 })409 }410411 /// Iterate over elements, evaluating them.412 pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {413 (0..self.len()).map(move |idx| match self {414 Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),415 Self::Lazy(l) => l[idx].evaluate(s.clone()),416 Self::Eager(e) => Ok(e[idx].clone()),417 Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {418 self.get(s.clone(), idx).map(|e| e.expect("idx < len"))419 }420 })421 }422423 /// Iterate over elements, returning lazy values.424 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {425 (0..self.len()).map(move |idx| match self {426 Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),427 Self::Lazy(l) => l[idx].clone(),428 Self::Eager(e) => Thunk::evaluated(e[idx].clone()),429 Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {430 self.get_lazy(idx).expect("idx < len")431 }432 })433 }434435 /// Return a reversed view on current array.436 #[must_use]437 pub fn reversed(self) -> Self {438 Self::Reversed(Box::new(self))439 }440441 /// Return a new array, produced by passing every element of current array to specified callback function.442 pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {443 let mut out = Vec::with_capacity(self.len());444445 for value in self.iter(s) {446 out.push(mapper(value?)?);447 }448449 Ok(Self::Eager(Cc::new(out)))450 }451452 /// Return a new array, produced from current array by removing every value, for which specified callback function returns false.453 pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {454 let mut out = Vec::with_capacity(self.len());455456 for value in self.iter(s) {457 let value = value?;458 if filter(&value)? {459 out.push(value);460 }461 }462463 Ok(Self::Eager(Cc::new(out)))464 }465466 pub fn ptr_eq(a: &Self, b: &Self) -> bool {467 match (a, b) {468 (Self::Lazy(a), Self::Lazy(b)) => Cc::ptr_eq(a, b),469 (Self::Eager(a), Self::Eager(b)) => Cc::ptr_eq(a, b),470 _ => false,471 }472 }473}474475impl From<Vec<Thunk<Val>>> for ArrValue {476 fn from(v: Vec<Thunk<Val>>) -> Self {477 Self::Lazy(Cc::new(v))478 }479}480481impl From<Vec<Val>> for ArrValue {482 fn from(v: Vec<Val>) -> Self {483 Self::Eager(Cc::new(v))484 }485}486487/// Represents a Jsonnet value, which can be spliced or indexed (string or array).488#[allow(clippy::module_name_repetitions)]489pub enum IndexableVal {490 /// String.491 Str(IStr),492 /// Array.493 Arr(ArrValue),494}495impl IndexableVal {496 /// Slice the value.497 ///498 /// # Implementation499 ///500 /// For strings, will create a copy of specified interval.501 ///502 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.503 pub fn slice(504 self,505 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,506 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,507 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,508 ) -> Result<Self> {509 match &self {510 IndexableVal::Str(s) => {511 let index = index.as_deref().copied().unwrap_or(0);512 let end = end.as_deref().copied().unwrap_or(usize::MAX);513 let step = step.as_deref().copied().unwrap_or(1);514515 if index >= end {516 return Ok(Self::Str("".into()));517 }518519 Ok(Self::Str(520 (s.chars()521 .skip(index)522 .take(end - index)523 .step_by(step)524 .collect::<String>())525 .into(),526 ))527 }528 IndexableVal::Arr(arr) => {529 let index = index.as_deref().copied().unwrap_or(0);530 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());531 let step = step.as_deref().copied().unwrap_or(1);532533 if index >= end {534 return Ok(Self::Arr(ArrValue::new_eager()));535 }536537 Ok(Self::Arr(ArrValue::Slice(Box::new(Slice {538 inner: arr.clone(),539 from: index as u32,540 to: end as u32,541 step: step as u32,542 }))))543 }544 }545 }546}547548/// Represents any valid Jsonnet value.549#[derive(Debug, Clone, Trace)]550pub enum Val {551 /// Represents a Jsonnet boolean.552 Bool(bool),553 /// Represents a Jsonnet null value.554 Null,555 /// Represents a Jsonnet string.556 Str(IStr),557 /// Represents a Jsonnet number.558 /// Should be finite, and not NaN559 /// This restriction isn't enforced by enum, as enum field can't be marked as private560 Num(f64),561 /// Represents a Jsonnet array.562 Arr(ArrValue),563 /// Represents a Jsonnet object.564 Obj(ObjValue),565 /// Represents a Jsonnet function.566 Func(FuncVal),567}568569impl From<IndexableVal> for Val {570 fn from(v: IndexableVal) -> Self {571 match v {572 IndexableVal::Str(s) => Self::Str(s),573 IndexableVal::Arr(a) => Self::Arr(a),574 }575 }576}577578// Broken between stable and nightly, as there is new layout size optimization579// #[cfg(target_pointer_width = "64")]580// static_assertions::assert_eq_size!(Val, [u8; 24]);581582impl Val {583 pub const fn as_bool(&self) -> Option<bool> {584 match self {585 Self::Bool(v) => Some(*v),586 _ => None,587 }588 }589 pub const fn as_null(&self) -> Option<()> {590 match self {591 Self::Null => Some(()),592 _ => None,593 }594 }595 pub fn as_str(&self) -> Option<IStr> {596 match self {597 Self::Str(s) => Some(s.clone()),598 _ => None,599 }600 }601 pub const fn as_num(&self) -> Option<f64> {602 match self {603 Self::Num(n) => Some(*n),604 _ => None,605 }606 }607 pub fn as_arr(&self) -> Option<ArrValue> {608 match self {609 Self::Arr(a) => Some(a.clone()),610 _ => None,611 }612 }613 pub fn as_obj(&self) -> Option<ObjValue> {614 match self {615 Self::Obj(o) => Some(o.clone()),616 _ => None,617 }618 }619 pub fn as_func(&self) -> Option<FuncVal> {620 match self {621 Self::Func(f) => Some(f.clone()),622 _ => None,623 }624 }625626 /// Creates `Val::Num` after checking for numeric overflow.627 /// As numbers are `f64`, we can just check for their finity.628 pub fn new_checked_num(num: f64) -> Result<Self> {629 if num.is_finite() {630 Ok(Self::Num(num))631 } else {632 throw!(RuntimeError("overflow".into()))633 }634 }635636 pub const fn value_type(&self) -> ValType {637 match self {638 Self::Str(..) => ValType::Str,639 Self::Num(..) => ValType::Num,640 Self::Arr(..) => ValType::Arr,641 Self::Obj(..) => ValType::Obj,642 Self::Bool(_) => ValType::Bool,643 Self::Null => ValType::Null,644 Self::Func(..) => ValType::Func,645 }646 }647648 pub fn to_string(&self, s: State) -> Result<IStr> {649 Ok(match self {650 Self::Bool(true) => "true".into(),651 Self::Bool(false) => "false".into(),652 Self::Null => "null".into(),653 Self::Str(s) => s.clone(),654 v => manifest_json_ex(655 s,656 v,657 &ManifestJsonOptions {658 padding: "",659 mtype: ManifestType::ToString,660 newline: "\n",661 key_val_sep: ": ",662 #[cfg(feature = "exp-preserve-order")]663 preserve_order: false,664 },665 )?666 .into(),667 })668 }669670 /// Expects value to be object, outputs (key, manifested value) pairs671 pub fn manifest_multi(&self, s: State, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {672 let obj = match self {673 Self::Obj(obj) => obj,674 _ => throw!(MultiManifestOutputIsNotAObject),675 };676 let keys = obj.fields(677 #[cfg(feature = "exp-preserve-order")]678 ty.preserve_order(),679 );680 let mut out = Vec::with_capacity(keys.len());681 for key in keys {682 let value = obj683 .get(s.clone(), key.clone())?684 .expect("item in object")685 .manifest(s.clone(), ty)?;686 out.push((key, value));687 }688 Ok(out)689 }690691 /// Expects value to be array, outputs manifested values692 pub fn manifest_stream(&self, s: State, ty: &ManifestFormat) -> Result<Vec<IStr>> {693 let arr = match self {694 Self::Arr(a) => a,695 _ => throw!(StreamManifestOutputIsNotAArray),696 };697 let mut out = Vec::with_capacity(arr.len());698 for i in arr.iter(s.clone()) {699 out.push(i?.manifest(s.clone(), ty)?);700 }701 Ok(out)702 }703704 pub fn manifest(&self, s: State, ty: &ManifestFormat) -> Result<IStr> {705 Ok(match ty {706 ManifestFormat::YamlStream(format) => {707 let arr = match self {708 Self::Arr(a) => a,709 _ => throw!(StreamManifestOutputIsNotAArray),710 };711 let mut out = String::new();712713 match format as &ManifestFormat {714 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),715 ManifestFormat::String => throw!(StreamManifestCannotNestString),716 _ => {}717 };718719 if !arr.is_empty() {720 for v in arr.iter(s.clone()) {721 out.push_str("---\n");722 out.push_str(&v?.manifest(s.clone(), format)?);723 out.push('\n');724 }725 out.push_str("...");726 }727728 out.into()729 }730 ManifestFormat::Yaml {731 padding,732 #[cfg(feature = "exp-preserve-order")]733 preserve_order,734 } => self.to_yaml(735 s,736 *padding,737 #[cfg(feature = "exp-preserve-order")]738 *preserve_order,739 )?,740 ManifestFormat::Json {741 padding,742 #[cfg(feature = "exp-preserve-order")]743 preserve_order,744 } => self.to_json(745 s,746 *padding,747 #[cfg(feature = "exp-preserve-order")]748 *preserve_order,749 )?,750 ManifestFormat::ToString => self.to_string(s)?,751 ManifestFormat::String => match self {752 Self::Str(s) => s.clone(),753 _ => throw!(StringManifestOutputIsNotAString),754 },755 })756 }757758 /// For manifestification759 pub fn to_json(760 &self,761 s: State,762 padding: usize,763 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,764 ) -> Result<IStr> {765 manifest_json_ex(766 s,767 self,768 &ManifestJsonOptions {769 padding: &" ".repeat(padding),770 mtype: if padding == 0 {771 ManifestType::Minify772 } else {773 ManifestType::Manifest774 },775 newline: "\n",776 key_val_sep: ": ",777 #[cfg(feature = "exp-preserve-order")]778 preserve_order,779 },780 )781 .map(Into::into)782 }783784 /// Calls `std.manifestJson`785 pub fn to_std_json(786 &self,787 s: State,788 padding: usize,789 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,790 ) -> Result<Rc<str>> {791 manifest_json_ex(792 s,793 self,794 &ManifestJsonOptions {795 padding: &" ".repeat(padding),796 mtype: ManifestType::Std,797 newline: "\n",798 key_val_sep: ": ",799 #[cfg(feature = "exp-preserve-order")]800 preserve_order,801 },802 )803 .map(Into::into)804 }805806 pub fn to_yaml(807 &self,808 s: State,809 padding: usize,810 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,811 ) -> Result<IStr> {812 let padding = &" ".repeat(padding);813 manifest_yaml_ex(814 s,815 self,816 &ManifestYamlOptions {817 padding,818 arr_element_padding: padding,819 quote_keys: false,820 #[cfg(feature = "exp-preserve-order")]821 preserve_order,822 },823 )824 .map(Into::into)825 }826 pub fn into_indexable(self) -> Result<IndexableVal> {827 Ok(match self {828 Val::Str(s) => IndexableVal::Str(s),829 Val::Arr(arr) => IndexableVal::Arr(arr),830 _ => throw!(ValueIsNotIndexable(self.value_type())),831 })832 }833}834835const fn is_function_like(val: &Val) -> bool {836 matches!(val, Val::Func(_))837}838839/// Native implementation of `std.primitiveEquals`840pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {841 Ok(match (val_a, val_b) {842 (Val::Bool(a), Val::Bool(b)) => a == b,843 (Val::Null, Val::Null) => true,844 (Val::Str(a), Val::Str(b)) => a == b,845 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,846 (Val::Arr(_), Val::Arr(_)) => throw!(RuntimeError(847 "primitiveEquals operates on primitive types, got array".into(),848 )),849 (Val::Obj(_), Val::Obj(_)) => throw!(RuntimeError(850 "primitiveEquals operates on primitive types, got object".into(),851 )),852 (a, b) if is_function_like(a) && is_function_like(b) => {853 throw!(RuntimeError("cannot test equality of functions".into()))854 }855 (_, _) => false,856 })857}858859/// Native implementation of `std.equals`860pub fn equals(s: State, val_a: &Val, val_b: &Val) -> Result<bool> {861 if val_a.value_type() != val_b.value_type() {862 return Ok(false);863 }864 match (val_a, val_b) {865 (Val::Arr(a), Val::Arr(b)) => {866 if ArrValue::ptr_eq(a, b) {867 return Ok(true);868 }869 if a.len() != b.len() {870 return Ok(false);871 }872 for (a, b) in a.iter(s.clone()).zip(b.iter(s.clone())) {873 if !equals(s.clone(), &a?, &b?)? {874 return Ok(false);875 }876 }877 Ok(true)878 }879 (Val::Obj(a), Val::Obj(b)) => {880 if ObjValue::ptr_eq(a, b) {881 return Ok(true);882 }883 let fields = a.fields(884 #[cfg(feature = "exp-preserve-order")]885 false,886 );887 if fields888 != b.fields(889 #[cfg(feature = "exp-preserve-order")]890 false,891 ) {892 return Ok(false);893 }894 for field in fields {895 if !equals(896 s.clone(),897 &a.get(s.clone(), field.clone())?.expect("field exists"),898 &b.get(s.clone(), field)?.expect("field exists"),899 )? {900 return Ok(false);901 }902 }903 Ok(true)904 }905 (a, b) => Ok(primitive_equals(a, b)?),906 }907}1use std::{cell::RefCell, fmt::Debug, rc::Rc};23use jrsonnet_gcmodule::{Cc, Trace};4use jrsonnet_interner::{IBytes, IStr};5use jrsonnet_types::ValType;67use crate::{8 error::{Error::*, LocError},9 function::FuncVal,10 gc::{GcHashMap, TraceBox},11 stdlib::manifest::{12 manifest_json_ex, manifest_yaml_ex, ManifestJsonOptions, ManifestType, ManifestYamlOptions,13 },14 throw,15 typed::BoundedUsize,16 ObjValue, Result, State, Unbound, WeakObjValue,17};1819pub trait ThunkValue: Trace {20 type Output;21 fn get(self: Box<Self>, s: State) -> Result<Self::Output>;22}2324#[derive(Trace)]25enum ThunkInner<T: Trace> {26 Computed(T),27 Errored(LocError),28 Waiting(TraceBox<dyn ThunkValue<Output = T>>),29 Pending,30}3132#[allow(clippy::module_name_repetitions)]33#[derive(Clone, Trace)]34pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);3536impl<T> Thunk<T>37where38 T: Clone + Trace,39{40 pub fn new(f: TraceBox<dyn ThunkValue<Output = T>>) -> Self {41 Self(Cc::new(RefCell::new(ThunkInner::Waiting(f))))42 }43 pub fn evaluated(val: T) -> Self {44 Self(Cc::new(RefCell::new(ThunkInner::Computed(val))))45 }46 pub fn force(&self, s: State) -> Result<()> {47 self.evaluate(s)?;48 Ok(())49 }50 pub fn evaluate(&self, s: State) -> Result<T> {51 match &*self.0.borrow() {52 ThunkInner::Computed(v) => return Ok(v.clone()),53 ThunkInner::Errored(e) => return Err(e.clone()),54 ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),55 ThunkInner::Waiting(..) => (),56 };57 let value = if let ThunkInner::Waiting(value) =58 std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)59 {60 value61 } else {62 unreachable!()63 };64 let new_value = match value.0.get(s) {65 Ok(v) => v,66 Err(e) => {67 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());68 return Err(e);69 }70 };71 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());72 Ok(new_value)73 }74}7576type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);7778#[derive(Trace, Clone)]79pub struct CachedUnbound<I, T>80where81 I: Unbound<Bound = T>,82 T: Trace,83{84 cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,85 value: I,86}87impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {88 pub fn new(value: I) -> Self {89 Self {90 cache: Cc::new(RefCell::new(GcHashMap::new())),91 value,92 }93 }94}95impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {96 type Bound = T;97 fn bind(&self, s: State, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {98 let cache_key = (99 sup.as_ref().map(|s| s.clone().downgrade()),100 this.as_ref().map(|t| t.clone().downgrade()),101 );102 {103 if let Some(t) = self.cache.borrow().get(&cache_key) {104 return Ok(t.clone());105 }106 }107 let bound = self.value.bind(s, sup, this)?;108109 {110 let mut cache = self.cache.borrow_mut();111 cache.insert(cache_key, bound.clone());112 }113114 Ok(bound)115 }116}117118impl<T: Debug + Trace> Debug for Thunk<T> {119 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {120 write!(f, "Lazy")121 }122}123impl<T: Trace> PartialEq for Thunk<T> {124 fn eq(&self, other: &Self) -> bool {125 Cc::ptr_eq(&self.0, &other.0)126 }127}128129#[derive(Clone)]130pub enum ManifestFormat {131 YamlStream(Box<ManifestFormat>),132 Yaml {133 padding: usize,134 #[cfg(feature = "exp-preserve-order")]135 preserve_order: bool,136 },137 Json {138 padding: usize,139 #[cfg(feature = "exp-preserve-order")]140 preserve_order: bool,141 },142 ToString,143 String,144}145impl ManifestFormat {146 #[cfg(feature = "exp-preserve-order")]147 fn preserve_order(&self) -> bool {148 match self {149 ManifestFormat::YamlStream(s) => s.preserve_order(),150 ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,151 ManifestFormat::Json { preserve_order, .. } => *preserve_order,152 ManifestFormat::ToString => false,153 ManifestFormat::String => false,154 }155 }156}157158#[derive(Debug, Clone, Trace)]159pub struct Slice {160 pub(crate) inner: ArrValue,161 pub(crate) from: u32,162 pub(crate) to: u32,163 pub(crate) step: u32,164}165impl Slice {166 const fn from(&self) -> usize {167 self.from as usize168 }169 const fn to(&self) -> usize {170 self.to as usize171 }172 const fn step(&self) -> usize {173 self.step as usize174 }175 const fn len(&self) -> usize {176 // TODO: use div_ceil177 let diff = self.to() - self.from();178 let rem = diff % self.step();179 let div = diff / self.step();180181 if rem == 0 {182 div183 } else {184 div + 1185 }186 }187}188189/// Represents a Jsonnet array value.190#[derive(Debug, Clone, Trace)]191// may contrain other ArrValue192#[trace(tracking(force))]193pub enum ArrValue {194 /// Layout optimized byte array.195 Bytes(#[trace(skip)] IBytes),196 /// Every element is lazy evaluated.197 Lazy(Cc<Vec<Thunk<Val>>>),198 /// Every field is already evaluated.199 Eager(Cc<Vec<Val>>),200 /// Concatenation of two arrays of any kind.201 Extended(Box<(Self, Self)>),202 /// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.203 /// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.204 Range(i32, i32),205 /// Sliced array view.206 Slice(Box<Slice>),207 /// Reversed array view.208 /// Returned by `std.reverse(other)` call209 Reversed(Box<Self>),210}211212#[cfg(target_pointer_width = "64")]213static_assertions::assert_eq_size!(ArrValue, [u8; 16]);214215impl ArrValue {216 pub fn new_eager() -> Self {217 Self::Eager(Cc::new(Vec::new()))218 }219 pub fn empty() -> Self {220 Self::new_range(0, 0)221 }222223 /// # Panics224 /// If a > b225 #[inline]226 pub fn new_range(a: i32, b: i32) -> Self {227 assert!(a <= b);228 Self::Range(a, b)229 }230231 /// # Panics232 /// If passed numbers are incorrect233 #[must_use]234 pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {235 let len = self.len();236 let from = from.unwrap_or(0);237 let to = to.unwrap_or(len).min(len);238 let step = step.unwrap_or(1);239 assert!(from < to);240 assert!(step > 0);241242 Self::Slice(Box::new(Slice {243 inner: self,244 from: from as u32,245 to: to as u32,246 step: step as u32,247 }))248 }249250 /// Array length.251 pub fn len(&self) -> usize {252 match self {253 Self::Bytes(i) => i.len(),254 Self::Lazy(l) => l.len(),255 Self::Eager(e) => e.len(),256 Self::Extended(v) => v.0.len() + v.1.len(),257 Self::Range(a, b) => a.abs_diff(*b) as usize + 1,258 Self::Reversed(i) => i.len(),259 Self::Slice(s) => s.len(),260 }261 }262263 /// Is array contains no elements?264 pub fn is_empty(&self) -> bool {265 self.len() == 0266 }267268 /// Get array element by index, evaluating it, if it is lazy.269 ///270 /// Returns `None` on out-of-bounds condition.271 pub fn get(&self, s: State, index: usize) -> Result<Option<Val>> {272 match self {273 Self::Bytes(i) => i274 .get(index)275 .map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),276 Self::Lazy(vec) => {277 if let Some(v) = vec.get(index) {278 Ok(Some(v.evaluate(s)?))279 } else {280 Ok(None)281 }282 }283 Self::Eager(vec) => Ok(vec.get(index).cloned()),284 Self::Extended(v) => {285 let a_len = v.0.len();286 if a_len > index {287 v.0.get(s, index)288 } else {289 v.1.get(s, index - a_len)290 }291 }292 Self::Range(a, _) => {293 if index >= self.len() {294 return Ok(None);295 }296 Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))297 }298 Self::Reversed(v) => {299 let len = v.len();300 if index >= len {301 return Ok(None);302 }303 v.get(s, len - index - 1)304 }305 Self::Slice(v) => {306 let index = v.from() + index * v.step();307 if index >= v.to() {308 return Ok(None);309 }310 v.inner.get(s, index)311 }312 }313 }314315 /// Get array element by index, without evaluation.316 ///317 /// Returns `None` on out-of-bounds condition.318 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {319 match self {320 Self::Bytes(i) => i321 .get(index)322 .map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),323 Self::Lazy(vec) => vec.get(index).cloned(),324 Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),325 Self::Extended(v) => {326 let a_len = v.0.len();327 if a_len > index {328 v.0.get_lazy(index)329 } else {330 v.1.get_lazy(index - a_len)331 }332 }333 Self::Range(a, _) => {334 if index >= self.len() {335 return None;336 }337 Some(Thunk::evaluated(Val::Num(338 ((*a as isize) + index as isize) as f64,339 )))340 }341 Self::Reversed(v) => {342 let len = v.len();343 if index >= len {344 return None;345 }346 v.get_lazy(len - index - 1)347 }348 Self::Slice(s) => {349 let index = s.from() + index * s.step();350 if index >= s.to() {351 return None;352 }353 s.inner.get_lazy(index)354 }355 }356 }357358 /// Evaluate all array elements, returning new array.359 pub fn evaluated(&self, s: State) -> Result<Cc<Vec<Val>>> {360 Ok(match self {361 Self::Bytes(i) => {362 let mut out = Vec::with_capacity(i.len());363 for v in i.iter() {364 out.push(Val::Num(f64::from(*v)));365 }366 Cc::new(out)367 }368 Self::Lazy(vec) => {369 let mut out = Vec::with_capacity(vec.len());370 for item in vec.iter() {371 out.push(item.evaluate(s.clone())?);372 }373 Cc::new(out)374 }375 Self::Eager(vec) => vec.clone(),376 Self::Extended(_v) => {377 let mut out = Vec::with_capacity(self.len());378 for item in self.iter(s) {379 out.push(item?);380 }381 Cc::new(out)382 }383 Self::Range(a, b) => {384 let mut out = Vec::with_capacity(self.len());385 for i in *a..*b {386 out.push(Val::Num(f64::from(i)));387 }388 Cc::new(out)389 }390 Self::Reversed(r) => {391 let mut r = r.evaluated(s)?;392 Cc::update_with(&mut r, |v| v.reverse());393 r394 }395 Self::Slice(v) => {396 let mut out = Vec::with_capacity(v.inner.len());397 for v in v398 .inner399 .iter_lazy()400 .skip(v.from())401 .take(v.to() - v.from())402 .step_by(v.step())403 {404 out.push(v.evaluate(s.clone())?);405 }406 Cc::new(out)407 }408 })409 }410411 /// Iterate over elements, evaluating them.412 pub fn iter(&self, s: State) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {413 (0..self.len()).map(move |idx| match self {414 Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),415 Self::Lazy(l) => l[idx].evaluate(s.clone()),416 Self::Eager(e) => Ok(e[idx].clone()),417 Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {418 self.get(s.clone(), idx).map(|e| e.expect("idx < len"))419 }420 })421 }422423 /// Iterate over elements, returning lazy values.424 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {425 (0..self.len()).map(move |idx| match self {426 Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),427 Self::Lazy(l) => l[idx].clone(),428 Self::Eager(e) => Thunk::evaluated(e[idx].clone()),429 Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {430 self.get_lazy(idx).expect("idx < len")431 }432 })433 }434435 /// Return a reversed view on current array.436 #[must_use]437 pub fn reversed(self) -> Self {438 Self::Reversed(Box::new(self))439 }440441 /// Return a new array, produced by passing every element of current array to specified callback function.442 pub fn map(self, s: State, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {443 let mut out = Vec::with_capacity(self.len());444445 for value in self.iter(s) {446 out.push(mapper(value?)?);447 }448449 Ok(Self::Eager(Cc::new(out)))450 }451452 /// Return a new array, produced from current array by removing every value, for which specified callback function returns false.453 pub fn filter(self, s: State, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {454 let mut out = Vec::with_capacity(self.len());455456 for value in self.iter(s) {457 let value = value?;458 if filter(&value)? {459 out.push(value);460 }461 }462463 Ok(Self::Eager(Cc::new(out)))464 }465466 pub fn ptr_eq(a: &Self, b: &Self) -> bool {467 match (a, b) {468 (Self::Lazy(a), Self::Lazy(b)) => Cc::ptr_eq(a, b),469 (Self::Eager(a), Self::Eager(b)) => Cc::ptr_eq(a, b),470 _ => false,471 }472 }473}474475impl From<Vec<Thunk<Val>>> for ArrValue {476 fn from(v: Vec<Thunk<Val>>) -> Self {477 Self::Lazy(Cc::new(v))478 }479}480481impl From<Vec<Val>> for ArrValue {482 fn from(v: Vec<Val>) -> Self {483 Self::Eager(Cc::new(v))484 }485}486487/// Represents a Jsonnet value, which can be spliced or indexed (string or array).488#[allow(clippy::module_name_repetitions)]489pub enum IndexableVal {490 /// String.491 Str(IStr),492 /// Array.493 Arr(ArrValue),494}495impl IndexableVal {496 /// Slice the value.497 ///498 /// # Implementation499 ///500 /// For strings, will create a copy of specified interval.501 ///502 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.503 pub fn slice(504 self,505 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,506 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,507 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,508 ) -> Result<Self> {509 match &self {510 IndexableVal::Str(s) => {511 let index = index.as_deref().copied().unwrap_or(0);512 let end = end.as_deref().copied().unwrap_or(usize::MAX);513 let step = step.as_deref().copied().unwrap_or(1);514515 if index >= end {516 return Ok(Self::Str("".into()));517 }518519 Ok(Self::Str(520 (s.chars()521 .skip(index)522 .take(end - index)523 .step_by(step)524 .collect::<String>())525 .into(),526 ))527 }528 IndexableVal::Arr(arr) => {529 let index = index.as_deref().copied().unwrap_or(0);530 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());531 let step = step.as_deref().copied().unwrap_or(1);532533 if index >= end {534 return Ok(Self::Arr(ArrValue::new_eager()));535 }536537 Ok(Self::Arr(ArrValue::Slice(Box::new(Slice {538 inner: arr.clone(),539 from: index as u32,540 to: end as u32,541 step: step as u32,542 }))))543 }544 }545 }546}547548/// Represents any valid Jsonnet value.549#[derive(Debug, Clone, Trace)]550pub enum Val {551 /// Represents a Jsonnet boolean.552 Bool(bool),553 /// Represents a Jsonnet null value.554 Null,555 /// Represents a Jsonnet string.556 Str(IStr),557 /// Represents a Jsonnet number.558 /// Should be finite, and not NaN559 /// This restriction isn't enforced by enum, as enum field can't be marked as private560 Num(f64),561 /// Represents a Jsonnet array.562 Arr(ArrValue),563 /// Represents a Jsonnet object.564 Obj(ObjValue),565 /// Represents a Jsonnet function.566 Func(FuncVal),567}568569impl From<IndexableVal> for Val {570 fn from(v: IndexableVal) -> Self {571 match v {572 IndexableVal::Str(s) => Self::Str(s),573 IndexableVal::Arr(a) => Self::Arr(a),574 }575 }576}577578// Broken between stable and nightly, as there is new layout size optimization579// #[cfg(target_pointer_width = "64")]580// static_assertions::assert_eq_size!(Val, [u8; 24]);581582impl Val {583 pub const fn as_bool(&self) -> Option<bool> {584 match self {585 Self::Bool(v) => Some(*v),586 _ => None,587 }588 }589 pub const fn as_null(&self) -> Option<()> {590 match self {591 Self::Null => Some(()),592 _ => None,593 }594 }595 pub fn as_str(&self) -> Option<IStr> {596 match self {597 Self::Str(s) => Some(s.clone()),598 _ => None,599 }600 }601 pub const fn as_num(&self) -> Option<f64> {602 match self {603 Self::Num(n) => Some(*n),604 _ => None,605 }606 }607 pub fn as_arr(&self) -> Option<ArrValue> {608 match self {609 Self::Arr(a) => Some(a.clone()),610 _ => None,611 }612 }613 pub fn as_obj(&self) -> Option<ObjValue> {614 match self {615 Self::Obj(o) => Some(o.clone()),616 _ => None,617 }618 }619 pub fn as_func(&self) -> Option<FuncVal> {620 match self {621 Self::Func(f) => Some(f.clone()),622 _ => None,623 }624 }625626 /// Creates `Val::Num` after checking for numeric overflow.627 /// As numbers are `f64`, we can just check for their finity.628 pub fn new_checked_num(num: f64) -> Result<Self> {629 if num.is_finite() {630 Ok(Self::Num(num))631 } else {632 throw!("overflow")633 }634 }635636 pub const fn value_type(&self) -> ValType {637 match self {638 Self::Str(..) => ValType::Str,639 Self::Num(..) => ValType::Num,640 Self::Arr(..) => ValType::Arr,641 Self::Obj(..) => ValType::Obj,642 Self::Bool(_) => ValType::Bool,643 Self::Null => ValType::Null,644 Self::Func(..) => ValType::Func,645 }646 }647648 pub fn to_string(&self, s: State) -> Result<IStr> {649 Ok(match self {650 Self::Bool(true) => "true".into(),651 Self::Bool(false) => "false".into(),652 Self::Null => "null".into(),653 Self::Str(s) => s.clone(),654 v => manifest_json_ex(655 s,656 v,657 &ManifestJsonOptions {658 padding: "",659 mtype: ManifestType::ToString,660 newline: "\n",661 key_val_sep: ": ",662 #[cfg(feature = "exp-preserve-order")]663 preserve_order: false,664 },665 )?666 .into(),667 })668 }669670 /// Expects value to be object, outputs (key, manifested value) pairs671 pub fn manifest_multi(&self, s: State, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {672 let obj = match self {673 Self::Obj(obj) => obj,674 _ => throw!(MultiManifestOutputIsNotAObject),675 };676 let keys = obj.fields(677 #[cfg(feature = "exp-preserve-order")]678 ty.preserve_order(),679 );680 let mut out = Vec::with_capacity(keys.len());681 for key in keys {682 let value = obj683 .get(s.clone(), key.clone())?684 .expect("item in object")685 .manifest(s.clone(), ty)?;686 out.push((key, value));687 }688 Ok(out)689 }690691 /// Expects value to be array, outputs manifested values692 pub fn manifest_stream(&self, s: State, ty: &ManifestFormat) -> Result<Vec<IStr>> {693 let arr = match self {694 Self::Arr(a) => a,695 _ => throw!(StreamManifestOutputIsNotAArray),696 };697 let mut out = Vec::with_capacity(arr.len());698 for i in arr.iter(s.clone()) {699 out.push(i?.manifest(s.clone(), ty)?);700 }701 Ok(out)702 }703704 pub fn manifest(&self, s: State, ty: &ManifestFormat) -> Result<IStr> {705 Ok(match ty {706 ManifestFormat::YamlStream(format) => {707 let arr = match self {708 Self::Arr(a) => a,709 _ => throw!(StreamManifestOutputIsNotAArray),710 };711 let mut out = String::new();712713 match format as &ManifestFormat {714 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),715 ManifestFormat::String => throw!(StreamManifestCannotNestString),716 _ => {}717 };718719 if !arr.is_empty() {720 for v in arr.iter(s.clone()) {721 out.push_str("---\n");722 out.push_str(&v?.manifest(s.clone(), format)?);723 out.push('\n');724 }725 out.push_str("...");726 }727728 out.into()729 }730 ManifestFormat::Yaml {731 padding,732 #[cfg(feature = "exp-preserve-order")]733 preserve_order,734 } => self.to_yaml(735 s,736 *padding,737 #[cfg(feature = "exp-preserve-order")]738 *preserve_order,739 )?,740 ManifestFormat::Json {741 padding,742 #[cfg(feature = "exp-preserve-order")]743 preserve_order,744 } => self.to_json(745 s,746 *padding,747 #[cfg(feature = "exp-preserve-order")]748 *preserve_order,749 )?,750 ManifestFormat::ToString => self.to_string(s)?,751 ManifestFormat::String => match self {752 Self::Str(s) => s.clone(),753 _ => throw!(StringManifestOutputIsNotAString),754 },755 })756 }757758 /// For manifestification759 pub fn to_json(760 &self,761 s: State,762 padding: usize,763 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,764 ) -> Result<IStr> {765 manifest_json_ex(766 s,767 self,768 &ManifestJsonOptions {769 padding: &" ".repeat(padding),770 mtype: if padding == 0 {771 ManifestType::Minify772 } else {773 ManifestType::Manifest774 },775 newline: "\n",776 key_val_sep: ": ",777 #[cfg(feature = "exp-preserve-order")]778 preserve_order,779 },780 )781 .map(Into::into)782 }783784 /// Calls `std.manifestJson`785 pub fn to_std_json(786 &self,787 s: State,788 padding: usize,789 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,790 ) -> Result<Rc<str>> {791 manifest_json_ex(792 s,793 self,794 &ManifestJsonOptions {795 padding: &" ".repeat(padding),796 mtype: ManifestType::Std,797 newline: "\n",798 key_val_sep: ": ",799 #[cfg(feature = "exp-preserve-order")]800 preserve_order,801 },802 )803 .map(Into::into)804 }805806 pub fn to_yaml(807 &self,808 s: State,809 padding: usize,810 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,811 ) -> Result<IStr> {812 let padding = &" ".repeat(padding);813 manifest_yaml_ex(814 s,815 self,816 &ManifestYamlOptions {817 padding,818 arr_element_padding: padding,819 quote_keys: false,820 #[cfg(feature = "exp-preserve-order")]821 preserve_order,822 },823 )824 .map(Into::into)825 }826 pub fn into_indexable(self) -> Result<IndexableVal> {827 Ok(match self {828 Val::Str(s) => IndexableVal::Str(s),829 Val::Arr(arr) => IndexableVal::Arr(arr),830 _ => throw!(ValueIsNotIndexable(self.value_type())),831 })832 }833}834835const fn is_function_like(val: &Val) -> bool {836 matches!(val, Val::Func(_))837}838839/// Native implementation of `std.primitiveEquals`840pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {841 Ok(match (val_a, val_b) {842 (Val::Bool(a), Val::Bool(b)) => a == b,843 (Val::Null, Val::Null) => true,844 (Val::Str(a), Val::Str(b)) => a == b,845 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,846 (Val::Arr(_), Val::Arr(_)) => {847 throw!("primitiveEquals operates on primitive types, got array")848 }849 (Val::Obj(_), Val::Obj(_)) => {850 throw!("primitiveEquals operates on primitive types, got object")851 }852 (a, b) if is_function_like(a) && is_function_like(b) => {853 throw!("cannot test equality of functions")854 }855 (_, _) => false,856 })857}858859/// Native implementation of `std.equals`860pub fn equals(s: State, val_a: &Val, val_b: &Val) -> Result<bool> {861 if val_a.value_type() != val_b.value_type() {862 return Ok(false);863 }864 match (val_a, val_b) {865 (Val::Arr(a), Val::Arr(b)) => {866 if ArrValue::ptr_eq(a, b) {867 return Ok(true);868 }869 if a.len() != b.len() {870 return Ok(false);871 }872 for (a, b) in a.iter(s.clone()).zip(b.iter(s.clone())) {873 if !equals(s.clone(), &a?, &b?)? {874 return Ok(false);875 }876 }877 Ok(true)878 }879 (Val::Obj(a), Val::Obj(b)) => {880 if ObjValue::ptr_eq(a, b) {881 return Ok(true);882 }883 let fields = a.fields(884 #[cfg(feature = "exp-preserve-order")]885 false,886 );887 if fields888 != b.fields(889 #[cfg(feature = "exp-preserve-order")]890 false,891 ) {892 return Ok(false);893 }894 for field in fields {895 if !equals(896 s.clone(),897 &a.get(s.clone(), field.clone())?.expect("field exists"),898 &b.get(s.clone(), field)?.expect("field exists"),899 )? {900 return Ok(false);901 }902 }903 Ok(true)904 }905 (a, b) => Ok(primitive_equals(a, b)?),906 }907}crates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -1,7 +1,7 @@
use jrsonnet_evaluator::{
error::Result,
function::{builtin, FuncVal},
- throw_runtime,
+ throw,
typed::{Any, BoundedUsize, Typed, VecVal},
val::{equals, ArrValue, IndexableVal},
IStr, State, Val,
@@ -43,7 +43,7 @@
match func.evaluate_simple(s.clone(), &(c.to_string(),))? {
Val::Str(o) => out.push_str(&o),
Val::Null => continue,
- _ => throw_runtime!("in std.join all items should be strings"),
+ _ => throw!("in std.join all items should be strings"),
};
}
Ok(IndexableVal::Str(out.into()))
@@ -59,7 +59,7 @@
}
}
Val::Null => continue,
- _ => throw_runtime!("in std.join all items should be arrays"),
+ _ => throw!("in std.join all items should be arrays"),
};
}
Ok(IndexableVal::Arr(out.into()))
@@ -128,7 +128,7 @@
} else if matches!(item, Val::Null) {
continue;
} else {
- throw_runtime!("in std.join all items should be arrays");
+ throw!("in std.join all items should be arrays");
}
}
@@ -149,7 +149,7 @@
} else if matches!(item, Val::Null) {
continue;
} else {
- throw_runtime!("in std.join all items should be strings");
+ throw!("in std.join all items should be strings");
}
}
crates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -8,7 +8,7 @@
error::{Error::*, Result},
function::{builtin::Builtin, ArgLike, CallLocation, FuncVal, TlaArg},
gc::{GcHashMap, TraceBox},
- tb, throw_runtime,
+ tb, throw,
trace::PathResolver,
typed::{Any, Either, Either2, Either4, VecVal, M1},
val::{equals, ArrValue},
@@ -500,7 +500,7 @@
true
}
}
- _ => throw_runtime!("both arguments should be of the same type"),
+ _ => throw!("both arguments should be of the same type"),
})
}
@@ -534,7 +534,7 @@
true
}
}
- _ => throw_runtime!("both arguments should be of the same type"),
+ _ => throw!("both arguments should be of the same type"),
})
}
crates/jrsonnet-stdlib/src/sort.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/sort.rs
+++ b/crates/jrsonnet-stdlib/src/sort.rs
@@ -1,7 +1,7 @@
use jrsonnet_evaluator::{
error::Result,
function::{builtin, FuncVal},
- throw_runtime,
+ throw,
typed::Any,
val::ArrValue,
State, Val,
@@ -41,9 +41,9 @@
(Val::Num(_), SortKeyType::Unknown) => sort_type = SortKeyType::Number,
(Val::Str(_), SortKeyType::String) | (Val::Num(_), SortKeyType::Number) => {}
(Val::Str(_) | Val::Num(_), _) => {
- throw_runtime!("sort elements should have the same types")
+ throw!("sort elements should have the same types")
}
- _ => throw_runtime!("sort key should either be a string or a number"),
+ _ => throw!("sort key should either be a string or a number"),
}
}
Ok(sort_type)
tests/tests/common.rsdiffbeforeafterboth--- a/tests/tests/common.rs
+++ b/tests/tests/common.rs
@@ -1,7 +1,7 @@
use jrsonnet_evaluator::{
error::Result,
function::{builtin, FuncVal},
- throw_runtime, ObjValueBuilder, State, Thunk, Val,
+ throw, ObjValueBuilder, State, Thunk, Val,
};
use jrsonnet_stdlib::StateExt;
@@ -11,7 +11,7 @@
let a = &$a;
let b = &$b;
if a != b {
- ::jrsonnet_evaluator::throw_runtime!("assertion failed: a != b\na={:#?}\nb={:#?}", a, b)
+ ::jrsonnet_evaluator::throw!("assertion failed: a != b\na={:#?}\nb={:#?}", a, b)
}
}};
}
@@ -20,7 +20,7 @@
macro_rules! ensure {
($v:expr $(,)?) => {
if !$v {
- ::jrsonnet_evaluator::throw_runtime!("assertion failed: {}", stringify!($v))
+ ::jrsonnet_evaluator::throw!("assertion failed: {}", stringify!($v))
}
};
}
@@ -29,7 +29,7 @@
macro_rules! ensure_val_eq {
($s:expr, $a:expr, $b:expr) => {{
if !::jrsonnet_evaluator::val::equals($s.clone(), &$a.clone(), &$b.clone())? {
- ::jrsonnet_evaluator::throw_runtime!(
+ ::jrsonnet_evaluator::throw!(
"assertion failed: a != b\na={:#?}\nb={:#?}",
$a.to_json(
$s.clone(),
@@ -52,7 +52,7 @@
fn assert_throw(s: State, lazy: Thunk<Val>, message: String) -> Result<bool> {
match lazy.evaluate(s) {
Ok(_) => {
- throw_runtime!("expected argument to throw on evaluation, but it returned instead")
+ throw!("expected argument to throw on evaluation, but it returned instead")
}
Err(e) => {
let error = format!("{}", e.error());
tests/tests/sanity.rsdiffbeforeafterboth--- a/tests/tests/sanity.rs
+++ b/tests/tests/sanity.rs
@@ -1,4 +1,4 @@
-use jrsonnet_evaluator::{error::Result, throw_runtime, State, Val};
+use jrsonnet_evaluator::{error::Result, throw, State, Val};
use jrsonnet_stdlib::StateExt;
mod common;
@@ -23,7 +23,7 @@
{
let e = match s.evaluate_snippet("snip".to_owned(), "assert 1 == 2: 'fail'; null") {
- Ok(_) => throw_runtime!("assertion should fail"),
+ Ok(_) => throw!("assertion should fail"),
Err(e) => e,
};
let e = s.stringify_err(&e);
@@ -31,7 +31,7 @@
}
{
let e = match s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 2)") {
- Ok(_) => throw_runtime!("assertion should fail"),
+ Ok(_) => throw!("assertion should fail"),
Err(e) => e,
};
let e = s.stringify_err(&e);