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