git.delta.rocks / jrsonnet / refs/commits / a05afd32cebc

difftreelog

style fix clippy warnings

Yaroslav Bolyukin2023-01-20parent: #974f2c1.patch.diff
in: master

16 files changed

modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -5,7 +5,7 @@
 
 use clap::{CommandFactory, Parser};
 use clap_complete::Shell;
-use jrsonnet_cli::{ManifestOpts, OutputOpts, TraceOpts, MiscOpts, TlaOpts, StdOpts, GcOpts};
+use jrsonnet_cli::{GcOpts, ManifestOpts, MiscOpts, OutputOpts, StdOpts, TlaOpts, TraceOpts};
 use jrsonnet_evaluator::{
 	apply_tla,
 	error::{Error as JrError, ErrorKind},
@@ -133,16 +133,14 @@
 
 fn main_catch(opts: Opts) -> bool {
 	let s = State::default();
-	let trace = opts
-		.trace
-		.trace_format();
+	let trace = opts.trace.trace_format();
 	if let Err(e) = main_real(&s, opts) {
 		if let Error::Evaluation(e) = e {
 			let mut out = String::new();
 			trace.write_trace(&mut out, &e).expect("format error");
 			eprintln!("{out}")
 		} else {
-			eprintln!("{}", e);
+			eprintln!("{e}");
 		}
 		return false;
 	}
@@ -150,7 +148,7 @@
 }
 
 fn main_real(s: &State, opts: Opts) -> Result<(), Error> {
-	let _gc_leak_guard= opts.gc.leak_on_exit();
+	let _gc_leak_guard = opts.gc.leak_on_exit();
 	let _gc_print_stats = opts.gc.stats_printer();
 	let _stack_depth_override = opts.misc.stack_size_override();
 
@@ -220,7 +218,7 @@
 	} else {
 		let output = val.manifest(manifest_format)?;
 		if !output.is_empty() {
-			println!("{}", output);
+			println!("{output}");
 		}
 	}
 
modifiedcrates/jrsonnet-cli/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/lib.rs
+++ b/crates/jrsonnet-cli/src/lib.rs
@@ -6,7 +6,10 @@
 use std::{env, marker::PhantomData, path::PathBuf};
 
 use clap::Parser;
-use jrsonnet_evaluator::{error::Result, stack::{set_stack_depth_limit, StackDepthLimitOverrideGuard, limit_stack_depth}, FileImportResolver, State, ImportResolver};
+use jrsonnet_evaluator::{
+	stack::{limit_stack_depth, StackDepthLimitOverrideGuard},
+	FileImportResolver,
+};
 use jrsonnet_gcmodule::with_thread_object_space;
 pub use manifest::*;
 pub use stdlib::*;
@@ -71,6 +74,7 @@
 }
 impl GcOpts {
 	pub fn stats_printer(&self) -> Option<GcStatsPrinter> {
+		#[allow(clippy::unnecessary_lazy_evaluations/*, reason = "GcStatsPrinter has side-effect on Drop"*/)]
 		self.gc_print_stats.then(|| GcStatsPrinter {
 			collect_before_printing_stats: self.gc_collect_before_printing_stats,
 		})
@@ -96,7 +100,7 @@
 		eprintln!("=== GC STATS ===");
 		if self.collect_before_printing_stats {
 			let collected = jrsonnet_gcmodule::collect_thread_cycles();
-			eprintln!("Collected: {}", collected);
+			eprintln!("Collected: {collected}");
 		}
 		eprintln!("Tracked: {}", jrsonnet_gcmodule::count_thread_tracked())
 	}
modifiedcrates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -1,10 +1,8 @@
 use std::path::PathBuf;
 
 use clap::{Parser, ValueEnum};
-use jrsonnet_evaluator::{
-	error::Result,
-	manifest::{JsonFormat, ManifestFormat, StringFormat, ToStringFormat, YamlStreamFormat},
-	State,
+use jrsonnet_evaluator::manifest::{
+	JsonFormat, ManifestFormat, StringFormat, ToStringFormat, YamlStreamFormat,
 };
 use jrsonnet_stdlib::{TomlFormat, YamlFormat};
 
modifiedcrates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -1,7 +1,7 @@
 use std::{fs::read_to_string, str::FromStr};
 
 use clap::Parser;
-use jrsonnet_evaluator::{error::Result, tb, trace::PathResolver, State};
+use jrsonnet_evaluator::{error::Result, trace::PathResolver, State};
 use jrsonnet_stdlib::ContextInitializer;
 
 #[derive(Clone)]
@@ -49,7 +49,7 @@
 				name: out[0].into(),
 				value: content,
 			}),
-			Err(e) => Err(format!("{}", e)),
+			Err(e) => Err(format!("{e}")),
 		}
 	}
 }
@@ -86,8 +86,7 @@
 		if self.no_stdlib {
 			return Ok(None);
 		}
-		let ctx =
-			ContextInitializer::new(s.clone(), PathResolver::new_cwd_fallback());
+		let ctx = ContextInitializer::new(s.clone(), PathResolver::new_cwd_fallback());
 		for ext in self.ext_str.iter() {
 			ctx.add_ext_str((&ext.name as &str).into(), (&ext.value as &str).into());
 		}
modifiedcrates/jrsonnet-cli/src/tla.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/tla.rs
+++ b/crates/jrsonnet-cli/src/tla.rs
@@ -3,7 +3,7 @@
 	error::{ErrorKind, Result},
 	function::TlaArg,
 	gc::GcHashMap,
-	IStr, State,
+	IStr,
 };
 use jrsonnet_parser::{ParserSettings, Source};
 
modifiedcrates/jrsonnet-cli/src/trace.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/trace.rs
+++ b/crates/jrsonnet-cli/src/trace.rs
@@ -1,9 +1,5 @@
 use clap::{Parser, ValueEnum};
-use jrsonnet_evaluator::{
-	error::Result,
-	trace::{CompactFormat, ExplainingFormat, PathResolver, TraceFormat},
-	State,
-};
+use jrsonnet_evaluator::trace::{CompactFormat, ExplainingFormat, PathResolver, TraceFormat};
 
 #[derive(PartialEq, Eq, ValueEnum, Clone)]
 pub enum TraceFormatName {
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -274,6 +274,7 @@
 		f.debug_tuple("LocError").field(&self.0).finish()
 	}
 }
+impl std::error::Error for Error {}
 
 pub trait ErrorSource {
 	fn to_location(self) -> Option<ExprLocation>;
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -104,28 +104,15 @@
 					}
 				}
 			} else {
-				{
-					let ai = a.iter();
-					let bi = b.iter();
+				let ai = a.iter();
+				let bi = b.iter();
 
-					for (a, b) in ai.zip(bi) {
-						let ord = evaluate_compare_op(&a?, &b?, op)?;
-						if !ord.is_eq() {
-							return Ok(ord);
-						}
+				for (a, b) in ai.zip(bi) {
+					let ord = evaluate_compare_op(&a?, &b?, op)?;
+					if !ord.is_eq() {
+						return Ok(ord);
 					}
 				}
-				// {
-				// 	let ai = a.iter_expl();
-				// 	let bi = b.iter_expl();
-
-				// 	for (a, b) in ai.zip(bi) {
-				// 		let ord = evaluate_compare_op(&a?, &b?, op)?;
-				// 		if !ord.is_eq() {
-				// 			return Ok(ord);
-				// 		}
-				// 	}
-				// }
 			}
 			a.len().cmp(&b.len())
 		}
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -36,6 +36,7 @@
 	clippy::use_self,
 	// https://github.com/rust-lang/rust-clippy/issues/8539
 	clippy::iter_with_drain,
+	clippy::type_repetition_in_bounds,
 	// ci is being run with nightly, but library should work on stable
 	clippy::missing_const_for_fn,
 )]
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -54,7 +54,7 @@
 
 #[cfg(feature = "exp-preserve-order")]
 mod ordering {
-	use std::cmp::Reverse;
+	use std::cmp::{Ordering, Reverse};
 
 	use jrsonnet_gcmodule::Trace;
 
@@ -81,12 +81,10 @@
 			Self(Reverse(depth), index)
 		}
 		pub fn collide(self, other: Self) -> Self {
-			if self.0 .0 > other.0 .0 {
-				self
-			} else if self.0 .0 < other.0 .0 {
-				other
-			} else {
-				unreachable!("object can't have two fields with same name")
+			match self.0 .0.cmp(&other.0 .0) {
+				Ordering::Greater => self,
+				Ordering::Less => other,
+				Ordering::Equal => unreachable!("object can't have two fields with the same name"),
 			}
 		}
 	}
@@ -188,6 +186,12 @@
 	pub fn new_empty() -> Self {
 		Self::new(None, Cc::new(GcHashMap::new()), Cc::new(Vec::new()))
 	}
+	pub fn builder() -> ObjValueBuilder {
+		ObjValueBuilder::new()
+	}
+	pub fn builder_with_capacity(capacity: usize) -> ObjValueBuilder {
+		ObjValueBuilder::with_capacity(capacity)
+	}
 	#[must_use]
 	pub fn extend_from(&self, sup: Self) -> Self {
 		match &self.0.sup {
@@ -304,7 +308,7 @@
 						break;
 					}
 					fields[j] = fields[k].clone();
-					j = k
+					j = k;
 				}
 				fields[j] = x;
 			}
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -33,6 +33,7 @@
 	Pending,
 }
 
+/// Lazily evaluated value
 #[allow(clippy::module_name_repetitions)]
 #[derive(Clone, Trace)]
 pub struct Thunk<T: Trace>(Cc<RefCell<ThunkInner<T>>>);
@@ -57,6 +58,13 @@
 		self.evaluate()?;
 		Ok(())
 	}
+
+	/// Evaluate thunk, or return cached value
+	///
+	/// # Errors
+	///
+	/// - Lazy value evaluation returned error
+	/// - This method was called during inner value evaluation
 	pub fn evaluate(&self) -> Result<T> {
 		match &*self.0.borrow() {
 			ThunkInner::Computed(v) => return Ok(v.clone()),
@@ -132,7 +140,7 @@
 	}
 }
 
-/// Represents a Jsonnet value, which can be spliced or indexed (string or array).
+/// Represents a Jsonnet value, which can be sliced or indexed (string or array).
 #[allow(clippy::module_name_repetitions)]
 pub enum IndexableVal {
 	/// String.
@@ -247,6 +255,16 @@
 		}
 	}
 }
+impl From<&str> for StrValue {
+	fn from(value: &str) -> Self {
+		Self::Flat(value.into())
+	}
+}
+impl From<String> for StrValue {
+	fn from(value: String) -> Self {
+		Self::Flat(value.into())
+	}
+}
 impl Display for StrValue {
 	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 		match self {
modifiedcrates/jrsonnet-parser/src/source.rsdiffbeforeafterboth
--- a/crates/jrsonnet-parser/src/source.rs
+++ b/crates/jrsonnet-parser/src/source.rs
@@ -33,8 +33,8 @@
 		}
 		fn dyn_eq(&self, other: &dyn $T) -> bool {
 			let Some(other) = other.as_any().downcast_ref::<Self>() else {
-												return false
-											};
+				return false
+			};
 			let this = <Self as $T>::as_any(self)
 				.downcast_ref::<Self>()
 				.expect("restricted by impl");
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -211,7 +211,7 @@
 				locs[0].line
 			);
 		}
-		eprintln!(" {}", value);
+		eprintln!(" {value}");
 	}
 }
 
@@ -229,7 +229,7 @@
 }
 
 fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {
-	let source_name = format!("<extvar:{}>", name);
+	let source_name = format!("<extvar:{name}>");
 	Source::new_virtual(source_name.into(), code.into())
 }
 
modifiedcrates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -46,7 +46,7 @@
 		.ext_natives
 		.get(&x)
 		.cloned()
-		.map_or(Val::Null, |v| Val::Func(FuncVal::Builtin(v.clone())))
+		.map_or(Val::Null, |v| Val::Func(FuncVal::Builtin(v)))
 }
 
 #[builtin(fields(
modifiedcrates/jrsonnet-stdlib/src/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/parse.rs
+++ b/crates/jrsonnet-stdlib/src/parse.rs
@@ -8,7 +8,7 @@
 #[builtin]
 pub fn builtin_parse_json(str: IStr) -> Result<Val> {
 	let value: Val = serde_json::from_str(&str)
-		.map_err(|e| RuntimeError(format!("failed to parse json: {}", e).into()))?;
+		.map_err(|e| RuntimeError(format!("failed to parse json: {e}").into()))?;
 	Ok(value)
 }
 
@@ -22,7 +22,7 @@
 	let mut out = vec![];
 	for item in value {
 		let val = Val::deserialize(item)
-			.map_err(|e| RuntimeError(format!("failed to parse yaml: {}", e).into()))?;
+			.map_err(|e| RuntimeError(format!("failed to parse yaml: {e}").into()))?;
 		out.push(val);
 	}
 	Ok(if out.is_empty() {
modifiedcrates/jrsonnet-types/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-types/src/lib.rs
1#![allow(clippy::redundant_closure_call)]23use std::fmt::Display;45use jrsonnet_gcmodule::Trace;67#[macro_export]8macro_rules! ty {9	((Array<number>)) => {{10		$crate::ComplexValType::ArrayRef(&$crate::ComplexValType::Simple($crate::ValType::Num))11	}};12	((Array<ubyte>)) => {{13		$crate::ComplexValType::ArrayRef(&$crate::ComplexValType::BoundedNumber(Some(0.0), Some(255.0)))14	}};15	(array) => {16		$crate::ComplexValType::Simple($crate::ValType::Arr)17	};18	(boolean) => {19		$crate::ComplexValType::Simple($crate::ValType::Bool)20	};21	(null) => {22		$crate::ComplexValType::Simple($crate::ValType::Null)23	};24	(string) => {25		$crate::ComplexValType::Simple($crate::ValType::Str)26	};27	(char) => {28		$crate::ComplexValType::Char29	};30	(number) => {31		$crate::ComplexValType::Simple($crate::ValType::Num)32	};33	(BoundedNumber<($min:expr), ($max:expr)>) => {{34		$crate::ComplexValType::BoundedNumber($min, $max)35	}};36	(object) => {37		$crate::ComplexValType::Simple($crate::ValType::Obj)38	};39	(any) => {40		$crate::ComplexValType::Any41	};42	(function) => {43		$crate::ComplexValType::Simple($crate::ValType::Func)44	};45	(($($a:tt) |+)) => {{46		static CONTENTS: &'static [&'static $crate::ComplexValType] = &[47			$(&ty!($a)),+48		];49		$crate::ComplexValType::UnionRef(CONTENTS)50	}};51	(($($a:tt) &+)) => {{52		static CONTENTS: &'static [&'static $crate::ComplexValType] = &[53			$(&ty!($a)),+54		];55		$crate::ComplexValType::SumRef(CONTENTS)56	}};57}5859#[test]60fn test() {61	assert_eq!(62		ty!((Array<number>)),63		ComplexValType::ArrayRef(&ComplexValType::Simple(ValType::Num))64	);65	assert_eq!(ty!(array), ComplexValType::Simple(ValType::Arr));66	assert_eq!(ty!(any), ComplexValType::Any);67	assert_eq!(68		ty!((string | number)),69		ComplexValType::UnionRef(&[70			&ComplexValType::Simple(ValType::Str),71			&ComplexValType::Simple(ValType::Num)72		])73	);74	assert_eq!(75		format!("{}", ty!(((string & number) | (object & null)))),76		"string & number | object & null"77	);78	assert_eq!(format!("{}", ty!((string | array))), "string | array");79	assert_eq!(80		format!("{}", ty!(((string & number) | array))),81		"string & number | array"82	);83}8485#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]86pub enum ValType {87	Bool,88	Null,89	Str,90	Num,91	Arr,92	Obj,93	Func,94}9596impl ValType {97	pub const fn name(&self) -> &'static str {98		use ValType::*;99		match self {100			Bool => "boolean",101			Null => "null",102			Str => "string",103			Num => "number",104			Arr => "array",105			Obj => "object",106			Func => "function",107		}108	}109}110111impl Display for ValType {112	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {113		write!(f, "{}", self.name())114	}115}116117#[derive(Debug, Clone, PartialEq, Trace)]118#[trace(skip)]119pub enum ComplexValType {120	Any,121	Char,122	Simple(ValType),123	BoundedNumber(Option<f64>, Option<f64>),124	Array(Box<ComplexValType>),125	ArrayRef(&'static ComplexValType),126	ObjectRef(&'static [(&'static str, &'static ComplexValType)]),127	Union(Vec<ComplexValType>),128	UnionRef(&'static [&'static ComplexValType]),129	Sum(Vec<ComplexValType>),130	SumRef(&'static [&'static ComplexValType]),131}132133impl From<ValType> for ComplexValType {134	fn from(s: ValType) -> Self {135		Self::Simple(s)136	}137}138139fn write_union<'i>(140	f: &mut std::fmt::Formatter<'_>,141	is_union: bool,142	union: impl Iterator<Item = &'i ComplexValType>,143) -> std::fmt::Result {144	for (i, v) in union.enumerate() {145		let should_add_braces =146			matches!(v, ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union);147		if i != 0 {148			write!(f, " {} ", if is_union { '|' } else { '&' })?;149		}150		if should_add_braces {151			write!(f, "(")?;152		}153		write!(f, "{}", v)?;154		if should_add_braces {155			write!(f, ")")?;156		}157	}158	Ok(())159}160161fn print_array(a: &ComplexValType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {162	if *a == ComplexValType::Any {163		write!(f, "array")?164	} else {165		write!(f, "Array<{}>", a)?166	}167	Ok(())168}169170impl Display for ComplexValType {171	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {172		match self {173			ComplexValType::Any => write!(f, "any")?,174			ComplexValType::Simple(s) => write!(f, "{}", s)?,175			ComplexValType::Char => write!(f, "char")?,176			ComplexValType::BoundedNumber(a, b) => write!(177				f,178				"BoundedNumber<{}, {}>",179				a.map(|e| e.to_string()).unwrap_or_else(|| "".into()),180				b.map(|e| e.to_string()).unwrap_or_else(|| "".into())181			)?,182			ComplexValType::ArrayRef(a) => print_array(a, f)?,183			ComplexValType::Array(a) => print_array(a, f)?,184			ComplexValType::ObjectRef(fields) => {185				write!(f, "{{")?;186				for (i, (k, v)) in fields.iter().enumerate() {187					if i != 0 {188						write!(f, ", ")?;189					}190					write!(f, "{}: {}", k, v)?;191				}192				write!(f, "}}")?;193			}194			ComplexValType::Union(v) => write_union(f, true, v.iter())?,195			ComplexValType::UnionRef(v) => write_union(f, true, v.iter().copied())?,196			ComplexValType::Sum(v) => write_union(f, false, v.iter())?,197			ComplexValType::SumRef(v) => write_union(f, false, v.iter().copied())?,198		};199		Ok(())200	}201}202203peg::parser! {204pub grammar parser() for str {205	rule number() -> f64206		= n:$(['0'..='9']+) { n.parse().unwrap() }207208	rule any_ty() -> ComplexValType = "any" { ComplexValType::Any }209	rule char_ty() -> ComplexValType = "character" { ComplexValType::Char }210	rule bool_ty() -> ComplexValType = "boolean" { ComplexValType::Simple(ValType::Bool) }211	rule null_ty() -> ComplexValType = "null" { ComplexValType::Simple(ValType::Null) }212	rule str_ty() -> ComplexValType = "string" { ComplexValType::Simple(ValType::Str) }213	rule num_ty() -> ComplexValType = "number" { ComplexValType::Simple(ValType::Num) }214	rule simple_array_ty() -> ComplexValType = "array" { ComplexValType::Simple(ValType::Arr) }215	rule simple_object_ty() -> ComplexValType = "object" { ComplexValType::Simple(ValType::Obj) }216	rule simple_function_ty() -> ComplexValType = "function" { ComplexValType::Simple(ValType::Func) }217218	rule array_ty() -> ComplexValType219		= "Array<" t:ty() ">" { ComplexValType::Array(Box::new(t)) }220221	rule bounded_number_ty() -> ComplexValType222		= "BoundedNumber<" a:number() ", " b:number() ">" { ComplexValType::BoundedNumber(Some(a), Some(b)) }223224	rule ty_basic() -> ComplexValType225		= any_ty()226		/ char_ty()227		/ bool_ty()228		/ null_ty()229		/ str_ty()230		/ num_ty()231		/ simple_array_ty()232		/ simple_object_ty()233		/ simple_function_ty()234		/ array_ty()235		/ bounded_number_ty()236237	pub rule ty() -> ComplexValType238		= precedence! {239			a:(@) " | " b:@ {240				match a {241					ComplexValType::Union(mut a) => {242						a.push(b);243						ComplexValType::Union(a)244					}245					_ => ComplexValType::Union(vec![a, b]),246				}247			}248			--249			a:(@) " & " b:@ {250				match a {251					ComplexValType::Sum(mut a) => {252						a.push(b);253						ComplexValType::Sum(a)254					}255					_ => ComplexValType::Sum(vec![a, b]),256				}257			}258			--259			"(" t:ty() ")" { t }260			t:ty_basic() { t }261		}262}263}264265#[cfg(test)]266pub mod tests {267	use super::parser;268269	#[test]270	fn precedence() {271		assert_eq!(272			parser::ty("(any & any) | (any | any) & any")273				.unwrap()274				.to_string(),275			"any & any | (any | any) & any"276		);277	}278279	#[test]280	fn array() {281		assert_eq!(parser::ty("Array<any>").unwrap().to_string(), "array");282		assert_eq!(283			parser::ty("Array<number>").unwrap().to_string(),284			"Array<number>"285		);286	}287	#[test]288	fn bounded_number() {289		assert_eq!(290			parser::ty("BoundedNumber<1, 2>").unwrap().to_string(),291			"BoundedNumber<1, 2>"292		);293	}294}
after · crates/jrsonnet-types/src/lib.rs
1#![allow(clippy::redundant_closure_call)]23use std::fmt::Display;45use jrsonnet_gcmodule::Trace;67#[macro_export]8macro_rules! ty {9	((Array<number>)) => {{10		$crate::ComplexValType::ArrayRef(&$crate::ComplexValType::Simple($crate::ValType::Num))11	}};12	((Array<ubyte>)) => {{13		$crate::ComplexValType::ArrayRef(&$crate::ComplexValType::BoundedNumber(Some(0.0), Some(255.0)))14	}};15	(array) => {16		$crate::ComplexValType::Simple($crate::ValType::Arr)17	};18	(boolean) => {19		$crate::ComplexValType::Simple($crate::ValType::Bool)20	};21	(null) => {22		$crate::ComplexValType::Simple($crate::ValType::Null)23	};24	(string) => {25		$crate::ComplexValType::Simple($crate::ValType::Str)26	};27	(char) => {28		$crate::ComplexValType::Char29	};30	(number) => {31		$crate::ComplexValType::Simple($crate::ValType::Num)32	};33	(BoundedNumber<($min:expr), ($max:expr)>) => {{34		$crate::ComplexValType::BoundedNumber($min, $max)35	}};36	(object) => {37		$crate::ComplexValType::Simple($crate::ValType::Obj)38	};39	(any) => {40		$crate::ComplexValType::Any41	};42	(function) => {43		$crate::ComplexValType::Simple($crate::ValType::Func)44	};45	(($($a:tt) |+)) => {{46		static CONTENTS: &'static [&'static $crate::ComplexValType] = &[47			$(&ty!($a)),+48		];49		$crate::ComplexValType::UnionRef(CONTENTS)50	}};51	(($($a:tt) &+)) => {{52		static CONTENTS: &'static [&'static $crate::ComplexValType] = &[53			$(&ty!($a)),+54		];55		$crate::ComplexValType::SumRef(CONTENTS)56	}};57}5859#[test]60fn test() {61	assert_eq!(62		ty!((Array<number>)),63		ComplexValType::ArrayRef(&ComplexValType::Simple(ValType::Num))64	);65	assert_eq!(ty!(array), ComplexValType::Simple(ValType::Arr));66	assert_eq!(ty!(any), ComplexValType::Any);67	assert_eq!(68		ty!((string | number)),69		ComplexValType::UnionRef(&[70			&ComplexValType::Simple(ValType::Str),71			&ComplexValType::Simple(ValType::Num)72		])73	);74	assert_eq!(75		format!("{}", ty!(((string & number) | (object & null)))),76		"string & number | object & null"77	);78	assert_eq!(format!("{}", ty!((string | array))), "string | array");79	assert_eq!(80		format!("{}", ty!(((string & number) | array))),81		"string & number | array"82	);83}8485#[derive(Debug, Clone, Copy, PartialEq, Eq, Trace)]86pub enum ValType {87	Bool,88	Null,89	Str,90	Num,91	Arr,92	Obj,93	Func,94}9596impl ValType {97	pub const fn name(&self) -> &'static str {98		use ValType::*;99		match self {100			Bool => "boolean",101			Null => "null",102			Str => "string",103			Num => "number",104			Arr => "array",105			Obj => "object",106			Func => "function",107		}108	}109}110111impl Display for ValType {112	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {113		write!(f, "{}", self.name())114	}115}116117#[derive(Debug, Clone, PartialEq, Trace)]118#[trace(skip)]119pub enum ComplexValType {120	Any,121	Char,122	Simple(ValType),123	BoundedNumber(Option<f64>, Option<f64>),124	Array(Box<ComplexValType>),125	ArrayRef(&'static ComplexValType),126	ObjectRef(&'static [(&'static str, &'static ComplexValType)]),127	Union(Vec<ComplexValType>),128	UnionRef(&'static [&'static ComplexValType]),129	Sum(Vec<ComplexValType>),130	SumRef(&'static [&'static ComplexValType]),131}132133impl From<ValType> for ComplexValType {134	fn from(s: ValType) -> Self {135		Self::Simple(s)136	}137}138139fn write_union<'i>(140	f: &mut std::fmt::Formatter<'_>,141	is_union: bool,142	union: impl Iterator<Item = &'i ComplexValType>,143) -> std::fmt::Result {144	for (i, v) in union.enumerate() {145		let should_add_braces =146			matches!(v, ComplexValType::UnionRef(_) | ComplexValType::Union(_) if !is_union);147		if i != 0 {148			write!(f, " {} ", if is_union { '|' } else { '&' })?;149		}150		if should_add_braces {151			write!(f, "(")?;152		}153		write!(f, "{v}")?;154		if should_add_braces {155			write!(f, ")")?;156		}157	}158	Ok(())159}160161fn print_array(a: &ComplexValType, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {162	if *a == ComplexValType::Any {163		write!(f, "array")?164	} else {165		write!(f, "Array<{a}>")?166	}167	Ok(())168}169170impl Display for ComplexValType {171	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {172		match self {173			ComplexValType::Any => write!(f, "any")?,174			ComplexValType::Simple(s) => write!(f, "{s}")?,175			ComplexValType::Char => write!(f, "char")?,176			ComplexValType::BoundedNumber(a, b) => write!(177				f,178				"BoundedNumber<{}, {}>",179				a.map(|e| e.to_string()).unwrap_or_else(|| "".into()),180				b.map(|e| e.to_string()).unwrap_or_else(|| "".into())181			)?,182			ComplexValType::ArrayRef(a) => print_array(a, f)?,183			ComplexValType::Array(a) => print_array(a, f)?,184			ComplexValType::ObjectRef(fields) => {185				write!(f, "{{")?;186				for (i, (k, v)) in fields.iter().enumerate() {187					if i != 0 {188						write!(f, ", ")?;189					}190					write!(f, "{k}: {v}")?;191				}192				write!(f, "}}")?;193			}194			ComplexValType::Union(v) => write_union(f, true, v.iter())?,195			ComplexValType::UnionRef(v) => write_union(f, true, v.iter().copied())?,196			ComplexValType::Sum(v) => write_union(f, false, v.iter())?,197			ComplexValType::SumRef(v) => write_union(f, false, v.iter().copied())?,198		};199		Ok(())200	}201}202203peg::parser! {204pub grammar parser() for str {205	rule number() -> f64206		= n:$(['0'..='9']+) { n.parse().unwrap() }207208	rule any_ty() -> ComplexValType = "any" { ComplexValType::Any }209	rule char_ty() -> ComplexValType = "character" { ComplexValType::Char }210	rule bool_ty() -> ComplexValType = "boolean" { ComplexValType::Simple(ValType::Bool) }211	rule null_ty() -> ComplexValType = "null" { ComplexValType::Simple(ValType::Null) }212	rule str_ty() -> ComplexValType = "string" { ComplexValType::Simple(ValType::Str) }213	rule num_ty() -> ComplexValType = "number" { ComplexValType::Simple(ValType::Num) }214	rule simple_array_ty() -> ComplexValType = "array" { ComplexValType::Simple(ValType::Arr) }215	rule simple_object_ty() -> ComplexValType = "object" { ComplexValType::Simple(ValType::Obj) }216	rule simple_function_ty() -> ComplexValType = "function" { ComplexValType::Simple(ValType::Func) }217218	rule array_ty() -> ComplexValType219		= "Array<" t:ty() ">" { ComplexValType::Array(Box::new(t)) }220221	rule bounded_number_ty() -> ComplexValType222		= "BoundedNumber<" a:number() ", " b:number() ">" { ComplexValType::BoundedNumber(Some(a), Some(b)) }223224	rule ty_basic() -> ComplexValType225		= any_ty()226		/ char_ty()227		/ bool_ty()228		/ null_ty()229		/ str_ty()230		/ num_ty()231		/ simple_array_ty()232		/ simple_object_ty()233		/ simple_function_ty()234		/ array_ty()235		/ bounded_number_ty()236237	pub rule ty() -> ComplexValType238		= precedence! {239			a:(@) " | " b:@ {240				match a {241					ComplexValType::Union(mut a) => {242						a.push(b);243						ComplexValType::Union(a)244					}245					_ => ComplexValType::Union(vec![a, b]),246				}247			}248			--249			a:(@) " & " b:@ {250				match a {251					ComplexValType::Sum(mut a) => {252						a.push(b);253						ComplexValType::Sum(a)254					}255					_ => ComplexValType::Sum(vec![a, b]),256				}257			}258			--259			"(" t:ty() ")" { t }260			t:ty_basic() { t }261		}262}263}264265#[cfg(test)]266pub mod tests {267	use super::parser;268269	#[test]270	fn precedence() {271		assert_eq!(272			parser::ty("(any & any) | (any | any) & any")273				.unwrap()274				.to_string(),275			"any & any | (any | any) & any"276		);277	}278279	#[test]280	fn array() {281		assert_eq!(parser::ty("Array<any>").unwrap().to_string(), "array");282		assert_eq!(283			parser::ty("Array<number>").unwrap().to_string(),284			"Array<number>"285		);286	}287	#[test]288	fn bounded_number() {289		assert_eq!(290			parser::ty("BoundedNumber<1, 2>").unwrap().to_string(),291			"BoundedNumber<1, 2>"292		);293	}294}