git.delta.rocks / jrsonnet / refs/commits / 58696dc4e430

difftreelog

Merge pull request #146 from CertainLach/fix/tests

Yaroslav Bolyukin2024-01-16parents: #0d49135 #86f8537.patch.diff
in: master
Fix failing CI for tests and lints

22 files changed

modifiedcmds/jrsonnet-fmt/src/comments.rsdiffbeforeafterboth
--- a/cmds/jrsonnet-fmt/src/comments.rs
+++ b/cmds/jrsonnet-fmt/src/comments.rs
@@ -72,7 +72,7 @@
 					if matches!(loc, CommentLocation::ItemInline) {
 						p!(pi: str(" "));
 					}
-					p!(pi: str("/* ") string(lines[0].trim().to_string()) str(" */"))
+					p!(pi: str("/* ") string(lines[0].trim().to_string()) str(" */") nl)
 				} else if !lines.is_empty() {
 					fn common_ws_prefix<'a>(a: &'a str, b: &str) -> &'a str {
 						let offset = a
modifiedcmds/jrsonnet-fmt/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet-fmt/src/main.rs
+++ b/cmds/jrsonnet-fmt/src/main.rs
@@ -372,8 +372,8 @@
 					return p!(new: str("{ }"));
 				}
 				let mut pi = p!(new: str("{") >i nl);
-				for mem in children.into_iter() {
-					if mem.should_start_with_newline {
+				for (i, mem) in children.into_iter().enumerate() {
+					if mem.should_start_with_newline && i != 0 {
 						p!(pi: nl);
 					}
 					p!(pi: items(format_comments(&mem.before_trivia, CommentLocation::AboveItem)));
modifiedcrates/jrsonnet-cli/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/manifest.rs
+++ b/crates/jrsonnet-cli/src/manifest.rs
@@ -6,7 +6,7 @@
 };
 use jrsonnet_stdlib::{TomlFormat, YamlFormat};
 
-#[derive(Clone, ValueEnum)]
+#[derive(Clone, Copy, ValueEnum)]
 pub enum ManifestFormatName {
 	/// Expect string as output, and write them directly
 	String,
@@ -18,9 +18,11 @@
 #[derive(Parser)]
 #[clap(next_help_heading = "MANIFESTIFICATION OUTPUT")]
 pub struct ManifestOpts {
-	/// Output format, wraps resulting value to corresponding std.manifest call.
-	#[clap(long, short = 'f', default_value = "json")]
-	format: ManifestFormatName,
+	/// Output format, wraps resulting value to corresponding std.manifest call
+	///
+	/// [default: json, yaml when -y is used]
+	#[clap(long, short = 'f')]
+	format: Option<ManifestFormatName>,
 	/// Expect plain string as output.
 	/// Mutually exclusive with `--format`
 	#[clap(long, short = 'S', conflicts_with = "format")]
@@ -29,7 +31,9 @@
 	#[clap(long, short = 'y', conflicts_with = "string")]
 	yaml_stream: bool,
 	/// Number of spaces to pad output manifest with.
-	/// `0` for hard tabs, `-1` for single line output [default: 3 for json, 2 for yaml/toml]
+	/// `0` for hard tabs, `-1` for single line output
+	///
+	/// [default: 3 for json, 2 for yaml/toml]
 	#[clap(long)]
 	line_padding: Option<usize>,
 	/// Preserve order in object manifestification
@@ -44,7 +48,12 @@
 		} else {
 			#[cfg(feature = "exp-preserve-order")]
 			let preserve_order = self.preserve_order;
-			match self.format {
+			let format = match self.format {
+				Some(v) => v,
+				None if self.yaml_stream => ManifestFormatName::Yaml,
+				None => ManifestFormatName::Json,
+			};
+			match format {
 				ManifestFormatName::String => Box::new(ToStringFormat),
 				ManifestFormatName::Json => Box::new(JsonFormat::cli(
 					self.line_padding.unwrap_or(3),
modifiedcrates/jrsonnet-evaluator/src/arr/spec.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/arr/spec.rs
+++ b/crates/jrsonnet-evaluator/src/arr/spec.rs
@@ -372,7 +372,7 @@
 	pub fn new_inclusive(start: i32, end: i32) -> Self {
 		Self { start, end }
 	}
-	fn range(&self) -> impl Iterator<Item = i32> + ExactSizeIterator + DoubleEndedIterator {
+	fn range(&self) -> impl ExactSizeIterator<Item = i32> + DoubleEndedIterator {
 		WithExactSize(
 			self.start..=self.end,
 			(self.end as usize)
@@ -461,7 +461,7 @@
 			ArrayThunk::Waiting(..) => {}
 		};
 
-		let ArrayThunk::Waiting(_) =
+		let ArrayThunk::Waiting(()) =
 			replace(&mut self.cached.borrow_mut()[index], ArrayThunk::Pending)
 		else {
 			unreachable!()
@@ -508,7 +508,7 @@
 		match &self.cached.borrow()[index] {
 			ArrayThunk::Computed(c) => return Some(Thunk::evaluated(c.clone())),
 			ArrayThunk::Errored(e) => return Some(Thunk::errored(e.clone())),
-			ArrayThunk::Waiting(_) | ArrayThunk::Pending => {}
+			ArrayThunk::Waiting(()) | ArrayThunk::Pending => {}
 		};
 
 		Some(Thunk::new(ArrayElement {
@@ -597,9 +597,7 @@
 	}
 
 	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
-		let Some(key) = self.keys.get(index) else {
-			return None;
-		};
+		let key = self.keys.get(index)?;
 		Some(self.obj.get_lazy_or_bail(key.clone()))
 	}
 
@@ -649,9 +647,7 @@
 	}
 
 	fn get_lazy(&self, index: usize) -> Option<Thunk<Val>> {
-		let Some(key) = self.keys.get(index) else {
-			return None;
-		};
+		let key = self.keys.get(index)?;
 		// Nothing can fail in the key part, yet value is still
 		// lazy-evaluated
 		Some(Thunk::evaluated(
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -89,7 +89,7 @@
 	specs: &[CompSpec],
 	callback: &mut impl FnMut(Context) -> Result<()>,
 ) -> Result<()> {
-	match specs.get(0) {
+	match specs.first() {
 		None => callback(ctx)?,
 		Some(CompSpec::IfSpec(IfSpecData(cond))) => {
 			if bool::from_untyped(evaluate(ctx.clone(), cond)?)? {
modifiedcrates/jrsonnet-evaluator/src/function/builtin.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/builtin.rs
+++ b/crates/jrsonnet-evaluator/src/function/builtin.rs
@@ -6,8 +6,8 @@
 use super::{arglike::ArgsLike, parse::parse_builtin_call, CallLocation};
 use crate::{gc::TraceBox, tb, Context, Result, Val};
 
-/// Can't have str | IStr, because constant BuiltinParam causes
-/// E0492: constant functions cannot refer to interior mutable data
+/// Can't have `str` | `IStr`, because constant `BuiltinParam` causes
+/// `E0492: constant functions cannot refer to interior mutable data`
 #[derive(Clone, Trace)]
 pub struct ParamName(Option<Cow<'static, str>>);
 impl ParamName {
@@ -27,10 +27,9 @@
 }
 impl PartialEq<IStr> for ParamName {
 	fn eq(&self, other: &IStr) -> bool {
-		match &self.0 {
-			Some(s) => s.as_bytes() == other.as_bytes(),
-			None => false,
-		}
+		self.0
+			.as_ref()
+			.map_or(false, |s| s.as_bytes() == other.as_bytes())
 	}
 }
 
@@ -87,7 +86,7 @@
 			params: params
 				.into_iter()
 				.map(|n| BuiltinParam {
-					name: ParamName::new_dynamic(n.to_string()),
+					name: ParamName::new_dynamic(n),
 					has_default: false,
 				})
 				.collect(),
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -159,11 +159,11 @@
 			Val::Null => serializer.serialize_none(),
 			Val::Str(s) => serializer.serialize_str(&s.clone().into_flat()),
 			Val::Num(n) => {
-				if n.fract() != 0.0 {
-					serializer.serialize_f64(*n)
-				} else {
+				if n.fract() == 0.0 {
 					let n = *n as i64;
 					serializer.serialize_i64(n)
+				} else {
+					serializer.serialize_f64(*n)
 				}
 			}
 			#[cfg(feature = "exp-bigint")]
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -41,10 +41,12 @@
 	clippy::missing_const_for_fn,
 	// too many false-positives with .expect() calls
 	clippy::missing_panics_doc,
-    // false positive for IStr type. There is an configuration option for
-    // such cases, but it doesn't work:
-    // https://github.com/rust-lang/rust-clippy/issues/9801
-    clippy::mutable_key_type,
+	// false positive for IStr type. There is an configuration option for
+	// such cases, but it doesn't work:
+	// https://github.com/rust-lang/rust-clippy/issues/9801
+	clippy::mutable_key_type,
+	// false positives
+	clippy::redundant_pub_crate,
 )]
 
 // For jrsonnet-macros
modifiedcrates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -175,6 +175,8 @@
 	manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;
 	Ok(out)
 }
+
+#[allow(clippy::too_many_lines)]
 fn manifest_json_ex_buf(
 	val: &Val,
 	buf: &mut String,
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -171,7 +171,7 @@
 			// .field("assertions_ran", &self.assertions_ran)
 			.field("this_entries", &self.this_entries)
 			// .field("value_cache", &self.value_cache)
-			.finish()
+			.finish_non_exhaustive()
 	}
 }
 
@@ -347,7 +347,7 @@
 		out.with_super(self);
 		let mut member = out.field(key);
 		if value.flags.add() {
-			member = member.add()
+			member = member.add();
 		}
 		if let Some(loc) = value.location {
 			member = member.with_location(loc);
@@ -395,7 +395,7 @@
 
 	pub fn get(&self, key: IStr) -> Result<Option<Val>> {
 		self.run_assertions()?;
-		self.get_for(key, self.0.this().unwrap_or(self.clone()))
+		self.get_for(key, self.0.this().unwrap_or_else(|| self.clone()))
 	}
 
 	pub fn get_for(&self, key: IStr, this: ObjValue) -> Result<Option<Val>> {
@@ -474,7 +474,7 @@
 			type Output = Val;
 
 			fn get(self: Box<Self>) -> Result<Self::Output> {
-				Ok(self.obj.get_or_bail(self.key)?)
+				self.obj.get_or_bail(self.key)
 			}
 		}
 
@@ -495,7 +495,7 @@
 			SuperDepth::default(),
 			&mut |depth, index, name, visibility| {
 				let new_sort_key = FieldSortKey::new(depth, index);
-				let entry = out.entry(name.clone());
+				let entry = out.entry(name);
 				let (visible, _) = entry.or_insert((true, new_sort_key));
 				match visibility {
 					Visibility::Normal => {}
@@ -634,7 +634,7 @@
 			SuperDepth::default(),
 			&mut |depth, index, name, visibility| {
 				let new_sort_key = FieldSortKey::new(depth, index);
-				let entry = out.entry(name.clone());
+				let entry = out.entry(name);
 				let (visible, _) = entry.or_insert((true, new_sort_key));
 				match visibility {
 					Visibility::Normal => {}
modifiedcrates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/stdlib/format.rs
1//! faster std.format impl2#![allow(clippy::too_many_arguments)]34use jrsonnet_gcmodule::Trace;5use jrsonnet_interner::IStr;6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{10	bail,11	error::{format_found, suggest_object_fields, ErrorKind::*},12	typed::Typed,13	Error, ObjValue, Result, Val,14};1516#[derive(Debug, Clone, Error, Trace)]17pub enum FormatError {18	#[error("truncated format code")]19	TruncatedFormatCode,20	#[error("unrecognized conversion type: {0}")]21	UnrecognizedConversionType(char),2223	#[error("not enough values")]24	NotEnoughValues,2526	#[error("cannot use * width with object")]27	CannotUseStarWidthWithObject,28	#[error("mapping keys required")]29	MappingKeysRequired,30	#[error("no such format field: {0}")]31	NoSuchFormatField(IStr),3233	#[error("expected subfield <{0}> to be an object, got {1} instead")]34	SubfieldDidntYieldAnObject(IStr, ValType),35	#[error("subfield not found: <[{full}]{current}>{}", format_found(.found, "subfield"))]36	SubfieldNotFound {37		current: IStr,38		full: IStr,39		found: Box<Vec<IStr>>,40	},41}4243impl From<FormatError> for Error {44	fn from(e: FormatError) -> Self {45		Self::new(Format(e))46	}47}4849use FormatError::*;5051type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;5253pub fn try_parse_mapping_key(str: &str) -> ParseResult<'_, &str> {54	if str.is_empty() {55		return Err(TruncatedFormatCode);56	}57	let bytes = str.as_bytes();58	if bytes[0] == b'(' {59		let mut i = 1;60		while i < bytes.len() {61			if bytes[i] == b')' {62				return Ok((&str[1..i], &str[i + 1..]));63			}64			i += 1;65		}66		Err(TruncatedFormatCode)67	} else {68		Ok(("", str))69	}70}7172#[cfg(test)]73pub mod tests_key {74	use super::*;7576	#[test]77	fn parse_key() {78		assert_eq!(79			try_parse_mapping_key("(hello ) world").unwrap(),80			("hello ", " world")81		);82		assert_eq!(try_parse_mapping_key("() world").unwrap(), ("", " world"));83		assert_eq!(try_parse_mapping_key(" world").unwrap(), ("", " world"));84		assert_eq!(85			try_parse_mapping_key(" () world").unwrap(),86			("", " () world")87		);88	}8990	#[test]91	#[should_panic]92	fn parse_key_missing_start() {93		try_parse_mapping_key("").unwrap();94	}9596	#[test]97	#[should_panic]98	fn parse_key_missing_end() {99		try_parse_mapping_key("(   ").unwrap();100	}101}102103#[allow(clippy::struct_excessive_bools)]104#[derive(Default, Debug)]105pub struct CFlags {106	pub alt: bool,107	pub zero: bool,108	pub left: bool,109	pub blank: bool,110	pub sign: bool,111}112113pub fn try_parse_cflags(str: &str) -> ParseResult<'_, CFlags> {114	if str.is_empty() {115		return Err(TruncatedFormatCode);116	}117	let bytes = str.as_bytes();118	let mut i = 0;119	let mut out = CFlags::default();120	loop {121		if bytes.len() == i {122			return Err(TruncatedFormatCode);123		}124		match bytes[i] {125			b'#' => out.alt = true,126			b'0' => out.zero = true,127			b'-' => out.left = true,128			b' ' => out.blank = true,129			b'+' => out.sign = true,130			_ => break,131		}132		i += 1;133	}134	Ok((out, &str[i..]))135}136137#[derive(Debug, PartialEq, Eq)]138pub enum Width {139	Star,140	Fixed(usize),141}142pub fn try_parse_field_width(str: &str) -> ParseResult<'_, Width> {143	if str.is_empty() {144		return Err(TruncatedFormatCode);145	}146	let bytes = str.as_bytes();147	if bytes[0] == b'*' {148		return Ok((Width::Star, &str[1..]));149	}150	let mut out: usize = 0;151	let mut digits = 0;152	while let Some(digit) = (bytes[digits] as char).to_digit(10) {153		out *= 10;154		out += digit as usize;155		digits += 1;156		if digits == bytes.len() {157			return Err(TruncatedFormatCode);158		}159	}160	Ok((Width::Fixed(out), &str[digits..]))161}162163pub fn try_parse_precision(str: &str) -> ParseResult<'_, Option<Width>> {164	if str.is_empty() {165		return Err(TruncatedFormatCode);166	}167	let bytes = str.as_bytes();168	if bytes[0] == b'.' {169		try_parse_field_width(&str[1..]).map(|(r, s)| (Some(r), s))170	} else {171		Ok((None, str))172	}173}174175// Only skips176pub fn try_parse_length_modifier(str: &str) -> ParseResult<'_, ()> {177	if str.is_empty() {178		return Err(TruncatedFormatCode);179	}180	let bytes = str.as_bytes();181	let mut idx = 0;182	while bytes[idx] == b'h' || bytes[idx] == b'l' || bytes[idx] == b'L' {183		idx += 1;184		if bytes.len() == idx {185			return Err(TruncatedFormatCode);186		}187	}188	Ok(((), &str[idx..]))189}190191#[derive(Debug, PartialEq, Eq)]192pub enum ConvTypeV {193	Decimal,194	Octal,195	Hexadecimal,196	Scientific,197	Float,198	Shorter,199	Char,200	String,201	Percent,202}203pub struct ConvType {204	v: ConvTypeV,205	caps: bool,206}207208pub fn parse_conversion_type(str: &str) -> ParseResult<'_, ConvType> {209	if str.is_empty() {210		return Err(TruncatedFormatCode);211	}212213	let code = str.as_bytes()[0];214	let v: (ConvTypeV, bool) = match code {215		b'd' | b'i' | b'u' => (ConvTypeV::Decimal, false),216		b'o' => (ConvTypeV::Octal, false),217		b'x' => (ConvTypeV::Hexadecimal, false),218		b'X' => (ConvTypeV::Hexadecimal, true),219		b'e' => (ConvTypeV::Scientific, false),220		b'E' => (ConvTypeV::Scientific, true),221		b'f' => (ConvTypeV::Float, false),222		b'F' => (ConvTypeV::Float, true),223		b'g' => (ConvTypeV::Shorter, false),224		b'G' => (ConvTypeV::Shorter, true),225		b'c' => (ConvTypeV::Char, false),226		b's' => (ConvTypeV::String, false),227		b'%' => (ConvTypeV::Percent, false),228		c => return Err(UnrecognizedConversionType(c as char)),229	};230231	Ok((ConvType { v: v.0, caps: v.1 }, &str[1..]))232}233234#[derive(Debug)]235pub struct Code<'s> {236	mkey: &'s str,237	cflags: CFlags,238	width: Width,239	precision: Option<Width>,240	convtype: ConvTypeV,241	caps: bool,242}243pub fn parse_code(str: &str) -> ParseResult<'_, Code<'_>> {244	if str.is_empty() {245		return Err(TruncatedFormatCode);246	}247	let (mkey, str) = try_parse_mapping_key(str)?;248	let (cflags, str) = try_parse_cflags(str)?;249	let (width, str) = try_parse_field_width(str)?;250	let (precision, str) = try_parse_precision(str)?;251	let (_, str) = try_parse_length_modifier(str)?;252	let (convtype, str) = parse_conversion_type(str)?;253254	Ok((255		Code {256			mkey,257			cflags,258			width,259			precision,260			convtype: convtype.v,261			caps: convtype.caps,262		},263		str,264	))265}266267#[derive(Debug)]268pub enum Element<'s> {269	String(&'s str),270	Code(Code<'s>),271}272pub fn parse_codes(mut str: &str) -> Result<Vec<Element<'_>>> {273	let mut bytes = str.as_bytes();274	let mut out = vec![];275	let mut offset = 0;276277	loop {278		while offset != bytes.len() && bytes[offset] != b'%' {279			offset += 1;280		}281		if offset != 0 {282			out.push(Element::String(&str[0..offset]));283		}284		if offset == bytes.len() {285			return Ok(out);286		}287		str = &str[offset + 1..];288		let code;289		(code, str) = parse_code(str)?;290		bytes = str.as_bytes();291		offset = 0;292293		out.push(Element::Code(code));294	}295}296297const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";298299#[inline]300pub fn render_integer(301	out: &mut String,302	iv: f64,303	padding: usize,304	precision: usize,305	blank: bool,306	sign: bool,307	radix: i64,308	prefix: &str,309	caps: bool,310) {311	let radix = radix as f64;312	let iv = iv.floor();313	// Digit char indexes in reverse order, i.e314	// for radix = 16 and n = 12f: [15, 2, 1]315	let digits = if iv == 0.0 {316		vec![0u8]317	} else {318		let mut v = iv.abs();319		let mut nums = Vec::with_capacity(1);320		while v != 0.0 {321			nums.push((v % radix) as u8);322			v = (v / radix).floor();323		}324		nums325	};326	let neg = iv < 0.0;327	#[allow(clippy::bool_to_int_with_if)]328	let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });329	let zp2 = zp330		.max(precision)331		.saturating_sub(prefix.len() + digits.len());332333	if neg {334		out.push('-');335	} else if sign {336		out.push('+');337	} else if blank {338		out.push(' ');339	}340341	out.reserve(zp2);342	for _ in 0..zp2 {343		out.push('0');344	}345	out.push_str(prefix);346347	for digit in digits.into_iter().rev() {348		let ch = NUMBERS[digit as usize] as char;349		out.push(if caps { ch.to_ascii_uppercase() } else { ch });350	}351}352353pub fn render_decimal(354	out: &mut String,355	iv: f64,356	padding: usize,357	precision: usize,358	blank: bool,359	sign: bool,360) {361	render_integer(out, iv, padding, precision, blank, sign, 10, "", false);362}363pub fn render_octal(364	out: &mut String,365	iv: f64,366	padding: usize,367	precision: usize,368	alt: bool,369	blank: bool,370	sign: bool,371) {372	render_integer(373		out,374		iv,375		padding,376		precision,377		blank,378		sign,379		8,380		if alt && iv != 0.0 { "0" } else { "" },381		false,382	);383}384385#[allow(clippy::fn_params_excessive_bools)]386pub fn render_hexadecimal(387	out: &mut String,388	iv: f64,389	padding: usize,390	precision: usize,391	alt: bool,392	blank: bool,393	sign: bool,394	caps: bool,395) {396	render_integer(397		out,398		iv,399		padding,400		precision,401		blank,402		sign,403		16,404		match (alt, caps) {405			(true, true) => "0X",406			(true, false) => "0x",407			(false, _) => "",408		},409		caps,410	);411}412413#[allow(clippy::fn_params_excessive_bools)]414pub fn render_float(415	out: &mut String,416	n: f64,417	mut padding: usize,418	precision: usize,419	blank: bool,420	sign: bool,421	ensure_pt: bool,422	trailing: bool,423) {424	#[allow(clippy::bool_to_int_with_if)]425	let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };426	padding = padding.saturating_sub(dot_size + precision);427	render_decimal(out, n.floor(), padding, 0, blank, sign);428	if precision == 0 {429		if ensure_pt {430			out.push('.');431		}432		return;433	}434	let frac = n435		.fract()436		.mul_add(10.0_f64.powf(precision as f64), 0.5)437		.floor();438	if trailing || frac > 0.0 {439		out.push('.');440		let mut frac_str = String::new();441		render_decimal(&mut frac_str, frac, precision, 0, false, false);442		let mut trim = frac_str.len();443		if !trailing {444			for b in frac_str.as_bytes().iter().rev() {445				if *b == b'0' {446					trim -= 1;447				} else {448					break;449				}450			}451		}452		out.push_str(&frac_str[..trim]);453	} else if ensure_pt {454		out.push('.');455	}456}457458#[allow(clippy::fn_params_excessive_bools)]459pub fn render_float_sci(460	out: &mut String,461	n: f64,462	mut padding: usize,463	precision: usize,464	blank: bool,465	sign: bool,466	ensure_pt: bool,467	trailing: bool,468	caps: bool,469) {470	let exponent = n.log10().floor();471	let mantissa = if exponent as i16 == -324 {472		n * 10.0 / 10.0_f64.powf(exponent + 1.0)473	} else {474		n / 10.0_f64.powf(exponent)475	};476	let mut exponent_str = String::new();477	render_decimal(&mut exponent_str, exponent, 3, 0, false, true);478479	// +1 for e480	padding = padding.saturating_sub(exponent_str.len() + 1);481482	render_float(483		out, mantissa, padding, precision, blank, sign, ensure_pt, trailing,484	);485	out.push(if caps { 'E' } else { 'e' });486	out.push_str(&exponent_str);487}488489#[allow(clippy::too_many_lines)]490pub fn format_code(491	out: &mut String,492	value: &Val,493	code: &Code<'_>,494	width: usize,495	precision: Option<usize>,496) -> Result<()> {497	let clfags = &code.cflags;498	let (fpprec, iprec) = precision.map_or((6, 0), |v| (v, v));499	let padding = if clfags.zero && !clfags.left {500		width501	} else {502		0503	};504505	// TODO: If left padded, can optimize by writing directly to out506	let mut tmp_out = String::new();507508	match code.convtype {509		ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),510		ConvTypeV::Decimal => {511			let value = f64::from_untyped(value.clone())?;512			render_decimal(513				&mut tmp_out,514				value,515				padding,516				iprec,517				clfags.blank,518				clfags.sign,519			);520		}521		ConvTypeV::Octal => {522			let value = f64::from_untyped(value.clone())?;523			render_octal(524				&mut tmp_out,525				value,526				padding,527				iprec,528				clfags.alt,529				clfags.blank,530				clfags.sign,531			);532		}533		ConvTypeV::Hexadecimal => {534			let value = f64::from_untyped(value.clone())?;535			render_hexadecimal(536				&mut tmp_out,537				value,538				padding,539				iprec,540				clfags.alt,541				clfags.blank,542				clfags.sign,543				code.caps,544			);545		}546		ConvTypeV::Scientific => {547			let value = f64::from_untyped(value.clone())?;548			render_float_sci(549				&mut tmp_out,550				value,551				padding,552				fpprec,553				clfags.blank,554				clfags.sign,555				clfags.alt,556				true,557				code.caps,558			);559		}560		ConvTypeV::Float => {561			let value = f64::from_untyped(value.clone())?;562			render_float(563				&mut tmp_out,564				value,565				padding,566				fpprec,567				clfags.blank,568				clfags.sign,569				clfags.alt,570				true,571			);572		}573		ConvTypeV::Shorter => {574			let value = f64::from_untyped(value.clone())?;575			let exponent = if value == 0.0 {576				0.0577			} else {578				value.abs().log10().floor()579			};580			if exponent < -4.0 || exponent >= fpprec as f64 {581				render_float_sci(582					&mut tmp_out,583					value,584					padding,585					fpprec - 1,586					clfags.blank,587					clfags.sign,588					clfags.alt,589					clfags.alt,590					code.caps,591				);592			} else {593				let digits_before_pt = 1.max(exponent as usize + 1);594				render_float(595					&mut tmp_out,596					value,597					padding,598					fpprec - digits_before_pt,599					clfags.blank,600					clfags.sign,601					clfags.alt,602					clfags.alt,603				);604			}605		}606		ConvTypeV::Char => match value.clone() {607			Val::Num(n) => tmp_out.push(608				std::char::from_u32(n as u32)609					.ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,610			),611			Val::Str(s) => {612				let s = s.into_flat();613				if s.chars().count() != 1 {614					bail!("%c expected 1 char string, got {}", s.chars().count());615				}616				tmp_out.push_str(&s);617			}618			_ => {619				bail!(TypeMismatch(620					"%c requires number/string",621					vec![ValType::Num, ValType::Str],622					value.value_type(),623				));624			}625		},626		ConvTypeV::Percent => tmp_out.push('%'),627	};628629	let padding = width.saturating_sub(tmp_out.len());630631	if !clfags.left {632		for _ in 0..padding {633			out.push(' ');634		}635	}636	out.push_str(&tmp_out);637	if clfags.left {638		for _ in 0..padding {639			out.push(' ');640		}641	}642643	Ok(())644}645646pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {647	let codes = parse_codes(str)?;648	let mut out = String::new();649	let value_count = values.len();650651	for code in codes {652		match code {653			Element::String(s) => {654				out.push_str(s);655			}656			Element::Code(c) => {657				let width = match c.width {658					Width::Star => {659						if values.is_empty() {660							bail!(NotEnoughValues);661						}662						let value = &values[0];663						values = &values[1..];664						usize::from_untyped(value.clone())?665					}666					Width::Fixed(n) => n,667				};668				let precision = match c.precision {669					Some(Width::Star) => {670						if values.is_empty() {671							bail!(NotEnoughValues);672						}673						let value = &values[0];674						values = &values[1..];675						Some(usize::from_untyped(value.clone())?)676					}677					Some(Width::Fixed(n)) => Some(n),678					None => None,679				};680681				// %% should not consume a value682				let value = if c.convtype == ConvTypeV::Percent {683					&Val::Null684				} else {685					if values.is_empty() {686						bail!(NotEnoughValues);687					}688					let value = &values[0];689					values = &values[1..];690					value691				};692693				format_code(&mut out, value, &c, width, precision)?;694			}695		}696	}697698	if !values.is_empty() {699		bail!(700			"too many values to format, expected {value_count}, got {}",701			value_count + values.len()702		)703	}704705	Ok(out)706}707708fn get_dotted_field(obj: ObjValue, field: &str) -> Result<Val> {709	let mut current = Val::Obj(obj);710	let mut name_offset = 0;711	for component in field.split('.') {712		let end_offset = name_offset + component.len();713		current = if let Val::Obj(obj) = current {714			if let Some(value) = obj.get(component.into())? {715				value716			} else {717				let current = &field[name_offset..end_offset];718				let full = &field[..name_offset];719				let found = Box::new(suggest_object_fields(&obj, current.into()));720				bail!(SubfieldNotFound {721					current: current.into(),722					full: full.into(),723					found,724				})725			}726		} else {727			// No underflow may happen, initially we always start with an object728			let subfield = &field[..name_offset - 1];729			bail!(SubfieldDidntYieldAnObject(730				subfield.into(),731				current.value_type()732			));733		};734		name_offset = end_offset + 1;735	}736	Ok(current)737}738739pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {740	let codes = parse_codes(str)?;741	let mut out = String::new();742743	for code in codes {744		match code {745			Element::String(s) => {746				out.push_str(s);747			}748			Element::Code(c) => {749				// TODO: Operate on ref750				let f: IStr = c.mkey.into();751				let width = match c.width {752					Width::Star => {753						bail!(CannotUseStarWidthWithObject);754					}755					Width::Fixed(n) => n,756				};757				let precision = match c.precision {758					Some(Width::Star) => {759						bail!(CannotUseStarWidthWithObject);760					}761					Some(Width::Fixed(n)) => Some(n),762					None => None,763				};764765				let value = if c.convtype == ConvTypeV::Percent {766					Val::Null767				} else {768					if f.is_empty() {769						bail!(MappingKeysRequired);770					}771					if let Some(v) = values.get(f.clone())? {772						v773					} else {774						get_dotted_field(values.clone(), &f)?775					}776				};777778				format_code(&mut out, &value, &c, width, precision)?;779			}780		}781	}782783	Ok(out)784}785786#[cfg(test)]787pub mod test_format {788	use super::*;789790	#[test]791	fn parse() {792		assert_eq!(793			parse_codes(794				"How much error budget is left looking at our %.3f%% availability gurantees?"795			)796			.unwrap()797			.len(),798			4799		);800	}801802	#[test]803	fn octals() {804		assert_eq!(format_arr("%#o", &[Val::Num(8.0)]).unwrap(), "010");805		assert_eq!(format_arr("%#4o", &[Val::Num(8.0)]).unwrap(), " 010");806		assert_eq!(format_arr("%4o", &[Val::Num(8.0)]).unwrap(), "  10");807		assert_eq!(format_arr("%04o", &[Val::Num(8.0)]).unwrap(), "0010");808		assert_eq!(format_arr("%+4o", &[Val::Num(8.0)]).unwrap(), " +10");809		assert_eq!(format_arr("%+04o", &[Val::Num(8.0)]).unwrap(), "+010");810		assert_eq!(format_arr("%-4o", &[Val::Num(8.0)]).unwrap(), "10  ");811		assert_eq!(format_arr("%+-4o", &[Val::Num(8.0)]).unwrap(), "+10 ");812		assert_eq!(format_arr("%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");813	}814815	#[test]816	fn percent_doesnt_consumes_values() {817		assert_eq!(818			format_arr(819				"How much error budget is left looking at our %.3f%% availability gurantees?",820				&[Val::Num(4.0)]821			)822			.unwrap(),823			"How much error budget is left looking at our 4.000% availability gurantees?"824		);825	}826}
after · crates/jrsonnet-evaluator/src/stdlib/format.rs
1//! faster std.format impl2#![allow(clippy::too_many_arguments)]34use jrsonnet_gcmodule::Trace;5use jrsonnet_interner::IStr;6use jrsonnet_types::ValType;7use thiserror::Error;89use crate::{10	bail,11	error::{format_found, suggest_object_fields, ErrorKind::*},12	typed::Typed,13	Error, ObjValue, Result, Val,14};1516#[derive(Debug, Clone, Error, Trace)]17pub enum FormatError {18	#[error("truncated format code")]19	TruncatedFormatCode,20	#[error("unrecognized conversion type: {0}")]21	UnrecognizedConversionType(char),2223	#[error("not enough values")]24	NotEnoughValues,2526	#[error("cannot use * width with object")]27	CannotUseStarWidthWithObject,28	#[error("mapping keys required")]29	MappingKeysRequired,30	#[error("no such format field: {0}")]31	NoSuchFormatField(IStr),3233	#[error("expected subfield <{0}> to be an object, got {1} instead")]34	SubfieldDidntYieldAnObject(IStr, ValType),35	#[error("subfield not found: <[{full}]{current}>{}", format_found(.found, "subfield"))]36	SubfieldNotFound {37		current: IStr,38		full: IStr,39		found: Box<Vec<IStr>>,40	},41}4243impl From<FormatError> for Error {44	fn from(e: FormatError) -> Self {45		Self::new(Format(e))46	}47}4849use FormatError::*;5051type ParseResult<'t, T> = std::result::Result<(T, &'t str), FormatError>;5253pub fn try_parse_mapping_key(str: &str) -> ParseResult<'_, &str> {54	if str.is_empty() {55		return Err(TruncatedFormatCode);56	}57	let bytes = str.as_bytes();58	if bytes[0] == b'(' {59		let mut i = 1;60		while i < bytes.len() {61			if bytes[i] == b')' {62				return Ok((&str[1..i], &str[i + 1..]));63			}64			i += 1;65		}66		Err(TruncatedFormatCode)67	} else {68		Ok(("", str))69	}70}7172#[cfg(test)]73pub mod tests_key {74	use super::*;7576	#[test]77	fn parse_key() {78		assert_eq!(79			try_parse_mapping_key("(hello ) world").unwrap(),80			("hello ", " world")81		);82		assert_eq!(try_parse_mapping_key("() world").unwrap(), ("", " world"));83		assert_eq!(try_parse_mapping_key(" world").unwrap(), ("", " world"));84		assert_eq!(85			try_parse_mapping_key(" () world").unwrap(),86			("", " () world")87		);88	}8990	#[test]91	#[should_panic]92	fn parse_key_missing_start() {93		try_parse_mapping_key("").unwrap();94	}9596	#[test]97	#[should_panic]98	fn parse_key_missing_end() {99		try_parse_mapping_key("(   ").unwrap();100	}101}102103#[allow(clippy::struct_excessive_bools)]104#[derive(Default, Debug)]105pub struct CFlags {106	pub alt: bool,107	pub zero: bool,108	pub left: bool,109	pub blank: bool,110	pub sign: bool,111}112113pub fn try_parse_cflags(str: &str) -> ParseResult<'_, CFlags> {114	if str.is_empty() {115		return Err(TruncatedFormatCode);116	}117	let bytes = str.as_bytes();118	let mut i = 0;119	let mut out = CFlags::default();120	loop {121		if bytes.len() == i {122			return Err(TruncatedFormatCode);123		}124		match bytes[i] {125			b'#' => out.alt = true,126			b'0' => out.zero = true,127			b'-' => out.left = true,128			b' ' => out.blank = true,129			b'+' => out.sign = true,130			_ => break,131		}132		i += 1;133	}134	Ok((out, &str[i..]))135}136137#[derive(Debug, PartialEq, Eq)]138pub enum Width {139	Star,140	Fixed(usize),141}142pub fn try_parse_field_width(str: &str) -> ParseResult<'_, Width> {143	if str.is_empty() {144		return Err(TruncatedFormatCode);145	}146	let bytes = str.as_bytes();147	if bytes[0] == b'*' {148		return Ok((Width::Star, &str[1..]));149	}150	let mut out: usize = 0;151	let mut digits = 0;152	while let Some(digit) = (bytes[digits] as char).to_digit(10) {153		out *= 10;154		out += digit as usize;155		digits += 1;156		if digits == bytes.len() {157			return Err(TruncatedFormatCode);158		}159	}160	Ok((Width::Fixed(out), &str[digits..]))161}162163pub fn try_parse_precision(str: &str) -> ParseResult<'_, Option<Width>> {164	if str.is_empty() {165		return Err(TruncatedFormatCode);166	}167	let bytes = str.as_bytes();168	if bytes[0] == b'.' {169		try_parse_field_width(&str[1..]).map(|(r, s)| (Some(r), s))170	} else {171		Ok((None, str))172	}173}174175// Only skips176pub fn try_parse_length_modifier(str: &str) -> ParseResult<'_, ()> {177	if str.is_empty() {178		return Err(TruncatedFormatCode);179	}180	let bytes = str.as_bytes();181	let mut idx = 0;182	while bytes[idx] == b'h' || bytes[idx] == b'l' || bytes[idx] == b'L' {183		idx += 1;184		if bytes.len() == idx {185			return Err(TruncatedFormatCode);186		}187	}188	Ok(((), &str[idx..]))189}190191#[derive(Debug, PartialEq, Eq)]192pub enum ConvTypeV {193	Decimal,194	Octal,195	Hexadecimal,196	Scientific,197	Float,198	Shorter,199	Char,200	String,201	Percent,202}203pub struct ConvType {204	v: ConvTypeV,205	caps: bool,206}207208pub fn parse_conversion_type(str: &str) -> ParseResult<'_, ConvType> {209	if str.is_empty() {210		return Err(TruncatedFormatCode);211	}212213	let code = str.as_bytes()[0];214	let v: (ConvTypeV, bool) = match code {215		b'd' | b'i' | b'u' => (ConvTypeV::Decimal, false),216		b'o' => (ConvTypeV::Octal, false),217		b'x' => (ConvTypeV::Hexadecimal, false),218		b'X' => (ConvTypeV::Hexadecimal, true),219		b'e' => (ConvTypeV::Scientific, false),220		b'E' => (ConvTypeV::Scientific, true),221		b'f' => (ConvTypeV::Float, false),222		b'F' => (ConvTypeV::Float, true),223		b'g' => (ConvTypeV::Shorter, false),224		b'G' => (ConvTypeV::Shorter, true),225		b'c' => (ConvTypeV::Char, false),226		b's' => (ConvTypeV::String, false),227		b'%' => (ConvTypeV::Percent, false),228		c => return Err(UnrecognizedConversionType(c as char)),229	};230231	Ok((ConvType { v: v.0, caps: v.1 }, &str[1..]))232}233234#[derive(Debug)]235pub struct Code<'s> {236	mkey: &'s str,237	cflags: CFlags,238	width: Width,239	precision: Option<Width>,240	convtype: ConvTypeV,241	caps: bool,242}243pub fn parse_code(str: &str) -> ParseResult<'_, Code<'_>> {244	if str.is_empty() {245		return Err(TruncatedFormatCode);246	}247	let (mkey, str) = try_parse_mapping_key(str)?;248	let (cflags, str) = try_parse_cflags(str)?;249	let (width, str) = try_parse_field_width(str)?;250	let (precision, str) = try_parse_precision(str)?;251	let ((), str) = try_parse_length_modifier(str)?;252	let (convtype, str) = parse_conversion_type(str)?;253254	Ok((255		Code {256			mkey,257			cflags,258			width,259			precision,260			convtype: convtype.v,261			caps: convtype.caps,262		},263		str,264	))265}266267#[derive(Debug)]268pub enum Element<'s> {269	String(&'s str),270	Code(Code<'s>),271}272pub fn parse_codes(mut str: &str) -> Result<Vec<Element<'_>>> {273	let mut bytes = str.as_bytes();274	let mut out = vec![];275	let mut offset = 0;276277	loop {278		while offset != bytes.len() && bytes[offset] != b'%' {279			offset += 1;280		}281		if offset != 0 {282			out.push(Element::String(&str[0..offset]));283		}284		if offset == bytes.len() {285			return Ok(out);286		}287		str = &str[offset + 1..];288		let code;289		(code, str) = parse_code(str)?;290		bytes = str.as_bytes();291		offset = 0;292293		out.push(Element::Code(code));294	}295}296297const NUMBERS: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";298299#[inline]300pub fn render_integer(301	out: &mut String,302	iv: f64,303	padding: usize,304	precision: usize,305	blank: bool,306	sign: bool,307	radix: i64,308	prefix: &str,309	caps: bool,310) {311	let radix = radix as f64;312	let iv = iv.floor();313	// Digit char indexes in reverse order, i.e314	// for radix = 16 and n = 12f: [15, 2, 1]315	let digits = if iv == 0.0 {316		vec![0u8]317	} else {318		let mut v = iv.abs();319		let mut nums = Vec::with_capacity(1);320		while v != 0.0 {321			nums.push((v % radix) as u8);322			v = (v / radix).floor();323		}324		nums325	};326	let neg = iv < 0.0;327	#[allow(clippy::bool_to_int_with_if)]328	let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });329	let zp2 = zp330		.max(precision)331		.saturating_sub(prefix.len() + digits.len());332333	if neg {334		out.push('-');335	} else if sign {336		out.push('+');337	} else if blank {338		out.push(' ');339	}340341	out.reserve(zp2);342	for _ in 0..zp2 {343		out.push('0');344	}345	out.push_str(prefix);346347	for digit in digits.into_iter().rev() {348		let ch = NUMBERS[digit as usize] as char;349		out.push(if caps { ch.to_ascii_uppercase() } else { ch });350	}351}352353pub fn render_decimal(354	out: &mut String,355	iv: f64,356	padding: usize,357	precision: usize,358	blank: bool,359	sign: bool,360) {361	render_integer(out, iv, padding, precision, blank, sign, 10, "", false);362}363pub fn render_octal(364	out: &mut String,365	iv: f64,366	padding: usize,367	precision: usize,368	alt: bool,369	blank: bool,370	sign: bool,371) {372	render_integer(373		out,374		iv,375		padding,376		precision,377		blank,378		sign,379		8,380		if alt && iv != 0.0 { "0" } else { "" },381		false,382	);383}384385#[allow(clippy::fn_params_excessive_bools)]386pub fn render_hexadecimal(387	out: &mut String,388	iv: f64,389	padding: usize,390	precision: usize,391	alt: bool,392	blank: bool,393	sign: bool,394	caps: bool,395) {396	render_integer(397		out,398		iv,399		padding,400		precision,401		blank,402		sign,403		16,404		match (alt, caps) {405			(true, true) => "0X",406			(true, false) => "0x",407			(false, _) => "",408		},409		caps,410	);411}412413#[allow(clippy::fn_params_excessive_bools)]414pub fn render_float(415	out: &mut String,416	n: f64,417	mut padding: usize,418	precision: usize,419	blank: bool,420	sign: bool,421	ensure_pt: bool,422	trailing: bool,423) {424	#[allow(clippy::bool_to_int_with_if)]425	let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };426	padding = padding.saturating_sub(dot_size + precision);427	render_decimal(out, n.floor(), padding, 0, blank, sign);428	if precision == 0 {429		if ensure_pt {430			out.push('.');431		}432		return;433	}434	let frac = n435		.fract()436		.mul_add(10.0_f64.powf(precision as f64), 0.5)437		.floor();438	if trailing || frac > 0.0 {439		out.push('.');440		let mut frac_str = String::new();441		render_decimal(&mut frac_str, frac, precision, 0, false, false);442		let mut trim = frac_str.len();443		if !trailing {444			for b in frac_str.as_bytes().iter().rev() {445				if *b == b'0' {446					trim -= 1;447				} else {448					break;449				}450			}451		}452		out.push_str(&frac_str[..trim]);453	} else if ensure_pt {454		out.push('.');455	}456}457458#[allow(clippy::fn_params_excessive_bools)]459pub fn render_float_sci(460	out: &mut String,461	n: f64,462	mut padding: usize,463	precision: usize,464	blank: bool,465	sign: bool,466	ensure_pt: bool,467	trailing: bool,468	caps: bool,469) {470	let exponent = n.log10().floor();471	let mantissa = if exponent as i16 == -324 {472		n * 10.0 / 10.0_f64.powf(exponent + 1.0)473	} else {474		n / 10.0_f64.powf(exponent)475	};476	let mut exponent_str = String::new();477	render_decimal(&mut exponent_str, exponent, 3, 0, false, true);478479	// +1 for e480	padding = padding.saturating_sub(exponent_str.len() + 1);481482	render_float(483		out, mantissa, padding, precision, blank, sign, ensure_pt, trailing,484	);485	out.push(if caps { 'E' } else { 'e' });486	out.push_str(&exponent_str);487}488489#[allow(clippy::too_many_lines)]490pub fn format_code(491	out: &mut String,492	value: &Val,493	code: &Code<'_>,494	width: usize,495	precision: Option<usize>,496) -> Result<()> {497	let clfags = &code.cflags;498	let (fpprec, iprec) = precision.map_or((6, 0), |v| (v, v));499	let padding = if clfags.zero && !clfags.left {500		width501	} else {502		0503	};504505	// TODO: If left padded, can optimize by writing directly to out506	let mut tmp_out = String::new();507508	match code.convtype {509		ConvTypeV::String => tmp_out.push_str(&value.clone().to_string()?),510		ConvTypeV::Decimal => {511			let value = f64::from_untyped(value.clone())?;512			render_decimal(513				&mut tmp_out,514				value,515				padding,516				iprec,517				clfags.blank,518				clfags.sign,519			);520		}521		ConvTypeV::Octal => {522			let value = f64::from_untyped(value.clone())?;523			render_octal(524				&mut tmp_out,525				value,526				padding,527				iprec,528				clfags.alt,529				clfags.blank,530				clfags.sign,531			);532		}533		ConvTypeV::Hexadecimal => {534			let value = f64::from_untyped(value.clone())?;535			render_hexadecimal(536				&mut tmp_out,537				value,538				padding,539				iprec,540				clfags.alt,541				clfags.blank,542				clfags.sign,543				code.caps,544			);545		}546		ConvTypeV::Scientific => {547			let value = f64::from_untyped(value.clone())?;548			render_float_sci(549				&mut tmp_out,550				value,551				padding,552				fpprec,553				clfags.blank,554				clfags.sign,555				clfags.alt,556				true,557				code.caps,558			);559		}560		ConvTypeV::Float => {561			let value = f64::from_untyped(value.clone())?;562			render_float(563				&mut tmp_out,564				value,565				padding,566				fpprec,567				clfags.blank,568				clfags.sign,569				clfags.alt,570				true,571			);572		}573		ConvTypeV::Shorter => {574			let value = f64::from_untyped(value.clone())?;575			let exponent = if value == 0.0 {576				0.0577			} else {578				value.abs().log10().floor()579			};580			if exponent < -4.0 || exponent >= fpprec as f64 {581				render_float_sci(582					&mut tmp_out,583					value,584					padding,585					fpprec - 1,586					clfags.blank,587					clfags.sign,588					clfags.alt,589					clfags.alt,590					code.caps,591				);592			} else {593				let digits_before_pt = 1.max(exponent as usize + 1);594				render_float(595					&mut tmp_out,596					value,597					padding,598					fpprec - digits_before_pt,599					clfags.blank,600					clfags.sign,601					clfags.alt,602					clfags.alt,603				);604			}605		}606		ConvTypeV::Char => match value.clone() {607			Val::Num(n) => tmp_out.push(608				std::char::from_u32(n as u32)609					.ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,610			),611			Val::Str(s) => {612				let s = s.into_flat();613				if s.chars().count() != 1 {614					bail!("%c expected 1 char string, got {}", s.chars().count());615				}616				tmp_out.push_str(&s);617			}618			_ => {619				bail!(TypeMismatch(620					"%c requires number/string",621					vec![ValType::Num, ValType::Str],622					value.value_type(),623				));624			}625		},626		ConvTypeV::Percent => tmp_out.push('%'),627	};628629	let padding = width.saturating_sub(tmp_out.len());630631	if !clfags.left {632		for _ in 0..padding {633			out.push(' ');634		}635	}636	out.push_str(&tmp_out);637	if clfags.left {638		for _ in 0..padding {639			out.push(' ');640		}641	}642643	Ok(())644}645646pub fn format_arr(str: &str, mut values: &[Val]) -> Result<String> {647	let codes = parse_codes(str)?;648	let mut out = String::new();649	let value_count = values.len();650651	for code in codes {652		match code {653			Element::String(s) => {654				out.push_str(s);655			}656			Element::Code(c) => {657				let width = match c.width {658					Width::Star => {659						if values.is_empty() {660							bail!(NotEnoughValues);661						}662						let value = &values[0];663						values = &values[1..];664						usize::from_untyped(value.clone())?665					}666					Width::Fixed(n) => n,667				};668				let precision = match c.precision {669					Some(Width::Star) => {670						if values.is_empty() {671							bail!(NotEnoughValues);672						}673						let value = &values[0];674						values = &values[1..];675						Some(usize::from_untyped(value.clone())?)676					}677					Some(Width::Fixed(n)) => Some(n),678					None => None,679				};680681				// %% should not consume a value682				let value = if c.convtype == ConvTypeV::Percent {683					&Val::Null684				} else {685					if values.is_empty() {686						bail!(NotEnoughValues);687					}688					let value = &values[0];689					values = &values[1..];690					value691				};692693				format_code(&mut out, value, &c, width, precision)?;694			}695		}696	}697698	if !values.is_empty() {699		bail!(700			"too many values to format, expected {value_count}, got {}",701			value_count + values.len()702		)703	}704705	Ok(out)706}707708fn get_dotted_field(obj: ObjValue, field: &str) -> Result<Val> {709	let mut current = Val::Obj(obj);710	let mut name_offset = 0;711	for component in field.split('.') {712		let end_offset = name_offset + component.len();713		current = if let Val::Obj(obj) = current {714			if let Some(value) = obj.get(component.into())? {715				value716			} else {717				let current = &field[name_offset..end_offset];718				let full = &field[..name_offset];719				let found = Box::new(suggest_object_fields(&obj, current.into()));720				bail!(SubfieldNotFound {721					current: current.into(),722					full: full.into(),723					found,724				})725			}726		} else {727			// No underflow may happen, initially we always start with an object728			let subfield = &field[..name_offset - 1];729			bail!(SubfieldDidntYieldAnObject(730				subfield.into(),731				current.value_type()732			));733		};734		name_offset = end_offset + 1;735	}736	Ok(current)737}738739pub fn format_obj(str: &str, values: &ObjValue) -> Result<String> {740	let codes = parse_codes(str)?;741	let mut out = String::new();742743	for code in codes {744		match code {745			Element::String(s) => {746				out.push_str(s);747			}748			Element::Code(c) => {749				// TODO: Operate on ref750				let f: IStr = c.mkey.into();751				let width = match c.width {752					Width::Star => {753						bail!(CannotUseStarWidthWithObject);754					}755					Width::Fixed(n) => n,756				};757				let precision = match c.precision {758					Some(Width::Star) => {759						bail!(CannotUseStarWidthWithObject);760					}761					Some(Width::Fixed(n)) => Some(n),762					None => None,763				};764765				let value = if c.convtype == ConvTypeV::Percent {766					Val::Null767				} else {768					if f.is_empty() {769						bail!(MappingKeysRequired);770					}771					if let Some(v) = values.get(f.clone())? {772						v773					} else {774						get_dotted_field(values.clone(), &f)?775					}776				};777778				format_code(&mut out, &value, &c, width, precision)?;779			}780		}781	}782783	Ok(out)784}785786#[cfg(test)]787pub mod test_format {788	use super::*;789790	#[test]791	fn parse() {792		assert_eq!(793			parse_codes(794				"How much error budget is left looking at our %.3f%% availability gurantees?"795			)796			.unwrap()797			.len(),798			4799		);800	}801802	#[test]803	fn octals() {804		assert_eq!(format_arr("%#o", &[Val::Num(8.0)]).unwrap(), "010");805		assert_eq!(format_arr("%#4o", &[Val::Num(8.0)]).unwrap(), " 010");806		assert_eq!(format_arr("%4o", &[Val::Num(8.0)]).unwrap(), "  10");807		assert_eq!(format_arr("%04o", &[Val::Num(8.0)]).unwrap(), "0010");808		assert_eq!(format_arr("%+4o", &[Val::Num(8.0)]).unwrap(), " +10");809		assert_eq!(format_arr("%+04o", &[Val::Num(8.0)]).unwrap(), "+010");810		assert_eq!(format_arr("%-4o", &[Val::Num(8.0)]).unwrap(), "10  ");811		assert_eq!(format_arr("%+-4o", &[Val::Num(8.0)]).unwrap(), "+10 ");812		assert_eq!(format_arr("%+-04o", &[Val::Num(8.0)]).unwrap(), "+10 ");813	}814815	#[test]816	fn percent_doesnt_consumes_values() {817		assert_eq!(818			format_arr(819				"How much error budget is left looking at our %.3f%% availability gurantees?",820				&[Val::Num(4.0)]821			)822			.unwrap(),823			"How much error budget is left looking at our 4.000% availability gurantees?"824		);825	}826}
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -449,25 +449,21 @@
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
-		match &value {
-			Val::Arr(a) => {
-				if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
-					return Ok(bytes.0.as_slice().into());
-				};
-				<Self as Typed>::TYPE.check(&value)?;
-				// Any::downcast_ref::<ByteArray>(&a);
-				let mut out = Vec::with_capacity(a.len());
-				for e in a.iter() {
-					let r = e?;
-					out.push(u8::from_untyped(r)?);
-				}
-				Ok(out.as_slice().into())
-			}
-			_ => {
-				<Self as Typed>::TYPE.check(&value)?;
-				unreachable!()
-			}
+		let Val::Arr(a) = &value else {
+			<Self as Typed>::TYPE.check(&value)?;
+			unreachable!()
+		};
+		if let Some(bytes) = a.as_any().downcast_ref::<BytesArray>() {
+			return Ok(bytes.0.as_slice().into());
+		};
+		<Self as Typed>::TYPE.check(&value)?;
+		// Any::downcast_ref::<ByteArray>(&a);
+		let mut out = Vec::with_capacity(a.len());
+		for e in a.iter() {
+			let r = e?;
+			out.push(u8::from_untyped(r)?);
 		}
+		Ok(out.as_slice().into())
 	}
 }
 
modifiedcrates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -90,7 +90,7 @@
 	item: impl Fn() -> Result<()>,
 ) -> Result<()> {
 	State::push_description(error_reason, || match item() {
-		Ok(_) => Ok(()),
+		Ok(()) => Ok(()),
 		Err(mut e) => {
 			if let ErrorKind::TypeError(e) = &mut e.error_mut() {
 				(e.1).0.push(path());
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -351,6 +351,8 @@
 	}
 }
 impl PartialEq for StrValue {
+	// False positive, into_flat returns not StrValue, but IStr, thus no infinite recursion here.
+	#[allow(clippy::unconditional_recursion)]
 	fn eq(&self, other: &Self) -> bool {
 		let a = self.clone().into_flat();
 		let b = other.clone().into_flat();
modifiedcrates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -6,7 +6,7 @@
 #![warn(clippy::pedantic, clippy::nursery)]
 #![allow(clippy::missing_const_for_fn)]
 use std::{
-	borrow::{Borrow, Cow},
+	borrow::Cow,
 	cell::RefCell,
 	fmt::{self, Display},
 	hash::{BuildHasherDefault, Hash, Hasher},
@@ -14,7 +14,7 @@
 	str,
 };
 
-use hashbrown::HashMap;
+use hashbrown::{hash_map::RawEntryMut, HashMap};
 use jrsonnet_gcmodule::Trace;
 use rustc_hash::FxHasher;
 
@@ -57,17 +57,6 @@
 	}
 }
 
-impl Borrow<str> for IStr {
-	fn borrow(&self) -> &str {
-		self.as_str()
-	}
-}
-impl Borrow<[u8]> for IStr {
-	fn borrow(&self) -> &[u8] {
-		self.as_bytes()
-	}
-}
-
 impl PartialEq for IStr {
 	fn eq(&self, other: &Self) -> bool {
 		// all IStr should be inlined into same pool
@@ -142,12 +131,6 @@
 	type Target = [u8];
 
 	fn deref(&self) -> &Self::Target {
-		self.0.as_slice()
-	}
-}
-
-impl Borrow<[u8]> for IBytes {
-	fn borrow(&self) -> &[u8] {
 		self.0.as_slice()
 	}
 }
@@ -285,9 +268,9 @@
 		let mut pool = pool.borrow_mut();
 		let entry = pool.raw_entry_mut().from_key(bytes);
 		match entry {
-			hashbrown::hash_map::RawEntryMut::Occupied(i) => IBytes(i.get_key_value().0.clone()),
-			hashbrown::hash_map::RawEntryMut::Vacant(e) => {
-				let (k, _) = e.insert(Inner::new_bytes(bytes), ());
+			RawEntryMut::Occupied(i) => IBytes(i.get_key_value().0.clone()),
+			RawEntryMut::Vacant(e) => {
+				let (k, ()) = e.insert(Inner::new_bytes(bytes), ());
 				IBytes(k.clone())
 			}
 		}
modifiedcrates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -374,6 +374,7 @@
 				fn params(&self) -> &[BuiltinParam] {
 					PARAMS
 				}
+				#[allow(unused_variable)]
 				fn call(&self, ctx: Context, location: CallLocation, args: &dyn ArgsLike) -> Result<Val> {
 					let parsed = parse_builtin_call(ctx.clone(), &PARAMS, args, false)?;
 
modifiedcrates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -39,5 +39,5 @@
 	let bytes = STANDARD
 		.decode(str.as_bytes())
 		.map_err(|e| runtime_error!("invalid base64: {e}"))?;
-	Ok(String::from_utf8(bytes).map_err(|_| runtime_error!("bad utf8"))?)
+	String::from_utf8(bytes).map_err(|_| runtime_error!("bad utf8"))
 }
modifiedcrates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/yaml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/yaml.rs
@@ -134,6 +134,14 @@
 					buf.push_str(&options.padding);
 					buf.push_str(line);
 				}
+			} else if s.contains('\n') {
+				buf.push_str("|-");
+				for line in s.split('\n') {
+					buf.push('\n');
+					buf.push_str(cur_padding);
+					buf.push_str(&options.padding);
+					buf.push_str(line);
+				}
 			} else if !options.quote_keys && !yaml_needs_quotes(&s) {
 				buf.push_str(&s);
 			} else {
modifiedcrates/jrsonnet-stdlib/src/misc.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/misc.rs
+++ b/crates/jrsonnet-stdlib/src/misc.rs
@@ -47,7 +47,7 @@
 		.ext_natives
 		.get(&x)
 		.cloned()
-		.map_or(Val::Null, |v| Val::Func(v))
+		.map_or(Val::Null, Val::Func)
 }
 
 #[builtin(fields(
modifiedflake.lockdiffbeforeafterboth
--- a/flake.lock
+++ b/flake.lock
@@ -5,11 +5,11 @@
         "systems": "systems"
       },
       "locked": {
-        "lastModified": 1694529238,
-        "narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=",
+        "lastModified": 1705309234,
+        "narHash": "sha256-uNRRNRKmJyCRC/8y1RqBkqWBLM034y4qN7EprSdmgyA=",
         "owner": "numtide",
         "repo": "flake-utils",
-        "rev": "ff7b65b44d01cf9ba6a71320833626af21126384",
+        "rev": "1ef2e671c3b0c19053962c07dbda38332dcebf26",
         "type": "github"
       },
       "original": {
@@ -20,11 +20,11 @@
     },
     "nixpkgs": {
       "locked": {
-        "lastModified": 1701376520,
-        "narHash": "sha256-U3iGiOZqgu7wvVzgfoQzGGFMqNsDj/q/6zPIjCy7ajg=",
+        "lastModified": 1705391267,
+        "narHash": "sha256-gGVm9QudiRtYTX8PN9cTTy7uuJcL4I2lRMoPx496kXk=",
         "owner": "nixos",
         "repo": "nixpkgs",
-        "rev": "c74cc3c3db2ed5e68895953d75c397797d499133",
+        "rev": "41a9a7f170c740acb24f3390323877d11c69d5ee",
         "type": "github"
       },
       "original": {
@@ -50,11 +50,11 @@
         ]
       },
       "locked": {
-        "lastModified": 1701310566,
-        "narHash": "sha256-CL9J3xUR2Ejni4LysrEGX0IdO+Y4BXCiH/By0lmF3eQ=",
+        "lastModified": 1705371439,
+        "narHash": "sha256-P1kulUXpYWkcrjiX3sV4j8ACJZh9XXSaaD+jDLBDLKo=",
         "owner": "oxalica",
         "repo": "rust-overlay",
-        "rev": "6d3c6e185198b8bf7ad639f22404a75aa9a09bff",
+        "rev": "b21f3c0d5bf0f0179f5f0140e8e0cd099618bd04",
         "type": "github"
       },
       "original": {
modifiedflake.nixdiffbeforeafterboth
--- a/flake.nix
+++ b/flake.nix
@@ -25,14 +25,14 @@
         lib = pkgs.lib;
         rust =
           (pkgs.rustChannelOf {
-            date = "2023-10-28";
+            date = "2024-01-10";
             channel = "nightly";
           })
           .default
           .override {
             extensions = ["rust-src" "miri" "rust-analyzer" "clippy"];
           };
-      in rec {
+      in {
         packages = rec {
           go-jsonnet = pkgs.callPackage ./nix/go-jsonnet.nix {};
           sjsonnet = pkgs.callPackage ./nix/sjsonnet.nix {};
modifiedtests/suite/std_param_names.jsonnetdiffbeforeafterboth
--- a/tests/suite/std_param_names.jsonnet
+++ b/tests/suite/std_param_names.jsonnet
@@ -103,6 +103,7 @@
     asin: ['x'],
     acos: ['x'],
     atan: ['x'],
+    atan2: ['y', 'x'],
     type: ['x'],
     filter: ['func', 'arr'],
     objectHasEx: ['obj', 'fname', 'hidden'],