difftreelog
style use let-else
in: master
7 files changed
crates/jrsonnet-evaluator/src/evaluate/destructure.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/destructure.rs
@@ -45,9 +45,8 @@
fn get(self: Box<Self>) -> Result<Self::Output> {
let v = self.parent.evaluate()?;
- let arr = match v {
- Val::Arr(a) => a,
- _ => throw!("expected array"),
+ let Val::Arr(arr) = v else {
+ throw!("expected array");
};
if !self.has_rest {
if arr.len() != self.min_len {
@@ -176,9 +175,8 @@
fn get(self: Box<Self>) -> Result<Self::Output> {
let v = self.parent.evaluate()?;
- let obj = match v {
- Val::Obj(o) => o,
- _ => throw!("expected object"),
+ let Val::Obj(obj) = v else {
+ throw!("expected object");
};
for field in &self.field_names {
if !obj.has_field_ex(field.clone(), true) {
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -162,9 +162,7 @@
}
let name = evaluate_field_name(ctx.clone(), name)?;
- let name = if let Some(name) = name {
- name
- } else {
+ let Some(name) = name else {
continue;
};
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -344,10 +344,10 @@
let mut file_cache = self.file_cache();
let mut file = file_cache.raw_entry_mut().from_key(&path);
- let file = match file {
- RawEntryMut::Occupied(ref mut d) => d.get_mut(),
- RawEntryMut::Vacant(_) => unreachable!("this file was just here!"),
+ let RawEntryMut::Occupied(file) = &mut file else {
+ unreachable!("this file was just here!")
};
+ let file = file.get_mut();
file.evaluating = false;
match res {
Ok(v) => {
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, Unbound, WeakObjValue,17};1819pub trait ThunkValue: Trace {20 type Output;21 fn get(self: Box<Self>) -> 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) -> Result<()> {47 self.evaluate()?;48 Ok(())49 }50 pub fn evaluate(&self) -> 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() {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, 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(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, Trace)]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, 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()?))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(index)288 } else {289 v.1.get(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(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(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) -> 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()?);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() {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()?;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()?);405 }406 Cc::new(out)407 }408 })409 }410411 /// Iterate over elements, evaluating them.412 pub fn iter(&self) -> 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(),416 Self::Eager(e) => Ok(e[idx].clone()),417 Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {418 self.get(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, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {443 let mut out = Vec::with_capacity(self.len());444445 for value in self.iter() {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, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {454 let mut out = Vec::with_capacity(self.len());455456 for value in self.iter() {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) -> 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 v,656 &ManifestJsonOptions {657 padding: "",658 mtype: ManifestType::ToString,659 newline: "\n",660 key_val_sep: ": ",661 #[cfg(feature = "exp-preserve-order")]662 preserve_order: false,663 },664 )?665 .into(),666 })667 }668669 /// Expects value to be object, outputs (key, manifested value) pairs670 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {671 let obj = match self {672 Self::Obj(obj) => obj,673 _ => throw!(MultiManifestOutputIsNotAObject),674 };675 let keys = obj.fields(676 #[cfg(feature = "exp-preserve-order")]677 ty.preserve_order(),678 );679 let mut out = Vec::with_capacity(keys.len());680 for key in keys {681 let value = obj682 .get(key.clone())?683 .expect("item in object")684 .manifest(ty)?;685 out.push((key, value));686 }687 Ok(out)688 }689690 /// Expects value to be array, outputs manifested values691 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {692 let arr = match self {693 Self::Arr(a) => a,694 _ => throw!(StreamManifestOutputIsNotAArray),695 };696 let mut out = Vec::with_capacity(arr.len());697 for i in arr.iter() {698 out.push(i?.manifest(ty)?);699 }700 Ok(out)701 }702703 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {704 Ok(match ty {705 ManifestFormat::YamlStream(format) => {706 let arr = match self {707 Self::Arr(a) => a,708 _ => throw!(StreamManifestOutputIsNotAArray),709 };710 let mut out = String::new();711712 match format as &ManifestFormat {713 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),714 ManifestFormat::String => throw!(StreamManifestCannotNestString),715 _ => {}716 };717718 if !arr.is_empty() {719 for v in arr.iter() {720 out.push_str("---\n");721 out.push_str(&v?.manifest(format)?);722 out.push('\n');723 }724 out.push_str("...");725 }726727 out.into()728 }729 ManifestFormat::Yaml {730 padding,731 #[cfg(feature = "exp-preserve-order")]732 preserve_order,733 } => self.to_yaml(734 *padding,735 #[cfg(feature = "exp-preserve-order")]736 *preserve_order,737 )?,738 ManifestFormat::Json {739 padding,740 #[cfg(feature = "exp-preserve-order")]741 preserve_order,742 } => self.to_json(743 *padding,744 #[cfg(feature = "exp-preserve-order")]745 *preserve_order,746 )?,747 ManifestFormat::ToString => self.to_string()?,748 ManifestFormat::String => match self {749 Self::Str(s) => s.clone(),750 _ => throw!(StringManifestOutputIsNotAString),751 },752 })753 }754755 /// For manifestification756 pub fn to_json(757 &self,758 padding: usize,759 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,760 ) -> Result<IStr> {761 manifest_json_ex(762 self,763 &ManifestJsonOptions {764 padding: &" ".repeat(padding),765 mtype: if padding == 0 {766 ManifestType::Minify767 } else {768 ManifestType::Manifest769 },770 newline: "\n",771 key_val_sep: ": ",772 #[cfg(feature = "exp-preserve-order")]773 preserve_order,774 },775 )776 .map(Into::into)777 }778779 /// Calls `std.manifestJson`780 pub fn to_std_json(781 &self,782 padding: usize,783 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,784 ) -> Result<Rc<str>> {785 manifest_json_ex(786 self,787 &ManifestJsonOptions {788 padding: &" ".repeat(padding),789 mtype: ManifestType::Std,790 newline: "\n",791 key_val_sep: ": ",792 #[cfg(feature = "exp-preserve-order")]793 preserve_order,794 },795 )796 .map(Into::into)797 }798799 pub fn to_yaml(800 &self,801 padding: usize,802 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,803 ) -> Result<IStr> {804 let padding = &" ".repeat(padding);805 manifest_yaml_ex(806 self,807 &ManifestYamlOptions {808 padding,809 arr_element_padding: padding,810 quote_keys: false,811 #[cfg(feature = "exp-preserve-order")]812 preserve_order,813 },814 )815 .map(Into::into)816 }817 pub fn into_indexable(self) -> Result<IndexableVal> {818 Ok(match self {819 Val::Str(s) => IndexableVal::Str(s),820 Val::Arr(arr) => IndexableVal::Arr(arr),821 _ => throw!(ValueIsNotIndexable(self.value_type())),822 })823 }824}825826const fn is_function_like(val: &Val) -> bool {827 matches!(val, Val::Func(_))828}829830/// Native implementation of `std.primitiveEquals`831pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {832 Ok(match (val_a, val_b) {833 (Val::Bool(a), Val::Bool(b)) => a == b,834 (Val::Null, Val::Null) => true,835 (Val::Str(a), Val::Str(b)) => a == b,836 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,837 (Val::Arr(_), Val::Arr(_)) => {838 throw!("primitiveEquals operates on primitive types, got array")839 }840 (Val::Obj(_), Val::Obj(_)) => {841 throw!("primitiveEquals operates on primitive types, got object")842 }843 (a, b) if is_function_like(a) && is_function_like(b) => {844 throw!("cannot test equality of functions")845 }846 (_, _) => false,847 })848}849850/// Native implementation of `std.equals`851pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {852 if val_a.value_type() != val_b.value_type() {853 return Ok(false);854 }855 match (val_a, val_b) {856 (Val::Arr(a), Val::Arr(b)) => {857 if ArrValue::ptr_eq(a, b) {858 return Ok(true);859 }860 if a.len() != b.len() {861 return Ok(false);862 }863 for (a, b) in a.iter().zip(b.iter()) {864 if !equals(&a?, &b?)? {865 return Ok(false);866 }867 }868 Ok(true)869 }870 (Val::Obj(a), Val::Obj(b)) => {871 if ObjValue::ptr_eq(a, b) {872 return Ok(true);873 }874 let fields = a.fields(875 #[cfg(feature = "exp-preserve-order")]876 false,877 );878 if fields879 != b.fields(880 #[cfg(feature = "exp-preserve-order")]881 false,882 ) {883 return Ok(false);884 }885 for field in fields {886 if !equals(887 &a.get(field.clone())?.expect("field exists"),888 &b.get(field)?.expect("field exists"),889 )? {890 return Ok(false);891 }892 }893 Ok(true)894 }895 (a, b) => Ok(primitive_equals(a, b)?),896 }897}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, Unbound, WeakObjValue,17};1819pub trait ThunkValue: Trace {20 type Output;21 fn get(self: Box<Self>) -> 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) -> Result<()> {47 self.evaluate()?;48 Ok(())49 }50 pub fn evaluate(&self) -> 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 ThunkInner::Waiting(value) = std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending) else {58 unreachable!();59 };60 let new_value = match value.0.get() {61 Ok(v) => v,62 Err(e) => {63 *self.0.borrow_mut() = ThunkInner::Errored(e.clone());64 return Err(e);65 }66 };67 *self.0.borrow_mut() = ThunkInner::Computed(new_value.clone());68 Ok(new_value)69 }70}7172type CacheKey = (Option<WeakObjValue>, Option<WeakObjValue>);7374#[derive(Trace, Clone)]75pub struct CachedUnbound<I, T>76where77 I: Unbound<Bound = T>,78 T: Trace,79{80 cache: Cc<RefCell<GcHashMap<CacheKey, T>>>,81 value: I,82}83impl<I: Unbound<Bound = T>, T: Trace> CachedUnbound<I, T> {84 pub fn new(value: I) -> Self {85 Self {86 cache: Cc::new(RefCell::new(GcHashMap::new())),87 value,88 }89 }90}91impl<I: Unbound<Bound = T>, T: Clone + Trace> Unbound for CachedUnbound<I, T> {92 type Bound = T;93 fn bind(&self, sup: Option<ObjValue>, this: Option<ObjValue>) -> Result<T> {94 let cache_key = (95 sup.as_ref().map(|s| s.clone().downgrade()),96 this.as_ref().map(|t| t.clone().downgrade()),97 );98 {99 if let Some(t) = self.cache.borrow().get(&cache_key) {100 return Ok(t.clone());101 }102 }103 let bound = self.value.bind(sup, this)?;104105 {106 let mut cache = self.cache.borrow_mut();107 cache.insert(cache_key, bound.clone());108 }109110 Ok(bound)111 }112}113114impl<T: Debug + Trace> Debug for Thunk<T> {115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {116 write!(f, "Lazy")117 }118}119impl<T: Trace> PartialEq for Thunk<T> {120 fn eq(&self, other: &Self) -> bool {121 Cc::ptr_eq(&self.0, &other.0)122 }123}124125#[derive(Clone, Trace)]126pub enum ManifestFormat {127 YamlStream(Box<ManifestFormat>),128 Yaml {129 padding: usize,130 #[cfg(feature = "exp-preserve-order")]131 preserve_order: bool,132 },133 Json {134 padding: usize,135 #[cfg(feature = "exp-preserve-order")]136 preserve_order: bool,137 },138 ToString,139 String,140}141impl ManifestFormat {142 #[cfg(feature = "exp-preserve-order")]143 fn preserve_order(&self) -> bool {144 match self {145 ManifestFormat::YamlStream(s) => s.preserve_order(),146 ManifestFormat::Yaml { preserve_order, .. } => *preserve_order,147 ManifestFormat::Json { preserve_order, .. } => *preserve_order,148 ManifestFormat::ToString => false,149 ManifestFormat::String => false,150 }151 }152}153154#[derive(Debug, Clone, Trace)]155pub struct Slice {156 pub(crate) inner: ArrValue,157 pub(crate) from: u32,158 pub(crate) to: u32,159 pub(crate) step: u32,160}161impl Slice {162 const fn from(&self) -> usize {163 self.from as usize164 }165 const fn to(&self) -> usize {166 self.to as usize167 }168 const fn step(&self) -> usize {169 self.step as usize170 }171 const fn len(&self) -> usize {172 // TODO: use div_ceil173 let diff = self.to() - self.from();174 let rem = diff % self.step();175 let div = diff / self.step();176177 if rem == 0 {178 div179 } else {180 div + 1181 }182 }183}184185/// Represents a Jsonnet array value.186#[derive(Debug, Clone, Trace)]187// may contrain other ArrValue188#[trace(tracking(force))]189pub enum ArrValue {190 /// Layout optimized byte array.191 Bytes(#[trace(skip)] IBytes),192 /// Every element is lazy evaluated.193 Lazy(Cc<Vec<Thunk<Val>>>),194 /// Every field is already evaluated.195 Eager(Cc<Vec<Val>>),196 /// Concatenation of two arrays of any kind.197 Extended(Box<(Self, Self)>),198 /// Represents a integer array in form `[start, start + 1, ... end - 1, end]`.199 /// This kind of arrays is generated by `std.range(start, end)` call, and used for loops.200 Range(i32, i32),201 /// Sliced array view.202 Slice(Box<Slice>),203 /// Reversed array view.204 /// Returned by `std.reverse(other)` call205 Reversed(Box<Self>),206}207208#[cfg(target_pointer_width = "64")]209static_assertions::assert_eq_size!(ArrValue, [u8; 16]);210211impl ArrValue {212 pub fn new_eager() -> Self {213 Self::Eager(Cc::new(Vec::new()))214 }215 pub fn empty() -> Self {216 Self::new_range(0, 0)217 }218219 /// # Panics220 /// If a > b221 #[inline]222 pub fn new_range(a: i32, b: i32) -> Self {223 assert!(a <= b);224 Self::Range(a, b)225 }226227 /// # Panics228 /// If passed numbers are incorrect229 #[must_use]230 pub fn slice(self, from: Option<usize>, to: Option<usize>, step: Option<usize>) -> Self {231 let len = self.len();232 let from = from.unwrap_or(0);233 let to = to.unwrap_or(len).min(len);234 let step = step.unwrap_or(1);235 assert!(from < to);236 assert!(step > 0);237238 Self::Slice(Box::new(Slice {239 inner: self,240 from: from as u32,241 to: to as u32,242 step: step as u32,243 }))244 }245246 /// Array length.247 pub fn len(&self) -> usize {248 match self {249 Self::Bytes(i) => i.len(),250 Self::Lazy(l) => l.len(),251 Self::Eager(e) => e.len(),252 Self::Extended(v) => v.0.len() + v.1.len(),253 Self::Range(a, b) => a.abs_diff(*b) as usize + 1,254 Self::Reversed(i) => i.len(),255 Self::Slice(s) => s.len(),256 }257 }258259 /// Is array contains no elements?260 pub fn is_empty(&self) -> bool {261 self.len() == 0262 }263264 /// Get array element by index, evaluating it, if it is lazy.265 ///266 /// Returns `None` on out-of-bounds condition.267 pub fn get(&self, index: usize) -> Result<Option<Val>> {268 match self {269 Self::Bytes(i) => i270 .get(index)271 .map_or(Ok(None), |v| Ok(Some(Val::Num(f64::from(*v))))),272 Self::Lazy(vec) => {273 if let Some(v) = vec.get(index) {274 Ok(Some(v.evaluate()?))275 } else {276 Ok(None)277 }278 }279 Self::Eager(vec) => Ok(vec.get(index).cloned()),280 Self::Extended(v) => {281 let a_len = v.0.len();282 if a_len > index {283 v.0.get(index)284 } else {285 v.1.get(index - a_len)286 }287 }288 Self::Range(a, _) => {289 if index >= self.len() {290 return Ok(None);291 }292 Ok(Some(Val::Num(((*a as isize) + index as isize) as f64)))293 }294 Self::Reversed(v) => {295 let len = v.len();296 if index >= len {297 return Ok(None);298 }299 v.get(len - index - 1)300 }301 Self::Slice(v) => {302 let index = v.from() + index * v.step();303 if index >= v.to() {304 return Ok(None);305 }306 v.inner.get(index)307 }308 }309 }310311 /// Get array element by index, without evaluation.312 ///313 /// Returns `None` on out-of-bounds condition.314 pub fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {315 match self {316 Self::Bytes(i) => i317 .get(index)318 .map(|b| Thunk::evaluated(Val::Num(f64::from(*b)))),319 Self::Lazy(vec) => vec.get(index).cloned(),320 Self::Eager(vec) => vec.get(index).cloned().map(Thunk::evaluated),321 Self::Extended(v) => {322 let a_len = v.0.len();323 if a_len > index {324 v.0.get_lazy(index)325 } else {326 v.1.get_lazy(index - a_len)327 }328 }329 Self::Range(a, _) => {330 if index >= self.len() {331 return None;332 }333 Some(Thunk::evaluated(Val::Num(334 ((*a as isize) + index as isize) as f64,335 )))336 }337 Self::Reversed(v) => {338 let len = v.len();339 if index >= len {340 return None;341 }342 v.get_lazy(len - index - 1)343 }344 Self::Slice(s) => {345 let index = s.from() + index * s.step();346 if index >= s.to() {347 return None;348 }349 s.inner.get_lazy(index)350 }351 }352 }353354 /// Evaluate all array elements, returning new array.355 pub fn evaluated(&self) -> Result<Cc<Vec<Val>>> {356 Ok(match self {357 Self::Bytes(i) => {358 let mut out = Vec::with_capacity(i.len());359 for v in i.iter() {360 out.push(Val::Num(f64::from(*v)));361 }362 Cc::new(out)363 }364 Self::Lazy(vec) => {365 let mut out = Vec::with_capacity(vec.len());366 for item in vec.iter() {367 out.push(item.evaluate()?);368 }369 Cc::new(out)370 }371 Self::Eager(vec) => vec.clone(),372 Self::Extended(_v) => {373 let mut out = Vec::with_capacity(self.len());374 for item in self.iter() {375 out.push(item?);376 }377 Cc::new(out)378 }379 Self::Range(a, b) => {380 let mut out = Vec::with_capacity(self.len());381 for i in *a..*b {382 out.push(Val::Num(f64::from(i)));383 }384 Cc::new(out)385 }386 Self::Reversed(r) => {387 let mut r = r.evaluated()?;388 Cc::update_with(&mut r, |v| v.reverse());389 r390 }391 Self::Slice(v) => {392 let mut out = Vec::with_capacity(v.inner.len());393 for v in v394 .inner395 .iter_lazy()396 .skip(v.from())397 .take(v.to() - v.from())398 .step_by(v.step())399 {400 out.push(v.evaluate()?);401 }402 Cc::new(out)403 }404 })405 }406407 /// Iterate over elements, evaluating them.408 pub fn iter(&self) -> impl DoubleEndedIterator<Item = Result<Val>> + '_ {409 (0..self.len()).map(move |idx| match self {410 Self::Bytes(b) => Ok(Val::Num(f64::from(b[idx]))),411 Self::Lazy(l) => l[idx].evaluate(),412 Self::Eager(e) => Ok(e[idx].clone()),413 Self::Extended(..) | Self::Range(..) | Self::Reversed(..) | Self::Slice(..) => {414 self.get(idx).map(|e| e.expect("idx < len"))415 }416 })417 }418419 /// Iterate over elements, returning lazy values.420 pub fn iter_lazy(&self) -> impl DoubleEndedIterator<Item = Thunk<Val>> + '_ {421 (0..self.len()).map(move |idx| match self {422 Self::Bytes(b) => Thunk::evaluated(Val::Num(f64::from(b[idx]))),423 Self::Lazy(l) => l[idx].clone(),424 Self::Eager(e) => Thunk::evaluated(e[idx].clone()),425 Self::Slice(..) | Self::Extended(..) | Self::Range(..) | Self::Reversed(..) => {426 self.get_lazy(idx).expect("idx < len")427 }428 })429 }430431 /// Return a reversed view on current array.432 #[must_use]433 pub fn reversed(self) -> Self {434 Self::Reversed(Box::new(self))435 }436437 /// Return a new array, produced by passing every element of current array to specified callback function.438 pub fn map(self, mapper: impl Fn(Val) -> Result<Val>) -> Result<Self> {439 let mut out = Vec::with_capacity(self.len());440441 for value in self.iter() {442 out.push(mapper(value?)?);443 }444445 Ok(Self::Eager(Cc::new(out)))446 }447448 /// Return a new array, produced from current array by removing every value, for which specified callback function returns false.449 pub fn filter(self, filter: impl Fn(&Val) -> Result<bool>) -> Result<Self> {450 let mut out = Vec::with_capacity(self.len());451452 for value in self.iter() {453 let value = value?;454 if filter(&value)? {455 out.push(value);456 }457 }458459 Ok(Self::Eager(Cc::new(out)))460 }461462 pub fn ptr_eq(a: &Self, b: &Self) -> bool {463 match (a, b) {464 (Self::Lazy(a), Self::Lazy(b)) => Cc::ptr_eq(a, b),465 (Self::Eager(a), Self::Eager(b)) => Cc::ptr_eq(a, b),466 _ => false,467 }468 }469}470471impl From<Vec<Thunk<Val>>> for ArrValue {472 fn from(v: Vec<Thunk<Val>>) -> Self {473 Self::Lazy(Cc::new(v))474 }475}476477impl From<Vec<Val>> for ArrValue {478 fn from(v: Vec<Val>) -> Self {479 Self::Eager(Cc::new(v))480 }481}482483/// Represents a Jsonnet value, which can be spliced or indexed (string or array).484#[allow(clippy::module_name_repetitions)]485pub enum IndexableVal {486 /// String.487 Str(IStr),488 /// Array.489 Arr(ArrValue),490}491impl IndexableVal {492 /// Slice the value.493 ///494 /// # Implementation495 ///496 /// For strings, will create a copy of specified interval.497 ///498 /// For arrays, nothing will be copied on this call, instead [`ArrValue::Slice`] view will be returned.499 pub fn slice(500 self,501 index: Option<BoundedUsize<0, { i32::MAX as usize }>>,502 end: Option<BoundedUsize<0, { i32::MAX as usize }>>,503 step: Option<BoundedUsize<1, { i32::MAX as usize }>>,504 ) -> Result<Self> {505 match &self {506 IndexableVal::Str(s) => {507 let index = index.as_deref().copied().unwrap_or(0);508 let end = end.as_deref().copied().unwrap_or(usize::MAX);509 let step = step.as_deref().copied().unwrap_or(1);510511 if index >= end {512 return Ok(Self::Str("".into()));513 }514515 Ok(Self::Str(516 (s.chars()517 .skip(index)518 .take(end - index)519 .step_by(step)520 .collect::<String>())521 .into(),522 ))523 }524 IndexableVal::Arr(arr) => {525 let index = index.as_deref().copied().unwrap_or(0);526 let end = end.as_deref().copied().unwrap_or(usize::MAX).min(arr.len());527 let step = step.as_deref().copied().unwrap_or(1);528529 if index >= end {530 return Ok(Self::Arr(ArrValue::new_eager()));531 }532533 Ok(Self::Arr(ArrValue::Slice(Box::new(Slice {534 inner: arr.clone(),535 from: index as u32,536 to: end as u32,537 step: step as u32,538 }))))539 }540 }541 }542}543544/// Represents any valid Jsonnet value.545#[derive(Debug, Clone, Trace)]546pub enum Val {547 /// Represents a Jsonnet boolean.548 Bool(bool),549 /// Represents a Jsonnet null value.550 Null,551 /// Represents a Jsonnet string.552 Str(IStr),553 /// Represents a Jsonnet number.554 /// Should be finite, and not NaN555 /// This restriction isn't enforced by enum, as enum field can't be marked as private556 Num(f64),557 /// Represents a Jsonnet array.558 Arr(ArrValue),559 /// Represents a Jsonnet object.560 Obj(ObjValue),561 /// Represents a Jsonnet function.562 Func(FuncVal),563}564565impl From<IndexableVal> for Val {566 fn from(v: IndexableVal) -> Self {567 match v {568 IndexableVal::Str(s) => Self::Str(s),569 IndexableVal::Arr(a) => Self::Arr(a),570 }571 }572}573574// Broken between stable and nightly, as there is new layout size optimization575// #[cfg(target_pointer_width = "64")]576// static_assertions::assert_eq_size!(Val, [u8; 24]);577578impl Val {579 pub const fn as_bool(&self) -> Option<bool> {580 match self {581 Self::Bool(v) => Some(*v),582 _ => None,583 }584 }585 pub const fn as_null(&self) -> Option<()> {586 match self {587 Self::Null => Some(()),588 _ => None,589 }590 }591 pub fn as_str(&self) -> Option<IStr> {592 match self {593 Self::Str(s) => Some(s.clone()),594 _ => None,595 }596 }597 pub const fn as_num(&self) -> Option<f64> {598 match self {599 Self::Num(n) => Some(*n),600 _ => None,601 }602 }603 pub fn as_arr(&self) -> Option<ArrValue> {604 match self {605 Self::Arr(a) => Some(a.clone()),606 _ => None,607 }608 }609 pub fn as_obj(&self) -> Option<ObjValue> {610 match self {611 Self::Obj(o) => Some(o.clone()),612 _ => None,613 }614 }615 pub fn as_func(&self) -> Option<FuncVal> {616 match self {617 Self::Func(f) => Some(f.clone()),618 _ => None,619 }620 }621622 /// Creates `Val::Num` after checking for numeric overflow.623 /// As numbers are `f64`, we can just check for their finity.624 pub fn new_checked_num(num: f64) -> Result<Self> {625 if num.is_finite() {626 Ok(Self::Num(num))627 } else {628 throw!("overflow")629 }630 }631632 pub const fn value_type(&self) -> ValType {633 match self {634 Self::Str(..) => ValType::Str,635 Self::Num(..) => ValType::Num,636 Self::Arr(..) => ValType::Arr,637 Self::Obj(..) => ValType::Obj,638 Self::Bool(_) => ValType::Bool,639 Self::Null => ValType::Null,640 Self::Func(..) => ValType::Func,641 }642 }643644 pub fn to_string(&self) -> Result<IStr> {645 Ok(match self {646 Self::Bool(true) => "true".into(),647 Self::Bool(false) => "false".into(),648 Self::Null => "null".into(),649 Self::Str(s) => s.clone(),650 v => manifest_json_ex(651 v,652 &ManifestJsonOptions {653 padding: "",654 mtype: ManifestType::ToString,655 newline: "\n",656 key_val_sep: ": ",657 #[cfg(feature = "exp-preserve-order")]658 preserve_order: false,659 },660 )?661 .into(),662 })663 }664665 /// Expects value to be object, outputs (key, manifested value) pairs666 pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {667 let Self::Obj(obj) = self else {668 throw!(MultiManifestOutputIsNotAObject);669 };670 let keys = obj.fields(671 #[cfg(feature = "exp-preserve-order")]672 ty.preserve_order(),673 );674 let mut out = Vec::with_capacity(keys.len());675 for key in keys {676 let value = obj677 .get(key.clone())?678 .expect("item in object")679 .manifest(ty)?;680 out.push((key, value));681 }682 Ok(out)683 }684685 /// Expects value to be array, outputs manifested values686 pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {687 let Self::Arr(arr) = self else {688 throw!(StreamManifestOutputIsNotAArray);689 };690 let mut out = Vec::with_capacity(arr.len());691 for i in arr.iter() {692 out.push(i?.manifest(ty)?);693 }694 Ok(out)695 }696697 pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {698 Ok(match ty {699 ManifestFormat::YamlStream(format) => {700 let Self::Arr(arr) = self else {701 throw!(StreamManifestOutputIsNotAArray)702 };703 let mut out = String::new();704705 match format as &ManifestFormat {706 ManifestFormat::YamlStream(_) => throw!(StreamManifestOutputCannotBeRecursed),707 ManifestFormat::String => throw!(StreamManifestCannotNestString),708 _ => {}709 };710711 if !arr.is_empty() {712 for v in arr.iter() {713 out.push_str("---\n");714 out.push_str(&v?.manifest(format)?);715 out.push('\n');716 }717 out.push_str("...");718 }719720 out.into()721 }722 ManifestFormat::Yaml {723 padding,724 #[cfg(feature = "exp-preserve-order")]725 preserve_order,726 } => self.to_yaml(727 *padding,728 #[cfg(feature = "exp-preserve-order")]729 *preserve_order,730 )?,731 ManifestFormat::Json {732 padding,733 #[cfg(feature = "exp-preserve-order")]734 preserve_order,735 } => self.to_json(736 *padding,737 #[cfg(feature = "exp-preserve-order")]738 *preserve_order,739 )?,740 ManifestFormat::ToString => self.to_string()?,741 ManifestFormat::String => match self {742 Self::Str(s) => s.clone(),743 _ => throw!(StringManifestOutputIsNotAString),744 },745 })746 }747748 /// For manifestification749 pub fn to_json(750 &self,751 padding: usize,752 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,753 ) -> Result<IStr> {754 manifest_json_ex(755 self,756 &ManifestJsonOptions {757 padding: &" ".repeat(padding),758 mtype: if padding == 0 {759 ManifestType::Minify760 } else {761 ManifestType::Manifest762 },763 newline: "\n",764 key_val_sep: ": ",765 #[cfg(feature = "exp-preserve-order")]766 preserve_order,767 },768 )769 .map(Into::into)770 }771772 /// Calls `std.manifestJson`773 pub fn to_std_json(774 &self,775 padding: usize,776 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,777 ) -> Result<Rc<str>> {778 manifest_json_ex(779 self,780 &ManifestJsonOptions {781 padding: &" ".repeat(padding),782 mtype: ManifestType::Std,783 newline: "\n",784 key_val_sep: ": ",785 #[cfg(feature = "exp-preserve-order")]786 preserve_order,787 },788 )789 .map(Into::into)790 }791792 pub fn to_yaml(793 &self,794 padding: usize,795 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,796 ) -> Result<IStr> {797 let padding = &" ".repeat(padding);798 manifest_yaml_ex(799 self,800 &ManifestYamlOptions {801 padding,802 arr_element_padding: padding,803 quote_keys: false,804 #[cfg(feature = "exp-preserve-order")]805 preserve_order,806 },807 )808 .map(Into::into)809 }810 pub fn into_indexable(self) -> Result<IndexableVal> {811 Ok(match self {812 Val::Str(s) => IndexableVal::Str(s),813 Val::Arr(arr) => IndexableVal::Arr(arr),814 _ => throw!(ValueIsNotIndexable(self.value_type())),815 })816 }817}818819const fn is_function_like(val: &Val) -> bool {820 matches!(val, Val::Func(_))821}822823/// Native implementation of `std.primitiveEquals`824pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {825 Ok(match (val_a, val_b) {826 (Val::Bool(a), Val::Bool(b)) => a == b,827 (Val::Null, Val::Null) => true,828 (Val::Str(a), Val::Str(b)) => a == b,829 (Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,830 (Val::Arr(_), Val::Arr(_)) => {831 throw!("primitiveEquals operates on primitive types, got array")832 }833 (Val::Obj(_), Val::Obj(_)) => {834 throw!("primitiveEquals operates on primitive types, got object")835 }836 (a, b) if is_function_like(a) && is_function_like(b) => {837 throw!("cannot test equality of functions")838 }839 (_, _) => false,840 })841}842843/// Native implementation of `std.equals`844pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {845 if val_a.value_type() != val_b.value_type() {846 return Ok(false);847 }848 match (val_a, val_b) {849 (Val::Arr(a), Val::Arr(b)) => {850 if ArrValue::ptr_eq(a, b) {851 return Ok(true);852 }853 if a.len() != b.len() {854 return Ok(false);855 }856 for (a, b) in a.iter().zip(b.iter()) {857 if !equals(&a?, &b?)? {858 return Ok(false);859 }860 }861 Ok(true)862 }863 (Val::Obj(a), Val::Obj(b)) => {864 if ObjValue::ptr_eq(a, b) {865 return Ok(true);866 }867 let fields = a.fields(868 #[cfg(feature = "exp-preserve-order")]869 false,870 );871 if fields872 != b.fields(873 #[cfg(feature = "exp-preserve-order")]874 false,875 ) {876 return Ok(false);877 }878 for field in fields {879 if !equals(880 &a.get(field.clone())?.expect("field exists"),881 &b.get(field)?.expect("field exists"),882 )? {883 return Ok(false);884 }885 }886 Ok(true)887 }888 (a, b) => Ok(primitive_equals(a, b)?),889 }890}crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -50,25 +50,22 @@
}
fn extract_type_from_option(ty: &Type) -> Result<Option<&Type>> {
- Ok(if let Some(args) = type_is_path(ty, "Option") {
- // It should have only on angle-bracketed param ("<String>"):
- let generic_arg = match args {
- PathArguments::AngleBracketed(params) => params.args.iter().next().unwrap(),
- _ => return Err(Error::new(args.span(), "missing option generic")),
- };
- // This argument must be a type:
- match generic_arg {
- GenericArgument::Type(ty) => Some(ty),
- _ => {
- return Err(Error::new(
- generic_arg.span(),
- "option generic should be a type",
- ))
- }
- }
- } else {
- None
- })
+ let Some(args) = type_is_path(ty, "Option") else {
+ return Ok(None)
+ };
+ // It should have only on angle-bracketed param ("<String>"):
+ let PathArguments::AngleBracketed(params) = args else {
+ return Err(Error::new(args.span(), "missing option generic"));
+ };
+ let generic_arg = params.args.iter().next().unwrap();
+ // This argument must be a type:
+ let GenericArgument::Type(ty) = generic_arg else {
+ return Err(Error::new(
+ generic_arg.span(),
+ "option generic should be a type",
+ ))
+ };
+ Ok(Some(ty))
}
struct Field {
@@ -137,9 +134,8 @@
impl ArgInfo {
fn parse(name: &str, arg: &FnArg) -> Result<Self> {
- let arg = match arg {
- FnArg::Receiver(_) => unreachable!(),
- FnArg::Typed(a) => a,
+ let FnArg::Typed(arg) = arg else {
+ unreachable!()
};
let ident = match &arg.pat as &Pat {
Pat::Ident(i) => Some(i.ident.clone()),
@@ -206,33 +202,28 @@
}
fn builtin_inner(attr: BuiltinAttrs, fun: ItemFn) -> syn::Result<TokenStream> {
- let result = match fun.sig.output {
- ReturnType::Default => {
- return Err(Error::new(
- fun.sig.span(),
- "builtin should return something",
- ))
- }
- ReturnType::Type(_, ref ty) => ty.clone(),
+ let ReturnType::Type(_, result) = &fun.sig.output else {
+ return Err(Error::new(
+ fun.sig.span(),
+ "builtin should return something",
+ ))
};
- let result_inner = if let Some(args) = type_is_path(&result, "Result") {
- let generic_arg = match args {
- PathArguments::AngleBracketed(params) => params.args.iter().next().unwrap(),
- _ => return Err(Error::new(args.span(), "missing result generic")),
- };
- // This argument must be a type:
- match generic_arg {
- GenericArgument::Type(ty) => ty,
- _ => {
- return Err(Error::new(
- generic_arg.span(),
- "option generic should be a type",
- ))
- }
- }
- } else {
+
+ let Some(args) = type_is_path(result, "Result") else {
return Err(Error::new(result.span(), "return value should be result"));
+
+ };
+ let PathArguments::AngleBracketed(params) = args else {
+ return Err(Error::new(args.span(), "missing result generic"));
};
+ let generic_arg = params.args.iter().next().unwrap();
+ // This argument must be a type:
+ let GenericArgument::Type(result_inner) = generic_arg else {
+ return Err(Error::new(
+ generic_arg.span(),
+ "option generic should be a type",
+ ))
+ };
let name = fun.sig.ident.to_string();
let args = fun
@@ -471,9 +462,7 @@
impl TypedField {
fn parse(field: &syn::Field) -> Result<Self> {
let attr = parse_attr::<TypedAttr, _>(&field.attrs, "typed")?.unwrap_or_default();
- let ident = if let Some(ident) = field.ident.clone() {
- ident
- } else {
+ let Some(ident) = field.ident.clone() else {
return Err(Error::new(
field.span(),
"this field should appear in output object, but it has no visible name",
@@ -603,9 +592,8 @@
}
fn derive_typed_inner(input: DeriveInput) -> Result<TokenStream> {
- let data = match &input.data {
- syn::Data::Struct(s) => s,
- _ => return Err(Error::new(input.span(), "only structs supported")),
+ let syn::Data::Struct(data) = &input.data else {
+ return Err(Error::new(input.span(), "only structs supported"));
};
let ident = &input.ident;
crates/jrsonnet-parser/src/source.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/source.rs
+++ b/crates/jrsonnet-parser/src/source.rs
@@ -32,10 +32,8 @@
self.hash(&mut hasher)
}
fn dyn_eq(&self, other: &dyn $T) -> bool {
- let other = if let Some(v) = other.as_any().downcast_ref::<Self>() {
- v
- } else {
- return false;
+ let Some(other) = other.as_any().downcast_ref::<Self>() else {
+ return false
};
let this = <Self as $T>::as_any(self)
.downcast_ref::<Self>()
tests/tests/sanity.rsdiffbeforeafterboth--- a/tests/tests/sanity.rs
+++ b/tests/tests/sanity.rs
@@ -22,17 +22,15 @@
s.with_stdlib();
{
- let e = match s.evaluate_snippet("snip".to_owned(), "assert 1 == 2: 'fail'; null") {
- Ok(_) => throw!("assertion should fail"),
- Err(e) => e,
+ let Err(e) = s.evaluate_snippet("snip".to_owned(), "assert 1 == 2: 'fail'; null") else {
+ throw!("assertion should fail");
};
let e = s.stringify_err(&e);
ensure!(e.starts_with("assert failed: fail\n"));
}
{
- let e = match s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 2)") {
- Ok(_) => throw!("assertion should fail"),
- Err(e) => e,
+ let Err(e) = s.evaluate_snippet("snip".to_owned(), "std.assertEqual(1, 2)") else {
+ throw!("assertion should fail")
};
let e = s.stringify_err(&e);
ensure!(e.starts_with("runtime error: Assertion failed. 1 != 2"))