git.delta.rocks / jrsonnet / refs/commits / 1925b3a76ba9

difftreelog

style use let-else

Yaroslav Bolyukin2022-11-03parent: #a8de1de.patch.diff
in: master

7 files changed

modifiedcrates/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) {
modifiedcrates/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;
 				};
 
modifiedcrates/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) => {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -54,12 +54,8 @@
 			ThunkInner::Pending => return Err(InfiniteRecursionDetected.into()),
 			ThunkInner::Waiting(..) => (),
 		};
-		let value = if let ThunkInner::Waiting(value) =
-			std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending)
-		{
-			value
-		} else {
-			unreachable!()
+		let ThunkInner::Waiting(value) = std::mem::replace(&mut *self.0.borrow_mut(), ThunkInner::Pending) else {
+			unreachable!();
 		};
 		let new_value = match value.0.get() {
 			Ok(v) => v,
@@ -668,9 +664,8 @@
 
 	/// Expects value to be object, outputs (key, manifested value) pairs
 	pub fn manifest_multi(&self, ty: &ManifestFormat) -> Result<Vec<(IStr, IStr)>> {
-		let obj = match self {
-			Self::Obj(obj) => obj,
-			_ => throw!(MultiManifestOutputIsNotAObject),
+		let Self::Obj(obj) = self else {
+			throw!(MultiManifestOutputIsNotAObject);
 		};
 		let keys = obj.fields(
 			#[cfg(feature = "exp-preserve-order")]
@@ -689,9 +684,8 @@
 
 	/// Expects value to be array, outputs manifested values
 	pub fn manifest_stream(&self, ty: &ManifestFormat) -> Result<Vec<IStr>> {
-		let arr = match self {
-			Self::Arr(a) => a,
-			_ => throw!(StreamManifestOutputIsNotAArray),
+		let Self::Arr(arr) = self else {
+			throw!(StreamManifestOutputIsNotAArray);
 		};
 		let mut out = Vec::with_capacity(arr.len());
 		for i in arr.iter() {
@@ -703,9 +697,8 @@
 	pub fn manifest(&self, ty: &ManifestFormat) -> Result<IStr> {
 		Ok(match ty {
 			ManifestFormat::YamlStream(format) => {
-				let arr = match self {
-					Self::Arr(a) => a,
-					_ => throw!(StreamManifestOutputIsNotAArray),
+				let Self::Arr(arr) = self else {
+					throw!(StreamManifestOutputIsNotAArray)
 				};
 				let mut out = String::new();
 
modifiedcrates/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;
modifiedcrates/jrsonnet-parser/src/source.rsdiffbeforeafterboth
before · crates/jrsonnet-parser/src/source.rs
1use std::{2	any::Any,3	fmt::{self, Debug, Display},4	hash::{Hash, Hasher},5	path::{Path, PathBuf},6	rc::Rc,7};89use jrsonnet_gcmodule::{Trace, Tracer};10use jrsonnet_interner::IStr;11#[cfg(feature = "serde")]12use serde::{Deserialize, Serialize};13#[cfg(feature = "structdump")]14use structdump::Codegen;1516use crate::location::{location_to_offset, offset_to_location, CodeLocation};1718macro_rules! any_ext_methods {19	($T:ident) => {20		fn as_any(&self) -> &dyn Any;21		fn dyn_hash(&self, hasher: &mut dyn Hasher);22		fn dyn_eq(&self, other: &dyn $T) -> bool;23		fn dyn_debug(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;24	};25}26macro_rules! any_ext_impl {27	($T:ident) => {28		fn as_any(&self) -> &dyn Any {29			self30		}31		fn dyn_hash(&self, mut hasher: &mut dyn Hasher) {32			self.hash(&mut hasher)33		}34		fn dyn_eq(&self, other: &dyn $T) -> bool {35			let other = if let Some(v) = other.as_any().downcast_ref::<Self>() {36				v37			} else {38				return false;39			};40			let this = <Self as $T>::as_any(self)41				.downcast_ref::<Self>()42				.expect("restricted by impl");43			this == other44		}45		fn dyn_debug(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {46			<Self as std::fmt::Debug>::fmt(self, fmt)47		}48	};49}50macro_rules! any_ext {51	($T:ident) => {52		impl Hash for dyn $T {53			fn hash<H: Hasher>(&self, state: &mut H) {54				self.dyn_hash(state)55			}56		}57		impl PartialEq for dyn $T {58			fn eq(&self, other: &Self) -> bool {59				self.dyn_eq(other)60			}61		}62		impl Eq for dyn $T {}63	};64}65pub trait SourcePathT: Trace + Debug + Display {66	/// This method should be checked by resolver before panicking with bad SourcePath input67	/// if `true` - then resolver may threat this path as default, and default is usally a CWD68	fn is_default(&self) -> bool;69	fn path(&self) -> Option<&Path>;70	any_ext_methods!(SourcePathT);71}72any_ext!(SourcePathT);7374/// Represents location of a file75///76/// Standard CLI only operates using77/// - [`SourceFile`] - for any file78/// - [`SourceDirectory`] - for resolution from CWD79/// - [`SourceVirtual`] - for stdlib/ext-str80///81/// From all of those, only [`SourceVirtual`] may be constructed manually, any other path kind should be only obtained82/// from assigned `ImportResolver`83/// However, you should always check `is_default` method return, as it will return true for any paths, where default84/// search location is applicable85///86/// Resolver may also return custom implementations of this trait, for example it may return http url in case of remotely loaded files87#[derive(Eq, Debug, Clone)]88pub struct SourcePath(Rc<dyn SourcePathT>);89impl SourcePath {90	pub fn new(inner: impl SourcePathT) -> Self {91		Self(Rc::new(inner))92	}93	pub fn downcast_ref<T: SourcePathT>(&self) -> Option<&T> {94		self.0.as_any().downcast_ref()95	}96	pub fn is_default(&self) -> bool {97		self.0.is_default()98	}99	pub fn path(&self) -> Option<&Path> {100		self.0.path()101	}102}103impl Hash for SourcePath {104	fn hash<H: Hasher>(&self, state: &mut H) {105		self.0.hash(state);106	}107}108impl PartialEq for SourcePath {109	#[allow(clippy::op_ref)]110	fn eq(&self, other: &Self) -> bool {111		&*self.0 == &*other.0112	}113}114impl Trace for SourcePath {115	fn trace(&self, tracer: &mut Tracer) {116		(*self.0).trace(tracer)117	}118119	fn is_type_tracked() -> bool120	where121		Self: Sized,122	{123		true124	}125}126impl Display for SourcePath {127	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {128		write!(f, "{}", self.0)129	}130}131impl Default for SourcePath {132	fn default() -> Self {133		Self(Rc::new(SourceDefault))134	}135}136137#[cfg(feature = "structdump")]138impl Codegen for SourcePath {139	fn gen_code(140		&self,141		res: &mut structdump::CodegenResult,142		unique: bool,143	) -> structdump::TokenStream {144		let source_virtual = self145			.0146			.as_any()147			.downcast_ref::<SourceVirtual>()148			.expect("can only codegen for virtual source paths!")149			.0150			.clone();151		let val = res.add_value(source_virtual, false);152		res.add_code(153			structdump::quote! {154				structdump_import::SourcePath::new(structdump_import::SourceVirtual(#val))155			},156			Some(structdump::quote!(SourcePath)),157			unique,158		)159	}160}161162#[derive(Trace, Hash, PartialEq, Eq, Debug)]163struct SourceDefault;164impl Display for SourceDefault {165	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {166		write!(f, "<default>")167	}168}169impl SourcePathT for SourceDefault {170	fn is_default(&self) -> bool {171		true172	}173	fn path(&self) -> Option<&Path> {174		None175	}176	any_ext_impl!(SourcePathT);177}178179/// Represents path to the file on the disk180/// Directories shouldn't be put here, as resolution for files differs from resolution for directories:181///182/// When `file` is being resolved from `SourceFile(a/b/c)`, it should be resolved to `SourceFile(a/b/file)`,183/// however if it is being resolved from `SourceDirectory(a/b/c)`, then it should be resolved to `SourceDirectory(a/b/c/file)`184#[derive(Trace, Hash, PartialEq, Eq, Debug)]185pub struct SourceFile(PathBuf);186impl SourceFile {187	pub fn new(path: PathBuf) -> Self {188		Self(path)189	}190	pub fn path(&self) -> &Path {191		&self.0192	}193}194impl Display for SourceFile {195	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {196		write!(f, "{}", self.0.display())197	}198}199impl SourcePathT for SourceFile {200	fn is_default(&self) -> bool {201		false202	}203	fn path(&self) -> Option<&Path> {204		Some(&self.0)205	}206	any_ext_impl!(SourcePathT);207}208209/// Represents path to the directory on the disk210///211/// See also [`SourceFile`]212#[derive(Trace, Hash, PartialEq, Eq, Debug)]213pub struct SourceDirectory(PathBuf);214impl SourceDirectory {215	pub fn new(path: PathBuf) -> Self {216		Self(path)217	}218	pub fn path(&self) -> &Path {219		&self.0220	}221}222impl Display for SourceDirectory {223	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {224		write!(f, "{}", self.0.display())225	}226}227impl SourcePathT for SourceDirectory {228	fn is_default(&self) -> bool {229		false230	}231	fn path(&self) -> Option<&Path> {232		Some(&self.0)233	}234	any_ext_impl!(SourcePathT);235}236237/// Represents virtual file, whose are located in memory, and shouldn't be cached238///239/// It is used for --ext-code=.../--tla-code=.../standard library source code by default,240/// and user can construct arbitrary values by hand, without asking import resolver241#[cfg_attr(feature = "structdump", derive(Codegen))]242#[derive(Trace, Hash, PartialEq, Eq, Debug, Clone)]243pub struct SourceVirtual(pub IStr);244impl Display for SourceVirtual {245	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {246		write!(f, "{}", self.0)247	}248}249impl SourcePathT for SourceVirtual {250	fn is_default(&self) -> bool {251		true252	}253	fn path(&self) -> Option<&Path> {254		None255	}256	any_ext_impl!(SourcePathT);257}258259/// Either real file, or virtual260/// Hash of FileName always have same value as raw Path, to make it possible to use with raw_entry_mut261#[cfg_attr(feature = "structdump", derive(Codegen))]262#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]263#[derive(Clone, PartialEq, Eq, Debug)]264pub struct Source(pub Rc<(SourcePath, IStr)>);265static_assertions::assert_eq_size!(Source, *const ());266267impl Trace for Source {268	fn trace(&self, _tracer: &mut Tracer) {}269270	fn is_type_tracked() -> bool {271		false272	}273}274275impl Source {276	pub fn new(path: SourcePath, code: IStr) -> Self {277		Self(Rc::new((path, code)))278	}279280	pub fn new_virtual(name: IStr, code: IStr) -> Self {281		Self::new(SourcePath::new(SourceVirtual(name)), code)282	}283284	pub fn code(&self) -> &str {285		&self.0 .1286	}287288	pub fn source_path(&self) -> &SourcePath {289		&self.0 .0290	}291292	pub fn map_source_locations<const S: usize>(&self, locs: &[u32; S]) -> [CodeLocation; S] {293		offset_to_location(&self.0 .1, locs)294	}295	pub fn map_from_source_location(&self, line: usize, column: usize) -> Option<usize> {296		location_to_offset(&self.0 .1, line, column)297	}298}
modifiedtests/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"))