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 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"))