git.delta.rocks / jrsonnet / refs/commits / 70f37833046b

difftreelog

style fix clippy warnings

Yaroslav Bolyukin2022-10-11parent: #afca252.patch.diff
in: master

20 files changed

modifiedbindings/jsonnet/src/lib.rsdiffbeforeafterboth
--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -70,6 +70,7 @@
 
 /// Creates a new Jsonnet virtual machine.
 #[no_mangle]
+#[allow(clippy::box_default)]
 pub extern "C" fn jsonnet_make() -> *mut State {
 	let state = State::default();
 	state.settings_mut().import_resolver = Box::new(FileImportResolver::default());
modifiedcrates/jrsonnet-cli/src/stdlib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-cli/src/stdlib.rs
+++ b/crates/jrsonnet-cli/src/stdlib.rs
@@ -44,7 +44,7 @@
 		if out.len() != 2 {
 			return Err("bad ext-file syntax".to_owned());
 		}
-		let file = read_to_string(&out[1]);
+		let file = read_to_string(out[1]);
 		match file {
 			Ok(content) => Ok(Self {
 				name: out[0].into(),
modifiedcrates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -100,7 +100,7 @@
 	#[error("duplicate local var: {0}")]
 	DuplicateLocalVar(IStr),
 
-	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{}", e)).collect::<Vec<_>>().join(", "))]
+	#[error("type mismatch: expected {}, got {2} {0}", .1.iter().map(|e| format!("{e}")).collect::<Vec<_>>().join(", "))]
 	TypeMismatch(&'static str, Vec<ValType>, ValType),
 	#[error("no such field: {}{}", format_empty_str(.0), format_found(.1, "field"))]
 	NoSuchField(IStr, Vec<IStr>),
@@ -113,7 +113,7 @@
 	BindingParameterASecondTime(IStr),
 	#[error("too many args, function has {0}{}", format_signature(.1))]
 	TooManyArgsFunctionHas(usize, FunctionSignature),
-	#[error("function argument is not passed: {}{}", .0.as_ref().map(|n| n.as_str()).unwrap_or("<unnamed>"), format_signature(.1))]
+	#[error("function argument is not passed: {}{}", .0.as_ref().map_or("<unnamed>", IStr::as_str), format_signature(.1))]
 	FunctionParameterNotBoundInCall(Option<IStr>, FunctionSignature),
 
 	#[error("external variable is not defined: {0}")]
@@ -249,7 +249,7 @@
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		writeln!(f, "{}", self.0 .0)?;
 		for el in &self.0 .1 .0 {
-			writeln!(f, "\t{:?}", el)?;
+			writeln!(f, "\t{el:?}")?;
 		}
 		Ok(())
 	}
modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -436,7 +436,7 @@
 		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(s, ctx, v)?)?,
 		Var(name) => s.push(
 			CallLocation::new(loc),
-			|| format!("variable <{}> access", name),
+			|| format!("variable <{name}> access"),
 			|| ctx.binding(name.clone())?.evaluate(s.clone()),
 		)?,
 		Index(value, index) => {
@@ -446,7 +446,7 @@
 			) {
 				(Val::Obj(v), Val::Str(key)) => s.push(
 					CallLocation::new(loc),
-					|| format!("field <{}> access", key),
+					|| format!("field <{key}> access"),
 					|| match v.get(s.clone(), key.clone()) {
 						Ok(Some(v)) => Ok(v),
 						#[cfg(not(feature = "friendly-errors"))]
@@ -611,7 +611,7 @@
 				if let Some(value) = expr {
 					Ok(Some(s.push(
 						loc,
-						|| format!("slice {}", desc),
+						|| format!("slice {desc}"),
 						|| T::from_untyped(evaluate(s.clone(), ctx.clone(), value)?, s.clone()),
 					)?))
 				} else {
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -30,8 +30,8 @@
 		(Str(a), Num(b)) => Str(format!("{a}{b}").into()),
 
 		(Str(a), o) | (o, Str(a)) if a.is_empty() => Val::Str(o.clone().to_string(s)?),
-		(Str(a), o) => Str(format!("{}{}", a, o.clone().to_string(s)?).into()),
-		(o, Str(a)) => Str(format!("{}{}", o.clone().to_string(s)?, a).into()),
+		(Str(a), o) => Str(format!("{a}{}", o.clone().to_string(s)?).into()),
+		(o, Str(a)) => Str(format!("{}{a}", o.clone().to_string(s)?).into()),
 
 		(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
 		(Arr(a), Arr(b)) => {
modifiedcrates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -108,7 +108,7 @@
 		handler: &mut dyn FnMut(usize, Thunk<Val>) -> Result<()>,
 	) -> Result<()> {
 		for (idx, el) in self.iter().enumerate() {
-			handler(idx, Thunk::evaluated(el.clone()))?
+			handler(idx, Thunk::evaluated(el.clone()))?;
 		}
 		Ok(())
 	}
modifiedcrates/jrsonnet-evaluator/src/function/parse.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/parse.rs
+++ b/crates/jrsonnet-evaluator/src/function/parse.rs
@@ -179,12 +179,7 @@
 		// FIXME: O(n) for arg existence check
 		let id = params
 			.iter()
-			.position(|p| {
-				p.name
-					.as_ref()
-					.map(|v| &v as &str == name as &str)
-					.unwrap_or(false)
-			})
+			.position(|p| p.name.as_ref().map_or(false, |v| v as &str == name as &str))
 			.ok_or_else(|| UnknownFunctionParameter((name as &str).to_owned()))?;
 		if replace(&mut passed_args[id], Some(arg)).is_some() {
 			throw!(BindingParameterASecondTime(name.clone()));
@@ -209,8 +204,7 @@
 					if param
 						.name
 						.as_ref()
-						.map(|v| &v as &str == name as &str)
-						.unwrap_or(false)
+						.map_or(false, |v| v as &str == name as &str)
 					{
 						found = true;
 					}
modifiedcrates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -123,15 +123,11 @@
 		};
 		if meta.is_file() {
 			Ok(SourcePath::new(SourceFile::new(
-				path.canonicalize()
-					.map_err(|e| ImportIo(e.to_string()))?
-					.to_owned(),
+				path.canonicalize().map_err(|e| ImportIo(e.to_string()))?,
 			)))
 		} else if meta.is_dir() {
 			Ok(SourcePath::new(SourceDirectory::new(
-				path.canonicalize()
-					.map_err(|e| ImportIo(e.to_string()))?
-					.to_owned(),
+				path.canonicalize().map_err(|e| ImportIo(e.to_string()))?,
 			)))
 		} else {
 			unreachable!("this can't be a symlink")
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -16,7 +16,7 @@
 			Self::Null => Val::Null,
 			Self::Bool(v) => Val::Bool(v),
 			Self::Number(n) => Val::Num(n.as_f64().ok_or_else(|| {
-				RuntimeError(format!("json number can't be represented as jsonnet: {}", n).into())
+				RuntimeError(format!("json number can't be represented as jsonnet: {n}").into())
 			})?),
 			Self::String(s) => Val::Str((&s as &str).into()),
 			Self::Array(a) => {
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -594,7 +594,7 @@
 			.insert(name, TlaArg::String(value));
 	}
 	pub fn add_tla_code(&self, name: IStr, code: &str) -> Result<()> {
-		let source_name = format!("<top-level-arg:{}>", name);
+		let source_name = format!("<top-level-arg:{name}>");
 		let source = Source::new_virtual(source_name.into(), code.into());
 		let parsed = jrsonnet_parser::parse(
 			code,
modifiedcrates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -156,9 +156,9 @@
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		if let Some(super_obj) = self.0.sup.as_ref() {
 			if f.alternate() {
-				write!(f, "{:#?}", super_obj)?;
+				write!(f, "{super_obj:#?}")?;
 			} else {
-				write!(f, "{:?}", super_obj)?;
+				write!(f, "{super_obj:?}")?;
 			}
 			write!(f, " + ")?;
 		}
@@ -395,10 +395,9 @@
 			})?;
 		self.0.value_cache.borrow_mut().insert(
 			key,
-			match &value {
-				Some(v) => CacheValue::Cached(v.clone()),
-				None => CacheValue::NotFound,
-			},
+			value
+				.as_ref()
+				.map_or(CacheValue::NotFound, |v| CacheValue::Cached(v.clone())),
 		);
 		Ok(value)
 	}
modifiedcrates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -45,7 +45,7 @@
 		let mut i = 1;
 		while i < bytes.len() {
 			if bytes[i] == b')' {
-				return Ok((&str[1..i as usize], &str[i as usize + 1..]));
+				return Ok((&str[1..i], &str[i + 1..]));
 			}
 			i += 1;
 		}
@@ -310,6 +310,7 @@
 		nums
 	};
 	let neg = iv < 0.0;
+	#[allow(clippy::bool_to_int_with_if)]
 	let zp = padding.saturating_sub(if neg || blank || sign { 1 } else { 0 });
 	let zp2 = zp
 		.max(precision)
@@ -406,6 +407,7 @@
 	ensure_pt: bool,
 	trailing: bool,
 ) {
+	#[allow(clippy::bool_to_int_with_if)]
 	let dot_size = if precision == 0 && !ensure_pt { 0 } else { 1 };
 	padding = padding.saturating_sub(dot_size + precision);
 	render_decimal(out, n.floor(), padding, 0, blank, sign);
@@ -478,10 +480,7 @@
 	precision: Option<usize>,
 ) -> Result<()> {
 	let clfags = &code.cflags;
-	let (fpprec, iprec) = match precision {
-		Some(v) => (v, v),
-		None => (6, 0),
-	};
+	let (fpprec, iprec) = precision.map_or((6, 0), |v| (v, v));
 	let padding = if clfags.zero && !clfags.left {
 		width
 	} else {
@@ -586,8 +585,10 @@
 			}
 		}
 		ConvTypeV::Char => match value.clone() {
-			Val::Num(n) => tmp_out
-				.push(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?),
+			Val::Num(n) => tmp_out.push(
+				std::char::from_u32(n as u32)
+					.ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
+			),
 			Val::Str(s) => {
 				if s.chars().count() != 1 {
 					throw!(RuntimeError(
modifiedcrates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
@@ -49,7 +49,7 @@
 		}
 		Val::Null => buf.push_str("null"),
 		Val::Str(s) => escape_string_json_buf(s, buf),
-		Val::Num(n) => write!(buf, "{}", n).unwrap(),
+		Val::Num(n) => write!(buf, "{n}").unwrap(),
 		Val::Arr(items) => {
 			buf.push('[');
 			if !items.is_empty() {
modifiedcrates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -12,7 +12,7 @@
 pub fn std_format(s: State, str: IStr, vals: Val) -> Result<String> {
 	s.push(
 		CallLocation::native(),
-		|| format!("std.format of {}", str),
+		|| format!("std.format of {str}"),
 		|| {
 			Ok(match vals {
 				Val::Arr(vals) => format_arr(s.clone(), &str, &vals.evaluated(s.clone())?)?,
modifiedcrates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -16,12 +16,9 @@
 }
 
 impl PathResolver {
-	/// Will return Self::Relative(cwd), or Self::Absolute on cwd failure
+	/// Will return `Self::Relative(cwd)`, or `Self::Absolute` on cwd failure
 	pub fn new_cwd_fallback() -> Self {
-		match std::env::current_dir() {
-			Ok(v) => Self::Relative(v),
-			Err(_) => Self::Absolute,
-		}
+		std::env::current_dir().map_or(Self::Absolute, Self::Relative)
 	}
 	pub fn resolve(&self, from: &Path) -> String {
 		match self {
@@ -97,10 +94,10 @@
 			use std::fmt::Write;
 
 			writeln!(out)?;
-			let mut n = match path.source_path().path() {
-				Some(r) => self.resolver.resolve(r),
-				None => path.source_path().to_string(),
-			};
+			let mut n = path.source_path().path().map_or_else(
+				|| path.source_path().to_string(),
+				|r| self.resolver.resolve(r),
+			);
 			let mut offset = error.location.offset;
 			let is_eof = if offset >= path.code().len() {
 				offset = path.code().len().saturating_sub(1);
@@ -119,7 +116,7 @@
 
 			write!(n, ":").unwrap();
 			print_code_location(&mut n, &location, &location).unwrap();
-			write!(out, "{:<p$}{}", "", n, p = self.padding,)?;
+			write!(out, "{:<p$}{n}", "", p = self.padding)?;
 		}
 		let file_names = error
 			.trace()
@@ -185,10 +182,10 @@
 			let desc = &item.desc;
 			if let Some(source) = &item.location {
 				let start_end = source.0.map_source_locations(&[source.1, source.2]);
-				let resolved_path = match source.0.source_path().path() {
-					Some(r) => r.display().to_string(),
-					None => source.0.source_path().to_string(),
-				};
+				let resolved_path = source.0.source_path().path().map_or_else(
+					|| source.0.source_path().to_string(),
+					|r| r.display().to_string(),
+				);
 
 				write!(
 					out,
@@ -196,7 +193,7 @@
 					desc, resolved_path, start_end[0].line, start_end[0].column,
 				)?;
 			} else {
-				write!(out, "    during {}", desc)?;
+				write!(out, "    during {desc}")?;
 			}
 		}
 		Ok(())
@@ -252,7 +249,7 @@
 					desc,
 				)?;
 			} else {
-				write!(out, "{}", desc)?;
+				write!(out, "{desc}")?;
 			}
 		}
 		Ok(())
@@ -280,10 +277,10 @@
 			.take(end.line_end_offset - end.line_start_offset)
 			.collect();
 
-		let origin = match origin.source_path().path() {
-			Some(r) => self.resolver.resolve(r),
-			None => origin.source_path().to_string(),
-		};
+		let origin = origin.source_path().path().map_or_else(
+			|| origin.source_path().to_string(),
+			|r| self.resolver.resolve(r),
+		);
 		let snippet = Snippet {
 			opt: FormatOptions {
 				color: true,
@@ -308,7 +305,7 @@
 		};
 
 		let dl = DisplayList::from(snippet);
-		write!(out, "{}", dl)?;
+		write!(out, "{dl}")?;
 
 		Ok(())
 	}
modifiedcrates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -21,8 +21,8 @@
 	UnionFailed(ComplexValType, TypeLocErrorList),
 	#[error(
 		"number out of bounds: {0} not in {}..{}",
-		.1.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
-		.2.map(|v|v.to_string()).unwrap_or_else(|| "".to_owned()),
+		.1.map(|v|v.to_string()).unwrap_or_default(),
+		.2.map(|v|v.to_string()).unwrap_or_default(),
 	)]
 	BoundsFailed(f64, Option<f64>, Option<f64>),
 }
@@ -65,7 +65,7 @@
 				writeln!(f)?;
 			}
 			out.clear();
-			write!(out, "{}", err)?;
+			write!(out, "{err}")?;
 
 			for (i, line) in out.lines().enumerate() {
 				if line.trim().is_empty() {
@@ -77,7 +77,7 @@
 					writeln!(f)?;
 					write!(f, "    ")?;
 				}
-				write!(f, "{}", line)?;
+				write!(f, "{line}")?;
 			}
 		}
 		Ok(())
@@ -125,8 +125,8 @@
 impl Display for ValuePathItem {
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		match self {
-			Self::Field(name) => write!(f, ".{:?}", name)?,
-			Self::Index(idx) => write!(f, "[{}]", idx)?,
+			Self::Field(name) => write!(f, ".{name:?}")?,
+			Self::Index(idx) => write!(f, "[{idx}]")?,
 		}
 		Ok(())
 	}
@@ -138,7 +138,7 @@
 	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 		write!(f, "self")?;
 		for elem in self.0.iter().rev() {
-			write!(f, "{}", elem)?;
+			write!(f, "{elem}")?;
 		}
 		Ok(())
 	}
@@ -171,7 +171,7 @@
 					for (i, item) in a.iter(s.clone()).enumerate() {
 						push_type_description(
 							s.clone(),
-							|| format!("array index {}", i),
+							|| format!("array index {i}"),
 							|| ValuePathItem::Index(i as u64),
 							|| elem_type.check(s.clone(), &item.clone()?),
 						)?;
@@ -185,7 +185,7 @@
 					for (i, item) in a.iter(s.clone()).enumerate() {
 						push_type_description(
 							s.clone(),
-							|| format!("array index {}", i),
+							|| format!("array index {i}"),
 							|| ValuePathItem::Index(i as u64),
 							|| elem_type.check(s.clone(), &item.clone()?),
 						)?;
@@ -200,7 +200,7 @@
 						if let Some(got_v) = obj.get(s.clone(), (*k).into())? {
 							push_type_description(
 								s.clone(),
-								|| format!("property {}", k),
+								|| format!("property {k}"),
 								|| ValuePathItem::Field((*k).into()),
 								|| v.check(s.clone(), &got_v),
 							)?;
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -292,7 +292,7 @@
 				if index >= v.to() {
 					return Ok(None);
 				}
-				v.inner.get(s, index as usize)
+				v.inner.get(s, index)
 			}
 		}
 	}
@@ -332,7 +332,7 @@
 				if index >= s.to() {
 					return None;
 				}
-				s.inner.get_lazy(index as usize)
+				s.inner.get_lazy(index)
 			}
 		}
 	}
@@ -531,8 +531,9 @@
 	}
 }
 
-#[cfg(target_pointer_width = "64")]
-static_assertions::assert_eq_size!(Val, [u8; 32]);
+// Broken between stable and nightly, as there is new layout size optimization
+// #[cfg(target_pointer_width = "64")]
+// static_assertions::assert_eq_size!(Val, [u8; 24]);
 
 impl Val {
 	pub const fn as_bool(&self) -> Option<bool> {
modifiedcrates/jrsonnet-stdlib/src/encoding.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/encoding.rs
+++ b/crates/jrsonnet-stdlib/src/encoding.rs
@@ -28,7 +28,7 @@
 
 #[builtin]
 pub fn builtin_base64_decode_bytes(input: IStr) -> Result<IBytes> {
-	Ok(base64::decode(&input.as_bytes())
+	Ok(base64::decode(input.as_bytes())
 		.map_err(|_| RuntimeError("bad base64".into()))?
 		.as_slice()
 		.into())
@@ -36,6 +36,6 @@
 
 #[builtin]
 pub fn builtin_base64_decode(input: IStr) -> Result<String> {
-	let bytes = base64::decode(&input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
+	let bytes = base64::decode(input.as_bytes()).map_err(|_| RuntimeError("bad base64".into()))?;
 	Ok(String::from_utf8(bytes).map_err(|_| RuntimeError("bad utf8".into()))?)
 }
modifiedcrates/jrsonnet-stdlib/src/hash.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/hash.rs
+++ b/crates/jrsonnet-stdlib/src/hash.rs
@@ -2,5 +2,5 @@
 
 #[builtin]
 pub fn builtin_md5(str: IStr) -> Result<String> {
-	Ok(format!("{:x}", md5::compute(&str.as_bytes())))
+	Ok(format!("{:x}", md5::compute(str.as_bytes())))
 }
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/lib.rs
1use std::{2	cell::{Ref, RefCell, RefMut},3	collections::HashMap,4	rc::Rc,5};67use jrsonnet_evaluator::{8	error::{Error::*, Result},9	function::{builtin::Builtin, ArgLike, CallLocation, FuncVal, TlaArg},10	gc::{GcHashMap, TraceBox},11	tb, throw_runtime,12	trace::PathResolver,13	typed::{Any, Either, Either2, Either4, VecVal, M1},14	val::{equals, ArrValue},15	Context, ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,16};17use jrsonnet_gcmodule::Cc;18use jrsonnet_macros::builtin;19use jrsonnet_parser::Source;2021mod expr;22mod types;23pub use types::*;24mod arrays;25pub use arrays::*;26mod math;27pub use math::*;28mod operator;29pub use operator::*;30mod sort;31pub use sort::*;32mod hash;33pub use hash::*;34mod encoding;35pub use encoding::*;36mod objects;37pub use objects::*;38mod manifest;39pub use manifest::*;40mod parse;41pub use parse::*;4243pub fn stdlib_uncached(s: State, settings: Rc<RefCell<Settings>>) -> ObjValue {44	let mut builder = ObjValueBuilder::new();4546	let expr = expr::stdlib_expr();47	let eval = jrsonnet_evaluator::evaluate(s.clone(), Context::default(), &expr)48		.expect("stdlib.jsonnet should have no errors")49		.as_obj()50		.expect("stdlib.jsonnet should evaluate to object");5152	builder.with_super(eval);5354	for (name, builtin) in [55		("length".into(), builtin_length::INST),56		// Types57		("type".into(), builtin_type::INST),58		("isString".into(), builtin_is_string::INST),59		("isNumber".into(), builtin_is_number::INST),60		("isBoolean".into(), builtin_is_boolean::INST),61		("isObject".into(), builtin_is_object::INST),62		("isArray".into(), builtin_is_array::INST),63		("isFunction".into(), builtin_is_function::INST),64		// Arrays65		("makeArray".into(), builtin_make_array::INST),66		("slice".into(), builtin_slice::INST),67		("map".into(), builtin_map::INST),68		("flatMap".into(), builtin_flatmap::INST),69		("filter".into(), builtin_filter::INST),70		("foldl".into(), builtin_foldl::INST),71		("foldr".into(), builtin_foldr::INST),72		("range".into(), builtin_range::INST),73		("join".into(), builtin_join::INST),74		("reverse".into(), builtin_reverse::INST),75		("any".into(), builtin_any::INST),76		("all".into(), builtin_all::INST),77		("member".into(), builtin_member::INST),78		("count".into(), builtin_count::INST),79		// Math80		("modulo".into(), builtin_modulo::INST),81		("floor".into(), builtin_floor::INST),82		("ceil".into(), builtin_ceil::INST),83		("log".into(), builtin_log::INST),84		("pow".into(), builtin_pow::INST),85		("sqrt".into(), builtin_sqrt::INST),86		("sin".into(), builtin_sin::INST),87		("cos".into(), builtin_cos::INST),88		("tan".into(), builtin_tan::INST),89		("asin".into(), builtin_asin::INST),90		("acos".into(), builtin_acos::INST),91		("atan".into(), builtin_atan::INST),92		("exp".into(), builtin_exp::INST),93		("mantissa".into(), builtin_mantissa::INST),94		("exponent".into(), builtin_exponent::INST),95		// Operator96		("mod".into(), builtin_mod::INST),97		("primitiveEquals".into(), builtin_primitive_equals::INST),98		("equals".into(), builtin_equals::INST),99		("format".into(), builtin_format::INST),100		// Sort101		("sort".into(), builtin_sort::INST),102		// Hash103		("md5".into(), builtin_md5::INST),104		// Encoding105		("encodeUTF8".into(), builtin_encode_utf8::INST),106		("decodeUTF8".into(), builtin_decode_utf8::INST),107		("base64".into(), builtin_base64::INST),108		("base64Decode".into(), builtin_base64_decode::INST),109		(110			"base64DecodeBytes".into(),111			builtin_base64_decode_bytes::INST,112		),113		// Objects114		("objectFieldsEx".into(), builtin_object_fields_ex::INST),115		("objectHasEx".into(), builtin_object_has_ex::INST),116		// Manifest117		("escapeStringJson".into(), builtin_escape_string_json::INST),118		("manifestJsonEx".into(), builtin_manifest_json_ex::INST),119		("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),120		// Parsing121		("parseJson".into(), builtin_parse_json::INST),122		("parseYaml".into(), builtin_parse_yaml::INST),123		// Misc124		("codepoint".into(), builtin_codepoint::INST),125		("substr".into(), builtin_substr::INST),126		("char".into(), builtin_char::INST),127		("strReplace".into(), builtin_str_replace::INST),128		("splitLimit".into(), builtin_splitlimit::INST),129		("asciiUpper".into(), builtin_ascii_upper::INST),130		("asciiLower".into(), builtin_ascii_lower::INST),131		("findSubstr".into(), builtin_find_substr::INST),132		("startsWith".into(), builtin_starts_with::INST),133		("endsWith".into(), builtin_ends_with::INST),134	]135	.iter()136	.cloned()137	{138		builder139			.member(name)140			.hide()141			.value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))142			.expect("no conflict");143	}144145	builder146		.member("extVar".into())147		.hide()148		.value(149			s.clone(),150			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {151				settings: settings.clone()152			})))),153		)154		.expect("no conflict");155	builder156		.member("native".into())157		.hide()158		.value(159			s.clone(),160			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {161				settings: settings.clone()162			})))),163		)164		.expect("no conflict");165	builder166		.member("trace".into())167		.hide()168		.value(169			s.clone(),170			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace { settings })))),171		)172		.expect("no conflict");173174	builder175		.member("id".into())176		.hide()177		.value(s, Val::Func(FuncVal::Id))178		.expect("no conflict");179180	builder.build()181}182183pub trait TracePrinter {184	fn print_trace(&self, s: State, loc: CallLocation, value: IStr);185}186187pub struct StdTracePrinter {188	resolver: PathResolver,189}190impl StdTracePrinter {191	pub fn new(resolver: PathResolver) -> Self {192		Self { resolver }193	}194}195impl TracePrinter for StdTracePrinter {196	fn print_trace(&self, _s: State, loc: CallLocation, value: IStr) {197		eprint!("TRACE:");198		if let Some(loc) = loc.0 {199			let locs = loc.0.map_source_locations(&[loc.1]);200			eprint!(201				" {}:{}",202				match loc.0.source_path().path() {203					Some(p) => self.resolver.resolve(p),204					None => loc.0.source_path().to_string(),205				},206				locs[0].line207			);208		}209		eprintln!(" {}", value);210	}211}212213pub struct Settings {214	/// Used for `std.extVar`215	pub ext_vars: HashMap<IStr, TlaArg>,216	/// Used for `std.native`217	pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,218	/// Helper to add globals without implementing custom ContextInitializer219	pub globals: GcHashMap<IStr, Thunk<Val>>,220	/// Used for `std.trace`221	pub trace_printer: Box<dyn TracePrinter>,222	/// Used for `std.thisFile`223	pub path_resolver: PathResolver,224}225226pub fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {227	let source_name = format!("<extvar:{}>", name);228	Source::new_virtual(source_name.into(), code.into())229}230231pub struct ContextInitializer {232	// When we don't need to support legacy-this-file, we can reuse same context for all files233	#[cfg(not(feature = "legacy-this-file"))]234	context: Context,235	// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it236	#[cfg(feature = "legacy-this-file")]237	stdlib_obj: ObjValue,238	settings: Rc<RefCell<Settings>>,239}240impl ContextInitializer {241	pub fn new(s: State, resolver: PathResolver) -> Self {242		let settings = Settings {243			ext_vars: Default::default(),244			ext_natives: Default::default(),245			globals: Default::default(),246			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),247			path_resolver: resolver,248		};249		let settings = Rc::new(RefCell::new(settings));250		Self {251			#[cfg(not(feature = "legacy-this-file"))]252			context: {253				let mut context = ContextBuilder::with_capacity(1);254				context.bind(255					"std".into(),256					Thunk::evaluated(Val::Obj(stdlib_uncached(s, settings.clone()))),257				);258				context.build()259			},260			#[cfg(feature = "legacy-this-file")]261			stdlib_obj: stdlib_uncached(s, settings.clone()),262			settings,263		}264	}265	pub fn settings(&self) -> Ref<Settings> {266		self.settings.borrow()267	}268	pub fn settings_mut(&self) -> RefMut<Settings> {269		self.settings.borrow_mut()270	}271	pub fn add_ext_var(&self, name: IStr, value: Val) {272		self.settings_mut()273			.ext_vars274			.insert(name, TlaArg::Val(value));275	}276	pub fn add_ext_str(&self, name: IStr, value: IStr) {277		self.settings_mut()278			.ext_vars279			.insert(name, TlaArg::String(value));280	}281	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {282		let code = code.into();283		let source = extvar_source(name, code.clone());284		let parsed = jrsonnet_parser::parse(285			&code,286			&jrsonnet_parser::ParserSettings {287				file_name: source.clone(),288			},289		)290		.map_err(|e| ImportSyntaxError {291			path: source,292			error: Box::new(e),293		})?;294		// self.data_mut().volatile_files.insert(source_name, code);295		self.settings_mut()296			.ext_vars297			.insert(name.into(), TlaArg::Code(parsed));298		Ok(())299	}300	pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {301		self.settings_mut().ext_natives.insert(name, cb);302	}303}304impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {305	#[cfg(not(feature = "legacy-this-file"))]306	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {307		let out = self.context.clone();308		let globals = &self.settings().globals;309		if globals.is_empty() {310			return out;311		}312313		let mut out = ContextBuilder::extend(out);314		for (k, v) in globals.iter() {315			out.bind(k.clone(), v.clone());316		}317		out.build()318	}319	#[cfg(feature = "legacy-this-file")]320	fn initialize(&self, s: State, source: Source) -> jrsonnet_evaluator::Context {321		let mut builder = ObjValueBuilder::new();322		builder.with_super(self.stdlib_obj.clone());323		builder324			.member("thisFile".into())325			.hide()326			.value(327				s,328				Val::Str(match source.source_path().path() {329					Some(p) => self.settings().path_resolver.resolve(p).into(),330					None => source.source_path().to_string().into(),331				}),332			)333			.expect("this object builder is empty");334		let stdlib_with_this_file = builder.build();335336		let mut context = ContextBuilder::with_capacity(1);337		context.bind(338			"std".into(),339			Thunk::evaluated(Val::Obj(stdlib_with_this_file)),340		);341		for (k, v) in self.settings().globals.iter() {342			context.bind(k.clone(), v.clone());343		}344		context.build()345	}346	fn as_any(&self) -> &dyn std::any::Any {347		self348	}349}350351#[builtin]352fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {353	use Either4::*;354	Ok(match x {355		A(x) => x.chars().count(),356		B(x) => x.len(),357		C(x) => x.len(),358		D(f) => f.params_len(),359	})360}361362#[builtin]363const fn builtin_codepoint(str: char) -> Result<u32> {364	Ok(str as u32)365}366367#[builtin]368fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {369	Ok(str.chars().skip(from as usize).take(len as usize).collect())370}371372#[builtin(fields(373	settings: Rc<RefCell<Settings>>,374))]375fn builtin_ext_var(this: &builtin_ext_var, s: State, x: IStr) -> Result<Any> {376	let ctx = s.create_default_context(extvar_source(&x, ""));377	Ok(Any(this378		.settings379		.borrow()380		.ext_vars381		.get(&x)382		.cloned()383		.ok_or(UndefinedExternalVariable(x))?384		.evaluate_arg(s.clone(), ctx, true)?385		.evaluate(s)?))386}387388#[builtin(fields(389	settings: Rc<RefCell<Settings>>,390))]391fn builtin_native(this: &builtin_native, name: IStr) -> Result<Any> {392	Ok(Any(this393		.settings394		.borrow()395		.ext_natives396		.get(&name)397		.cloned()398		.map_or(Val::Null, |v| {399			Val::Func(FuncVal::Builtin(v.clone()))400		})))401}402403#[builtin]404fn builtin_char(n: u32) -> Result<char> {405	Ok(std::char::from_u32(n as u32).ok_or(InvalidUnicodeCodepointGot(n as u32))?)406}407408#[builtin(fields(409	settings: Rc<RefCell<Settings>>,410))]411fn builtin_trace(412	this: &builtin_trace,413	s: State,414	loc: CallLocation,415	str: IStr,416	rest: Thunk<Val>,417) -> Result<Any> {418	this.settings419		.borrow()420		.trace_printer421		.print_trace(s.clone(), loc, str);422	Ok(Any(rest.evaluate(s)?))423}424425#[builtin]426fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {427	Ok(str.replace(&from as &str, &to as &str))428}429430#[builtin]431fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {432	use Either2::*;433	Ok(VecVal(Cc::new(match maxsplits {434		A(n) => str435			.splitn(n + 1, &c as &str)436			.map(|s| Val::Str(s.into()))437			.collect(),438		B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),439	})))440}441442#[builtin]443fn builtin_ascii_upper(str: IStr) -> Result<String> {444	Ok(str.to_ascii_uppercase())445}446447#[builtin]448fn builtin_ascii_lower(str: IStr) -> Result<String> {449	Ok(str.to_ascii_lowercase())450}451452#[builtin]453fn builtin_find_substr(pat: IStr, str: IStr) -> Result<ArrValue> {454	if pat.is_empty() || str.is_empty() || pat.len() > str.len() {455		return Ok(ArrValue::empty());456	}457458	let str = str.as_str();459	let pat = pat.as_bytes();460	let strb = str.as_bytes();461462	let max_pos = str.len() - pat.len();463464	let mut out: Vec<Val> = Vec::new();465	for (ch_idx, (i, _)) in str466		.char_indices()467		.take_while(|(i, _)| i <= &max_pos)468		.enumerate()469	{470		if &strb[i..i + pat.len()] == pat {471			out.push(Val::Num(ch_idx as f64))472		}473	}474	Ok(out.into())475}476477#[allow(clippy::comparison_chain)]478#[builtin]479fn builtin_starts_with(480	s: State,481	a: Either![IStr, ArrValue],482	b: Either![IStr, ArrValue],483) -> Result<bool> {484	Ok(match (a, b) {485		(Either2::A(a), Either2::A(b)) => a.starts_with(b.as_str()),486		(Either2::B(a), Either2::B(b)) => {487			if b.len() > a.len() {488				return Ok(false);489			} else if b.len() == a.len() {490				return equals(s, &Val::Arr(a), &Val::Arr(b));491			} else {492				for (a, b) in a493					.slice(None, Some(b.len()), None)494					.iter(s.clone())495					.zip(b.iter(s.clone()))496				{497					let a = a?;498					let b = b?;499					if !equals(s.clone(), &a, &b)? {500						return Ok(false);501					}502				}503				true504			}505		}506		_ => throw_runtime!("both arguments should be of the same type"),507	})508}509510#[allow(clippy::comparison_chain)]511#[builtin]512fn builtin_ends_with(513	s: State,514	a: Either![IStr, ArrValue],515	b: Either![IStr, ArrValue],516) -> Result<bool> {517	Ok(match (a, b) {518		(Either2::A(a), Either2::A(b)) => a.ends_with(b.as_str()),519		(Either2::B(a), Either2::B(b)) => {520			if b.len() > a.len() {521				return Ok(false);522			} else if b.len() == a.len() {523				return equals(s, &Val::Arr(a), &Val::Arr(b));524			} else {525				let a_len = a.len();526				for (a, b) in a527					.slice(Some(a_len - b.len()), None, None)528					.iter(s.clone())529					.zip(b.iter(s.clone()))530				{531					let a = a?;532					let b = b?;533					if !equals(s.clone(), &a, &b)? {534						return Ok(false);535					}536				}537				true538			}539		}540		_ => throw_runtime!("both arguments should be of the same type"),541	})542}543544pub trait StateExt {545	/// This method was previously implemented in jrsonnet-evaluator itself546	fn with_stdlib(&self);547	fn add_global(&self, name: IStr, value: Thunk<Val>);548}549550impl StateExt for State {551	fn with_stdlib(&self) {552		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());553		self.settings_mut().context_initializer = Box::new(initializer)554	}555	fn add_global(&self, name: IStr, value: Thunk<Val>) {556		self.settings()557			.context_initializer558			.as_any()559			.downcast_ref::<ContextInitializer>()560			.expect("not standard context initializer")561			.settings_mut()562			.globals563			.insert(name, value);564	}565}
after · crates/jrsonnet-stdlib/src/lib.rs
1use std::{2	cell::{Ref, RefCell, RefMut},3	collections::HashMap,4	rc::Rc,5};67use jrsonnet_evaluator::{8	error::{Error::*, Result},9	function::{builtin::Builtin, ArgLike, CallLocation, FuncVal, TlaArg},10	gc::{GcHashMap, TraceBox},11	tb, throw_runtime,12	trace::PathResolver,13	typed::{Any, Either, Either2, Either4, VecVal, M1},14	val::{equals, ArrValue},15	Context, ContextBuilder, IStr, ObjValue, ObjValueBuilder, State, Thunk, Val,16};17use jrsonnet_gcmodule::Cc;18use jrsonnet_macros::builtin;19use jrsonnet_parser::Source;2021mod expr;22mod types;23pub use types::*;24mod arrays;25pub use arrays::*;26mod math;27pub use math::*;28mod operator;29pub use operator::*;30mod sort;31pub use sort::*;32mod hash;33pub use hash::*;34mod encoding;35pub use encoding::*;36mod objects;37pub use objects::*;38mod manifest;39pub use manifest::*;40mod parse;41pub use parse::*;4243pub fn stdlib_uncached(s: State, settings: Rc<RefCell<Settings>>) -> ObjValue {44	let mut builder = ObjValueBuilder::new();4546	let expr = expr::stdlib_expr();47	let eval = jrsonnet_evaluator::evaluate(s.clone(), Context::default(), &expr)48		.expect("stdlib.jsonnet should have no errors")49		.as_obj()50		.expect("stdlib.jsonnet should evaluate to object");5152	builder.with_super(eval);5354	for (name, builtin) in [55		("length".into(), builtin_length::INST),56		// Types57		("type".into(), builtin_type::INST),58		("isString".into(), builtin_is_string::INST),59		("isNumber".into(), builtin_is_number::INST),60		("isBoolean".into(), builtin_is_boolean::INST),61		("isObject".into(), builtin_is_object::INST),62		("isArray".into(), builtin_is_array::INST),63		("isFunction".into(), builtin_is_function::INST),64		// Arrays65		("makeArray".into(), builtin_make_array::INST),66		("slice".into(), builtin_slice::INST),67		("map".into(), builtin_map::INST),68		("flatMap".into(), builtin_flatmap::INST),69		("filter".into(), builtin_filter::INST),70		("foldl".into(), builtin_foldl::INST),71		("foldr".into(), builtin_foldr::INST),72		("range".into(), builtin_range::INST),73		("join".into(), builtin_join::INST),74		("reverse".into(), builtin_reverse::INST),75		("any".into(), builtin_any::INST),76		("all".into(), builtin_all::INST),77		("member".into(), builtin_member::INST),78		("count".into(), builtin_count::INST),79		// Math80		("modulo".into(), builtin_modulo::INST),81		("floor".into(), builtin_floor::INST),82		("ceil".into(), builtin_ceil::INST),83		("log".into(), builtin_log::INST),84		("pow".into(), builtin_pow::INST),85		("sqrt".into(), builtin_sqrt::INST),86		("sin".into(), builtin_sin::INST),87		("cos".into(), builtin_cos::INST),88		("tan".into(), builtin_tan::INST),89		("asin".into(), builtin_asin::INST),90		("acos".into(), builtin_acos::INST),91		("atan".into(), builtin_atan::INST),92		("exp".into(), builtin_exp::INST),93		("mantissa".into(), builtin_mantissa::INST),94		("exponent".into(), builtin_exponent::INST),95		// Operator96		("mod".into(), builtin_mod::INST),97		("primitiveEquals".into(), builtin_primitive_equals::INST),98		("equals".into(), builtin_equals::INST),99		("format".into(), builtin_format::INST),100		// Sort101		("sort".into(), builtin_sort::INST),102		// Hash103		("md5".into(), builtin_md5::INST),104		// Encoding105		("encodeUTF8".into(), builtin_encode_utf8::INST),106		("decodeUTF8".into(), builtin_decode_utf8::INST),107		("base64".into(), builtin_base64::INST),108		("base64Decode".into(), builtin_base64_decode::INST),109		(110			"base64DecodeBytes".into(),111			builtin_base64_decode_bytes::INST,112		),113		// Objects114		("objectFieldsEx".into(), builtin_object_fields_ex::INST),115		("objectHasEx".into(), builtin_object_has_ex::INST),116		// Manifest117		("escapeStringJson".into(), builtin_escape_string_json::INST),118		("manifestJsonEx".into(), builtin_manifest_json_ex::INST),119		("manifestYamlDoc".into(), builtin_manifest_yaml_doc::INST),120		// Parsing121		("parseJson".into(), builtin_parse_json::INST),122		("parseYaml".into(), builtin_parse_yaml::INST),123		// Misc124		("codepoint".into(), builtin_codepoint::INST),125		("substr".into(), builtin_substr::INST),126		("char".into(), builtin_char::INST),127		("strReplace".into(), builtin_str_replace::INST),128		("splitLimit".into(), builtin_splitlimit::INST),129		("asciiUpper".into(), builtin_ascii_upper::INST),130		("asciiLower".into(), builtin_ascii_lower::INST),131		("findSubstr".into(), builtin_find_substr::INST),132		("startsWith".into(), builtin_starts_with::INST),133		("endsWith".into(), builtin_ends_with::INST),134	]135	.iter()136	.cloned()137	{138		builder139			.member(name)140			.hide()141			.value(s.clone(), Val::Func(FuncVal::StaticBuiltin(builtin)))142			.expect("no conflict");143	}144145	builder146		.member("extVar".into())147		.hide()148		.value(149			s.clone(),150			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_ext_var {151				settings: settings.clone()152			})))),153		)154		.expect("no conflict");155	builder156		.member("native".into())157		.hide()158		.value(159			s.clone(),160			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_native {161				settings: settings.clone()162			})))),163		)164		.expect("no conflict");165	builder166		.member("trace".into())167		.hide()168		.value(169			s.clone(),170			Val::Func(FuncVal::Builtin(Cc::new(tb!(builtin_trace { settings })))),171		)172		.expect("no conflict");173174	builder175		.member("id".into())176		.hide()177		.value(s, Val::Func(FuncVal::Id))178		.expect("no conflict");179180	builder.build()181}182183pub trait TracePrinter {184	fn print_trace(&self, s: State, loc: CallLocation, value: IStr);185}186187pub struct StdTracePrinter {188	resolver: PathResolver,189}190impl StdTracePrinter {191	pub fn new(resolver: PathResolver) -> Self {192		Self { resolver }193	}194}195impl TracePrinter for StdTracePrinter {196	fn print_trace(&self, _s: State, loc: CallLocation, value: IStr) {197		eprint!("TRACE:");198		if let Some(loc) = loc.0 {199			let locs = loc.0.map_source_locations(&[loc.1]);200			eprint!(201				" {}:{}",202				match loc.0.source_path().path() {203					Some(p) => self.resolver.resolve(p),204					None => loc.0.source_path().to_string(),205				},206				locs[0].line207			);208		}209		eprintln!(" {}", value);210	}211}212213pub struct Settings {214	/// Used for `std.extVar`215	pub ext_vars: HashMap<IStr, TlaArg>,216	/// Used for `std.native`217	pub ext_natives: HashMap<IStr, Cc<TraceBox<dyn Builtin>>>,218	/// Helper to add globals without implementing custom ContextInitializer219	pub globals: GcHashMap<IStr, Thunk<Val>>,220	/// Used for `std.trace`221	pub trace_printer: Box<dyn TracePrinter>,222	/// Used for `std.thisFile`223	pub path_resolver: PathResolver,224}225226pub fn extvar_source(name: &str, code: impl Into<IStr>) -> Source {227	let source_name = format!("<extvar:{}>", name);228	Source::new_virtual(source_name.into(), code.into())229}230231pub struct ContextInitializer {232	// When we don't need to support legacy-this-file, we can reuse same context for all files233	#[cfg(not(feature = "legacy-this-file"))]234	context: Context,235	// Otherwise, we can only keep first stdlib layer, and then stack thisFile on top of it236	#[cfg(feature = "legacy-this-file")]237	stdlib_obj: ObjValue,238	settings: Rc<RefCell<Settings>>,239}240impl ContextInitializer {241	pub fn new(s: State, resolver: PathResolver) -> Self {242		let settings = Settings {243			ext_vars: Default::default(),244			ext_natives: Default::default(),245			globals: Default::default(),246			trace_printer: Box::new(StdTracePrinter::new(resolver.clone())),247			path_resolver: resolver,248		};249		let settings = Rc::new(RefCell::new(settings));250		Self {251			#[cfg(not(feature = "legacy-this-file"))]252			context: {253				let mut context = ContextBuilder::with_capacity(1);254				context.bind(255					"std".into(),256					Thunk::evaluated(Val::Obj(stdlib_uncached(s, settings.clone()))),257				);258				context.build()259			},260			#[cfg(feature = "legacy-this-file")]261			stdlib_obj: stdlib_uncached(s, settings.clone()),262			settings,263		}264	}265	pub fn settings(&self) -> Ref<Settings> {266		self.settings.borrow()267	}268	pub fn settings_mut(&self) -> RefMut<Settings> {269		self.settings.borrow_mut()270	}271	pub fn add_ext_var(&self, name: IStr, value: Val) {272		self.settings_mut()273			.ext_vars274			.insert(name, TlaArg::Val(value));275	}276	pub fn add_ext_str(&self, name: IStr, value: IStr) {277		self.settings_mut()278			.ext_vars279			.insert(name, TlaArg::String(value));280	}281	pub fn add_ext_code(&self, name: &str, code: impl Into<IStr>) -> Result<()> {282		let code = code.into();283		let source = extvar_source(name, code.clone());284		let parsed = jrsonnet_parser::parse(285			&code,286			&jrsonnet_parser::ParserSettings {287				file_name: source.clone(),288			},289		)290		.map_err(|e| ImportSyntaxError {291			path: source,292			error: Box::new(e),293		})?;294		// self.data_mut().volatile_files.insert(source_name, code);295		self.settings_mut()296			.ext_vars297			.insert(name.into(), TlaArg::Code(parsed));298		Ok(())299	}300	pub fn add_native(&self, name: IStr, cb: Cc<TraceBox<dyn Builtin>>) {301		self.settings_mut().ext_natives.insert(name, cb);302	}303}304impl jrsonnet_evaluator::ContextInitializer for ContextInitializer {305	#[cfg(not(feature = "legacy-this-file"))]306	fn initialize(&self, _s: State, _source: Source) -> jrsonnet_evaluator::Context {307		let out = self.context.clone();308		let globals = &self.settings().globals;309		if globals.is_empty() {310			return out;311		}312313		let mut out = ContextBuilder::extend(out);314		for (k, v) in globals.iter() {315			out.bind(k.clone(), v.clone());316		}317		out.build()318	}319	#[cfg(feature = "legacy-this-file")]320	fn initialize(&self, s: State, source: Source) -> jrsonnet_evaluator::Context {321		let mut builder = ObjValueBuilder::new();322		builder.with_super(self.stdlib_obj.clone());323		builder324			.member("thisFile".into())325			.hide()326			.value(327				s,328				Val::Str(match source.source_path().path() {329					Some(p) => self.settings().path_resolver.resolve(p).into(),330					None => source.source_path().to_string().into(),331				}),332			)333			.expect("this object builder is empty");334		let stdlib_with_this_file = builder.build();335336		let mut context = ContextBuilder::with_capacity(1);337		context.bind(338			"std".into(),339			Thunk::evaluated(Val::Obj(stdlib_with_this_file)),340		);341		for (k, v) in self.settings().globals.iter() {342			context.bind(k.clone(), v.clone());343		}344		context.build()345	}346	fn as_any(&self) -> &dyn std::any::Any {347		self348	}349}350351#[builtin]352fn builtin_length(x: Either![IStr, ArrValue, ObjValue, FuncVal]) -> Result<usize> {353	use Either4::*;354	Ok(match x {355		A(x) => x.chars().count(),356		B(x) => x.len(),357		C(x) => x.len(),358		D(f) => f.params_len(),359	})360}361362#[builtin]363const fn builtin_codepoint(str: char) -> Result<u32> {364	Ok(str as u32)365}366367#[builtin]368fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {369	Ok(str.chars().skip(from).take(len).collect())370}371372#[builtin(fields(373	settings: Rc<RefCell<Settings>>,374))]375fn builtin_ext_var(this: &builtin_ext_var, s: State, x: IStr) -> Result<Any> {376	let ctx = s.create_default_context(extvar_source(&x, ""));377	Ok(Any(this378		.settings379		.borrow()380		.ext_vars381		.get(&x)382		.cloned()383		.ok_or_else(|| UndefinedExternalVariable(x))?384		.evaluate_arg(s.clone(), ctx, true)?385		.evaluate(s)?))386}387388#[builtin(fields(389	settings: Rc<RefCell<Settings>>,390))]391fn builtin_native(this: &builtin_native, name: IStr) -> Result<Any> {392	Ok(Any(this393		.settings394		.borrow()395		.ext_natives396		.get(&name)397		.cloned()398		.map_or(Val::Null, |v| {399			Val::Func(FuncVal::Builtin(v.clone()))400		})))401}402403#[builtin]404fn builtin_char(n: u32) -> Result<char> {405	Ok(std::char::from_u32(n).ok_or_else(|| InvalidUnicodeCodepointGot(n))?)406}407408#[builtin(fields(409	settings: Rc<RefCell<Settings>>,410))]411fn builtin_trace(412	this: &builtin_trace,413	s: State,414	loc: CallLocation,415	str: IStr,416	rest: Thunk<Val>,417) -> Result<Any> {418	this.settings419		.borrow()420		.trace_printer421		.print_trace(s.clone(), loc, str);422	Ok(Any(rest.evaluate(s)?))423}424425#[builtin]426fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {427	Ok(str.replace(&from as &str, &to as &str))428}429430#[builtin]431fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {432	use Either2::*;433	Ok(VecVal(Cc::new(match maxsplits {434		A(n) => str435			.splitn(n + 1, &c as &str)436			.map(|s| Val::Str(s.into()))437			.collect(),438		B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),439	})))440}441442#[builtin]443fn builtin_ascii_upper(str: IStr) -> Result<String> {444	Ok(str.to_ascii_uppercase())445}446447#[builtin]448fn builtin_ascii_lower(str: IStr) -> Result<String> {449	Ok(str.to_ascii_lowercase())450}451452#[builtin]453fn builtin_find_substr(pat: IStr, str: IStr) -> Result<ArrValue> {454	if pat.is_empty() || str.is_empty() || pat.len() > str.len() {455		return Ok(ArrValue::empty());456	}457458	let str = str.as_str();459	let pat = pat.as_bytes();460	let strb = str.as_bytes();461462	let max_pos = str.len() - pat.len();463464	let mut out: Vec<Val> = Vec::new();465	for (ch_idx, (i, _)) in str466		.char_indices()467		.take_while(|(i, _)| i <= &max_pos)468		.enumerate()469	{470		if &strb[i..i + pat.len()] == pat {471			out.push(Val::Num(ch_idx as f64))472		}473	}474	Ok(out.into())475}476477#[allow(clippy::comparison_chain)]478#[builtin]479fn builtin_starts_with(480	s: State,481	a: Either![IStr, ArrValue],482	b: Either![IStr, ArrValue],483) -> Result<bool> {484	Ok(match (a, b) {485		(Either2::A(a), Either2::A(b)) => a.starts_with(b.as_str()),486		(Either2::B(a), Either2::B(b)) => {487			if b.len() > a.len() {488				return Ok(false);489			} else if b.len() == a.len() {490				return equals(s, &Val::Arr(a), &Val::Arr(b));491			} else {492				for (a, b) in a493					.slice(None, Some(b.len()), None)494					.iter(s.clone())495					.zip(b.iter(s.clone()))496				{497					let a = a?;498					let b = b?;499					if !equals(s.clone(), &a, &b)? {500						return Ok(false);501					}502				}503				true504			}505		}506		_ => throw_runtime!("both arguments should be of the same type"),507	})508}509510#[allow(clippy::comparison_chain)]511#[builtin]512fn builtin_ends_with(513	s: State,514	a: Either![IStr, ArrValue],515	b: Either![IStr, ArrValue],516) -> Result<bool> {517	Ok(match (a, b) {518		(Either2::A(a), Either2::A(b)) => a.ends_with(b.as_str()),519		(Either2::B(a), Either2::B(b)) => {520			if b.len() > a.len() {521				return Ok(false);522			} else if b.len() == a.len() {523				return equals(s, &Val::Arr(a), &Val::Arr(b));524			} else {525				let a_len = a.len();526				for (a, b) in a527					.slice(Some(a_len - b.len()), None, None)528					.iter(s.clone())529					.zip(b.iter(s.clone()))530				{531					let a = a?;532					let b = b?;533					if !equals(s.clone(), &a, &b)? {534						return Ok(false);535					}536				}537				true538			}539		}540		_ => throw_runtime!("both arguments should be of the same type"),541	})542}543544pub trait StateExt {545	/// This method was previously implemented in jrsonnet-evaluator itself546	fn with_stdlib(&self);547	fn add_global(&self, name: IStr, value: Thunk<Val>);548}549550impl StateExt for State {551	fn with_stdlib(&self) {552		let initializer = ContextInitializer::new(self.clone(), PathResolver::new_cwd_fallback());553		self.settings_mut().context_initializer = Box::new(initializer)554	}555	fn add_global(&self, name: IStr, value: Thunk<Val>) {556		self.settings()557			.context_initializer558			.as_any()559			.downcast_ref::<ContextInitializer>()560			.expect("not standard context initializer")561			.settings_mut()562			.globals563			.insert(name, value);564	}565}