git.delta.rocks / jrsonnet / refs/commits / 2afd5ff0dd7a

difftreelog

refactor extended strings

Yaroslav Bolyukin2022-12-03parent: #81f0998.patch.diff
in: master

16 files changed

modifiedcrates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -17,7 +17,7 @@
 	function::{CallLocation, FuncDesc, FuncVal},
 	tb, throw,
 	typed::Typed,
-	val::{CachedUnbound, IndexableVal, Thunk, ThunkValue},
+	val::{CachedUnbound, IndexableVal, StrValue, Thunk, ThunkValue},
 	Context, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result, State,
 	Unbound, Val,
 };
@@ -36,7 +36,7 @@
 		}
 	}
 	Some(match &*expr.0 {
-		Expr::Str(s) => Val::Str(s.clone()),
+		Expr::Str(s) => Val::Str(StrValue::Flat(s.clone())),
 		Expr::Num(n) => Val::Num(*n),
 		Expr::Literal(LiteralType::False) => Val::Bool(false),
 		Expr::Literal(LiteralType::True) => Val::Bool(true),
@@ -135,7 +135,7 @@
 					let fctx = Pending::new();
 					let mut new_bindings = GcHashMap::with_capacity(var.capacity_hint());
 					let value = Thunk::evaluated(Val::Arr(ArrValue::lazy(Cc::new(vec![
-						Thunk::evaluated(Val::Str(field.clone())),
+						Thunk::evaluated(Val::Str(StrValue::Flat(field.clone()))),
 						Thunk::new(tb!(ObjectFieldThunk {
 							field: field.clone(),
 							obj: obj.clone(),
@@ -436,7 +436,7 @@
 		Literal(LiteralType::False) => Val::Bool(false),
 		Literal(LiteralType::Null) => Val::Null,
 		Parened(e) => evaluate(ctx, e)?,
-		Str(v) => Val::Str(v.clone()),
+		Str(v) => Val::Str(StrValue::Flat(v.clone())),
 		Num(v) => Val::new_checked_num(*v)?,
 		BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
 		UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
@@ -457,14 +457,14 @@
 			ctx.super_obj()
 				.clone()
 				.expect("no super found")
-				.get_for(name, ctx.this().clone().expect("no this found"))?
+				.get_for(name.into_flat(), ctx.this().clone().expect("no this found"))?
 				.expect("value not found")
 		}
 		Index(value, index) => match (evaluate(ctx.clone(), value)?, evaluate(ctx, index)?) {
 			(Val::Obj(v), Val::Str(key)) => State::push(
 				CallLocation::new(loc),
 				|| format!("field <{key}> access"),
-				|| match v.get(key.clone()) {
+				|| match v.get(key.clone().into_flat()) {
 					Ok(Some(v)) => Ok(v),
 					#[cfg(not(feature = "friendly-errors"))]
 					Ok(None) => throw!(NoSuchField(key.clone(), vec![])),
@@ -476,7 +476,10 @@
 							#[cfg(feature = "exp-preserve-order")]
 							false,
 						) {
-							let conf = strsim::jaro_winkler(&field as &str, &key as &str);
+							let conf = strsim::jaro_winkler(
+								&field as &str,
+								&key.clone().into_flat() as &str,
+							);
 							if conf < 0.8 {
 								continue;
 							}
@@ -485,7 +488,7 @@
 						heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(Ordering::Equal));
 
 						throw!(NoSuchField(
-							key.clone(),
+							key.clone().into_flat(),
 							heap.into_iter().map(|(_, v)| v).collect()
 						))
 					}
@@ -505,7 +508,7 @@
 				v.get(n as usize)?
 					.ok_or_else(|| ArrayBoundsError(n as usize, v.len()))?
 			}
-			(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n)),
+			(Val::Arr(_), Val::Str(n)) => throw!(AttemptedIndexAnArrayWithString(n.into_flat())),
 			(Val::Arr(_), n) => throw!(ValueIndexMustBeTypeGot(
 				ValType::Arr,
 				ValType::Num,
@@ -514,16 +517,18 @@
 
 			(Val::Str(s), Val::Num(n)) => Val::Str({
 				let v: IStr = s
+					.clone()
+					.into_flat()
 					.chars()
 					.skip(n as usize)
 					.take(1)
 					.collect::<String>()
 					.into();
 				if v.is_empty() {
-					let size = s.chars().count();
+					let size = s.into_flat().chars().count();
 					throw!(StringBoundsError(n as usize, size))
 				}
-				v
+				StrValue::Flat(v)
 			}),
 			(Val::Str(_), n) => throw!(ValueIndexMustBeTypeGot(
 				ValType::Str,
@@ -654,7 +659,7 @@
 					|| format!("import {:?}", path.clone()),
 					|| s.import_resolved(resolved_path),
 				)?,
-				ImportStr(_) => Val::Str(s.import_resolved_str(resolved_path)?),
+				ImportStr(_) => Val::Str(StrValue::Flat(s.import_resolved_str(resolved_path)?)),
 				ImportBin(_) => Val::Arr(ArrValue::bytes(s.import_resolved_bin(resolved_path)?)),
 				_ => unreachable!(),
 			}
modifiedcrates/jrsonnet-evaluator/src/evaluate/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate/operator.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/operator.rs
@@ -3,8 +3,14 @@
 use jrsonnet_parser::{BinaryOpType, LocExpr, UnaryOpType};
 
 use crate::{
-	arr::ArrValue, error::ErrorKind::*, evaluate, stdlib::std_format, throw, typed::Typed,
-	val::equals, Context, Result, Val,
+	arr::ArrValue,
+	error::ErrorKind::*,
+	evaluate,
+	stdlib::std_format,
+	throw,
+	typed::Typed,
+	val::{equals, StrValue},
+	Context, Result, Val,
 };
 
 pub fn evaluate_unary_op(op: UnaryOpType, b: &Val) -> Result<Val> {
@@ -25,15 +31,21 @@
 	Ok(match (a, b) {
 		(Str(a), Str(b)) if a.is_empty() => Val::Str(b.clone()),
 		(Str(a), Str(b)) if b.is_empty() => Val::Str(a.clone()),
-		(Str(v1), Str(v2)) => Str(((**v1).to_owned() + v2).into()),
+		(Str(v1), Str(v2)) => Str(StrValue::concat(v1.clone(), v2.clone())),
 
 		// Can't use generic json serialization way, because it depends on number to string concatenation (std.jsonnet:890)
-		(Num(a), Str(b)) => Str(format!("{a}{b}").into()),
-		(Str(a), Num(b)) => Str(format!("{a}{b}").into()),
+		(Num(a), Str(b)) => Str(StrValue::Flat(format!("{a}{b}").into())),
+		(Str(a), Num(b)) => Str(StrValue::Flat(format!("{a}{b}").into())),
 
-		(Str(a), o) | (o, Str(a)) if a.is_empty() => Val::Str(o.clone().to_string()?),
-		(Str(a), o) => Str(format!("{a}{}", o.clone().to_string()?).into()),
-		(o, Str(a)) => Str(format!("{}{a}", o.clone().to_string()?).into()),
+		(Str(a), o) | (o, Str(a)) if a.is_empty() => {
+			Val::Str(StrValue::Flat(o.clone().to_string()?))
+		}
+		(Str(a), o) => Str(StrValue::Flat(
+			format!("{a}{}", o.clone().to_string()?).into(),
+		)),
+		(o, Str(a)) => Str(StrValue::Flat(
+			format!("{}{a}", o.clone().to_string()?).into(),
+		)),
 
 		(Obj(v1), Obj(v2)) => Obj(v2.extend_from(v1.clone())),
 		(Arr(a), Arr(b)) => Val::Arr(ArrValue::extended(a.clone(), b.clone())),
@@ -56,7 +68,9 @@
 			}
 			Ok(Num(a % b))
 		}
-		(Str(str), vals) => String::into_untyped(std_format(str.clone(), vals.clone())?),
+		(Str(str), vals) => {
+			String::into_untyped(std_format(&str.clone().into_flat(), vals.clone())?)
+		}
 		(a, b) => throw!(BinaryOperatorDoesNotOperateOnValues(
 			BinaryOpType::Mod,
 			a.value_type(),
@@ -120,10 +134,10 @@
 		(a, Lte, b) => Bool(evaluate_compare_op(a, b, Lte)?.is_le()),
 		(a, Gte, b) => Bool(evaluate_compare_op(a, b, Gte)?.is_ge()),
 
-		(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone(), true)),
+		(Str(a), In, Obj(obj)) => Bool(obj.has_field_ex(a.clone().into_flat(), true)),
 		(a, Mod, b) => evaluate_mod_op(a, b)?,
 
-		(Str(v1), Mul, Num(v2)) => Str(v1.repeat(*v2 as usize).into()),
+		(Str(v1), Mul, Num(v2)) => Str(StrValue::Flat(v1.to_string().repeat(*v2 as usize).into())),
 
 		// Bool X Bool
 		(Bool(a), And, Bool(b)) => Bool(*a && *b),
modifiedcrates/jrsonnet-evaluator/src/function/arglike.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/function/arglike.rs
+++ b/crates/jrsonnet-evaluator/src/function/arglike.rs
@@ -4,7 +4,13 @@
 use jrsonnet_parser::{ArgsDesc, LocExpr};
 
 use crate::{
-	error::Result, evaluate, gc::GcHashMap, tb, typed::Typed, val::ThunkValue, Context, Thunk, Val,
+	error::Result,
+	evaluate,
+	gc::GcHashMap,
+	tb,
+	typed::Typed,
+	val::{StrValue, ThunkValue},
+	Context, Thunk, Val,
 };
 
 /// Marker for arguments, which can be evaluated with context set to None
@@ -59,7 +65,7 @@
 impl ArgLike for TlaArg {
 	fn evaluate_arg(&self, ctx: Context, tailstrict: bool) -> Result<Thunk<Val>> {
 		match self {
-			TlaArg::String(s) => Ok(Thunk::evaluated(Val::Str(s.clone()))),
+			TlaArg::String(s) => Ok(Thunk::evaluated(Val::Str(StrValue::Flat(s.clone())))),
 			TlaArg::Code(code) => Ok(if tailstrict {
 				Thunk::evaluated(evaluate(ctx, code)?)
 			} else {
modifiedcrates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -7,7 +7,7 @@
 	Deserialize, Serialize,
 };
 
-use crate::{arr::ArrValue, error::Result, ObjValueBuilder, State, Val};
+use crate::{arr::ArrValue, error::Result, val::StrValue, ObjValueBuilder, State, Val};
 
 impl<'de> Deserialize<'de> for Val {
 	fn deserialize<D>(deserializer: D) -> Result<Val, D::Error>
@@ -49,7 +49,7 @@
 			where
 				E: serde::de::Error,
 			{
-				Ok(Val::Str(v.into()))
+				Ok(Val::Str(StrValue::Flat(v.into())))
 			}
 
 			// visit_num! {
@@ -152,7 +152,7 @@
 		match self {
 			Val::Bool(v) => serializer.serialize_bool(*v),
 			Val::Null => serializer.serialize_none(),
-			Val::Str(s) => serializer.serialize_str(s),
+			Val::Str(s) => serializer.serialize_str(&s.clone().into_flat()),
 			Val::Num(n) => serializer.serialize_f64(*n),
 			Val::Arr(arr) => {
 				let mut seq = serializer.serialize_seq(Some(arr.len()))?;
modifiedcrates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -147,7 +147,7 @@
 			}
 		}
 		Val::Null => buf.push_str("null"),
-		Val::Str(s) => escape_string_json_buf(s, buf),
+		Val::Str(s) => escape_string_json_buf(&s.clone().into_flat(), buf),
 		Val::Num(n) => write!(buf, "{n}").unwrap(),
 		Val::Arr(items) => {
 			buf.push('[');
@@ -256,7 +256,7 @@
 		let Val::Str(s) = val else {
 			throw!("output should be string for string manifest format, got {}", val.value_type())
 		};
-		out.write_str(&s).unwrap();
+		write!(out, "{s}").unwrap();
 		Ok(())
 	}
 }
modifiedcrates/jrsonnet-evaluator/src/stdlib/format.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/format.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/format.rs
@@ -589,6 +589,7 @@
 					.ok_or_else(|| InvalidUnicodeCodepointGot(n as u32))?,
 			),
 			Val::Str(s) => {
+				let s = s.into_flat();
 				if s.chars().count() != 1 {
 					throw!("%c expected 1 char string, got {}", s.chars().count(),);
 				}
modifiedcrates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -2,13 +2,12 @@
 #![allow(clippy::unnecessary_wraps)]
 
 use format::{format_arr, format_obj};
-use jrsonnet_interner::IStr;
 
 use crate::{error::Result, function::CallLocation, State, Val};
 
 pub mod format;
 
-pub fn std_format(str: IStr, vals: Val) -> Result<String> {
+pub fn std_format(str: &str, vals: Val) -> Result<String> {
 	State::push(
 		CallLocation::native(),
 		|| format!("std.format of {str}"),
modifiedcrates/jrsonnet-evaluator/src/typed/conversions.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/conversions.rs
+++ b/crates/jrsonnet-evaluator/src/typed/conversions.rs
@@ -11,7 +11,7 @@
 	function::{native::NativeDesc, FuncDesc, FuncVal},
 	throw,
 	typed::CheckType,
-	val::IndexableVal,
+	val::{IndexableVal, StrValue},
 	ObjValue, ObjValueBuilder, Val,
 };
 
@@ -187,13 +187,13 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Str(value))
+		Ok(Val::Str(StrValue::Flat(value)))
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
-			Val::Str(s) => Ok(s),
+			Val::Str(s) => Ok(s.into_flat()),
 			_ => unreachable!(),
 		}
 	}
@@ -203,7 +203,7 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::Simple(ValType::Str);
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Str(value.into()))
+		Ok(Val::Str(StrValue::Flat(value.into())))
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
@@ -219,13 +219,13 @@
 	const TYPE: &'static ComplexValType = &ComplexValType::Char;
 
 	fn into_untyped(value: Self) -> Result<Val> {
-		Ok(Val::Str(value.to_string().into()))
+		Ok(Val::Str(StrValue::Flat(value.to_string().into())))
 	}
 
 	fn from_untyped(value: Val) -> Result<Self> {
 		<Self as Typed>::TYPE.check(&value)?;
 		match value {
-			Val::Str(s) => Ok(s.chars().next().unwrap()),
+			Val::Str(s) => Ok(s.into_flat().chars().next().unwrap()),
 			_ => unreachable!(),
 		}
 	}
@@ -480,7 +480,7 @@
 
 	fn into_untyped(value: Self) -> Result<Val> {
 		match value {
-			IndexableVal::Str(s) => Ok(Val::Str(s)),
+			IndexableVal::Str(s) => Ok(Val::Str(StrValue::Flat(s))),
 			IndexableVal::Arr(a) => Ok(Val::Arr(a)),
 		}
 	}
modifiedcrates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -150,7 +150,7 @@
 			Self::Any => Ok(()),
 			Self::Simple(t) => t.check(value),
 			Self::Char => match value {
-				Val::Str(s) if s.len() == 1 || s.chars().count() == 1 => Ok(()),
+				Val::Str(s) if s.len() == 1 || s.clone().into_flat().chars().count() == 1 => Ok(()),
 				v => Err(TypeError::ExpectedGot(self.clone(), v.value_type()).into()),
 			},
 			Self::BoundedNumber(from, to) => {
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/val.rs
+++ b/crates/jrsonnet-evaluator/src/val.rs
@@ -1,4 +1,9 @@
-use std::{cell::RefCell, fmt::Debug, mem::replace};
+use std::{
+	cell::RefCell,
+	fmt::{self, Debug, Display},
+	mem::replace,
+	rc::Rc,
+};
 
 use jrsonnet_gcmodule::{Cc, Trace};
 use jrsonnet_interner::IStr;
@@ -117,7 +122,7 @@
 }
 
 impl<T: Debug + Trace> Debug for Thunk<T> {
-	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
 		write!(f, "Lazy")
 	}
 }
@@ -187,6 +192,87 @@
 	}
 }
 
+#[derive(Debug, Clone, Trace)]
+pub enum StrValue {
+	Flat(IStr),
+	Tree(Rc<(StrValue, StrValue, usize)>),
+}
+impl StrValue {
+	pub fn concat(a: StrValue, b: StrValue) -> Self {
+		if a.is_empty() {
+			b
+		} else if b.is_empty() {
+			a
+		} else {
+			let len = a.len() + b.len();
+			Self::Tree(Rc::new((a, b, len)))
+		}
+	}
+	pub fn into_flat(self) -> IStr {
+		match self {
+			StrValue::Flat(f) => f,
+			StrValue::Tree(_) => {
+				let mut buf = String::new();
+				self.into_flat_buf(&mut buf);
+				buf.into()
+			}
+		}
+	}
+	fn into_flat_buf(&self, out: &mut String) {
+		match self {
+			StrValue::Flat(f) => out.push_str(f),
+			StrValue::Tree(t) => {
+				t.0.into_flat_buf(out);
+				t.1.into_flat_buf(out);
+			}
+		}
+	}
+	pub fn len(&self) -> usize {
+		match self {
+			StrValue::Flat(v) => v.len(),
+			StrValue::Tree(t) => t.2,
+		}
+	}
+	pub fn is_empty(&self) -> bool {
+		match self {
+			Self::Flat(v) => v.is_empty(),
+			_ => false,
+		}
+	}
+}
+impl Display for StrValue {
+	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+		match self {
+			StrValue::Flat(v) => write!(f, "{v}"),
+			StrValue::Tree(t) => {
+				write!(f, "{}", t.0)?;
+				write!(f, "{}", t.1)
+			}
+		}
+	}
+}
+impl PartialEq for StrValue {
+	fn eq(&self, other: &Self) -> bool {
+		let a = self.clone().into_flat();
+		let b = other.clone().into_flat();
+		a == b
+	}
+}
+impl Eq for StrValue {}
+impl PartialOrd for StrValue {
+	fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
+		let a = self.clone().into_flat();
+		let b = other.clone().into_flat();
+		Some(a.cmp(&b))
+	}
+}
+impl Ord for StrValue {
+	fn cmp(&self, other: &Self) -> std::cmp::Ordering {
+		self.partial_cmp(other)
+			.expect("partial_cmp always returns Some")
+	}
+}
+
 /// Represents any valid Jsonnet value.
 #[derive(Debug, Clone, Trace)]
 pub enum Val {
@@ -195,7 +281,7 @@
 	/// Represents a Jsonnet null value.
 	Null,
 	/// Represents a Jsonnet string.
-	Str(IStr),
+	Str(StrValue),
 	/// Represents a Jsonnet number.
 	/// Should be finite, and not NaN
 	/// This restriction isn't enforced by enum, as enum field can't be marked as private
@@ -208,10 +294,12 @@
 	Func(FuncVal),
 }
 
+static_assertions::assert_eq_size!(Val, [u8; 24]);
+
 impl From<IndexableVal> for Val {
 	fn from(v: IndexableVal) -> Self {
 		match v {
-			IndexableVal::Str(s) => Self::Str(s),
+			IndexableVal::Str(s) => Self::Str(StrValue::Flat(s)),
 			IndexableVal::Arr(a) => Self::Arr(a),
 		}
 	}
@@ -232,7 +320,7 @@
 	}
 	pub fn as_str(&self) -> Option<IStr> {
 		match self {
-			Self::Str(s) => Some(s.clone()),
+			Self::Str(s) => Some(s.clone().into_flat()),
 			_ => None,
 		}
 	}
@@ -295,14 +383,14 @@
 			Self::Bool(true) => "true".into(),
 			Self::Bool(false) => "false".into(),
 			Self::Null => "null".into(),
-			Self::Str(s) => s.clone(),
+			Self::Str(s) => s.clone().into_flat(),
 			_ => self.manifest(ToStringFormat).map(IStr::from)?,
 		})
 	}
 
 	pub fn into_indexable(self) -> Result<IndexableVal> {
 		Ok(match self {
-			Val::Str(s) => IndexableVal::Str(s),
+			Val::Str(s) => IndexableVal::Str(s.into_flat()),
 			Val::Arr(arr) => IndexableVal::Arr(arr),
 			_ => throw!(ValueIsNotIndexable(self.value_type())),
 		})
modifiedcrates/jrsonnet-stdlib/src/arrays.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/arrays.rs
+++ b/crates/jrsonnet-stdlib/src/arrays.rs
@@ -37,12 +37,13 @@
 	func: NativeFn<((Either![String, Any],), Any)>,
 	arr: IndexableVal,
 ) -> Result<IndexableVal> {
+	use std::fmt::Write;
 	match arr {
 		IndexableVal::Str(str) => {
 			let mut out = String::new();
 			for c in str.chars() {
 				match func(Either2::A(c.to_string()))?.0 {
-					Val::Str(o) => out.push_str(&o),
+					Val::Str(o) => write!(out, "{o}").unwrap(),
 					Val::Null => continue,
 					_ => throw!("in std.join all items should be strings"),
 				};
@@ -101,6 +102,7 @@
 
 #[builtin]
 pub fn builtin_join(sep: IndexableVal, arr: ArrValue) -> Result<IndexableVal> {
+	use std::fmt::Write;
 	Ok(match sep {
 		IndexableVal::Arr(joiner_items) => {
 			let mut out = Vec::new();
@@ -141,7 +143,7 @@
 						out += &sep;
 					}
 					first = false;
-					out += &item;
+					write!(out, "{item}").unwrap()
 				} else if matches!(item, Val::Null) {
 					continue;
 				} else {
modifiedcrates/jrsonnet-stdlib/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/lib.rs
+++ b/crates/jrsonnet-stdlib/src/lib.rs
@@ -320,15 +320,19 @@
 	}
 	#[cfg(feature = "legacy-this-file")]
 	fn initialize(&self, s: State, source: Source) -> Context {
+		use jrsonnet_evaluator::val::StrValue;
+
 		let mut builder = ObjValueBuilder::new();
 		builder.with_super(self.stdlib_obj.clone());
 		builder
 			.member("thisFile".into())
 			.hide()
-			.value(Val::Str(match source.source_path().path() {
-				Some(p) => self.settings().path_resolver.resolve(p).into(),
-				None => source.source_path().to_string().into(),
-			}))
+			.value(Val::Str(StrValue::Flat(
+				match source.source_path().path() {
+					Some(p) => self.settings().path_resolver.resolve(p).into(),
+					None => source.source_path().to_string().into(),
+				},
+			)))
 			.expect("this object builder is empty");
 		let stdlib_with_this_file = builder.build();
 
modifiedcrates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest/yaml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/yaml.rs
@@ -118,6 +118,7 @@
 		}
 		Val::Null => buf.push_str("null"),
 		Val::Str(s) => {
+			let s = s.clone().into_flat();
 			if s.is_empty() {
 				buf.push_str("\"\"");
 			} else if let Some(s) = s.strip_suffix('\n') {
@@ -128,10 +129,10 @@
 					buf.push_str(&options.padding);
 					buf.push_str(line);
 				}
-			} else if !options.quote_keys && !yaml_needs_quotes(s) {
-				buf.push_str(s);
+			} else if !options.quote_keys && !yaml_needs_quotes(&s) {
+				buf.push_str(&s);
 			} else {
-				escape_string_json_buf(s, buf);
+				escape_string_json_buf(&s, buf);
 			}
 		}
 		Val::Num(n) => write!(buf, "{}", *n).unwrap(),
modifiedcrates/jrsonnet-stdlib/src/objects.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/objects.rs
+++ b/crates/jrsonnet-stdlib/src/objects.rs
@@ -1,5 +1,9 @@
 use jrsonnet_evaluator::{
-	error::Result, function::builtin, typed::VecVal, val::Val, IStr, ObjValue,
+	error::Result,
+	function::builtin,
+	typed::VecVal,
+	val::{StrValue, Val},
+	IStr, ObjValue,
 };
 use jrsonnet_gcmodule::Cc;
 
@@ -17,7 +21,10 @@
 		preserve_order,
 	);
 	Ok(VecVal(Cc::new(
-		out.into_iter().map(Val::Str).collect::<Vec<_>>(),
+		out.into_iter()
+			.map(StrValue::Flat)
+			.map(Val::Str)
+			.collect::<Vec<_>>(),
 	)))
 }
 
modifiedcrates/jrsonnet-stdlib/src/operator.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/operator.rs
+++ b/crates/jrsonnet-stdlib/src/operator.rs
@@ -7,7 +7,7 @@
 	operator::evaluate_mod_op,
 	stdlib::std_format,
 	typed::{Any, Either, Either2},
-	val::{equals, primitive_equals},
+	val::{equals, primitive_equals, StrValue},
 	IStr, Val,
 };
 
@@ -17,7 +17,7 @@
 	Ok(Any(evaluate_mod_op(
 		&match a {
 			A(v) => Val::Num(v),
-			B(s) => Val::Str(s),
+			B(s) => Val::Str(StrValue::Flat(s)),
 		},
 		&b.0,
 	)?))
@@ -35,5 +35,5 @@
 
 #[builtin]
 pub fn builtin_format(str: IStr, vals: Any) -> Result<String> {
-	std_format(str, vals.0)
+	std_format(&str, vals.0)
 }
modifiedcrates/jrsonnet-stdlib/src/strings.rsdiffbeforeafterboth
before · crates/jrsonnet-stdlib/src/strings.rs
1use jrsonnet_evaluator::{2	error::{ErrorKind::*, Result},3	function::builtin,4	throw,5	typed::{Either2, VecVal, M1},6	val::ArrValue,7	Either, IStr, Val,8};9use jrsonnet_gcmodule::Cc;1011#[builtin]12pub const fn builtin_codepoint(str: char) -> Result<u32> {13	Ok(str as u32)14}1516#[builtin]17pub fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {18	Ok(str.chars().skip(from).take(len).collect())19}2021#[builtin]22pub fn builtin_char(n: u32) -> Result<char> {23	Ok(std::char::from_u32(n).ok_or_else(|| InvalidUnicodeCodepointGot(n))?)24}2526#[builtin]27pub fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {28	Ok(str.replace(&from as &str, &to as &str))29}3031#[builtin]32pub fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {33	use Either2::*;34	Ok(VecVal(Cc::new(match maxsplits {35		A(n) => str36			.splitn(n + 1, &c as &str)37			.map(|s| Val::Str(s.into()))38			.collect(),39		B(_) => str.split(&c as &str).map(|s| Val::Str(s.into())).collect(),40	})))41}4243#[builtin]44pub fn builtin_ascii_upper(str: IStr) -> Result<String> {45	Ok(str.to_ascii_uppercase())46}4748#[builtin]49pub fn builtin_ascii_lower(str: IStr) -> Result<String> {50	Ok(str.to_ascii_lowercase())51}5253#[builtin]54pub fn builtin_find_substr(pat: IStr, str: IStr) -> Result<ArrValue> {55	if pat.is_empty() || str.is_empty() || pat.len() > str.len() {56		return Ok(ArrValue::empty());57	}5859	let str = str.as_str();60	let pat = pat.as_bytes();61	let strb = str.as_bytes();6263	let max_pos = str.len() - pat.len();6465	let mut out: Vec<Val> = Vec::new();66	for (ch_idx, (i, _)) in str67		.char_indices()68		.take_while(|(i, _)| i <= &max_pos)69		.enumerate()70	{71		if &strb[i..i + pat.len()] == pat {72			out.push(Val::Num(ch_idx as f64))73		}74	}75	Ok(out.into())76}7778#[builtin]79pub fn builtin_parse_int(str: IStr) -> Result<f64> {80	if let Some(raw) = str.strip_prefix('-') {81		if raw.is_empty() {82			throw!("integer only consists of a minus")83		}8485		parse_nat::<10>(raw).map(|value| -value)86	} else {87		if str.is_empty() {88			throw!("empty integer")89		}9091		parse_nat::<10>(str.as_str())92	}93}9495#[builtin]96pub fn builtin_parse_octal(str: IStr) -> Result<f64> {97	if str.is_empty() {98		throw!("empty octal integer");99	}100101	parse_nat::<8>(str.as_str())102}103104#[builtin]105pub fn builtin_parse_hex(str: IStr) -> Result<f64> {106	if str.is_empty() {107		throw!("empty hexadecimal integer");108	}109110	parse_nat::<16>(str.as_str())111}112113fn parse_nat<const BASE: u32>(raw: &str) -> Result<f64> {114	debug_assert!(115		1 <= BASE && BASE <= 16,116		"integer base should be between 1 and 16"117	);118119	const ZERO_CODE: u32 = '0' as u32;120	const UPPER_A_CODE: u32 = 'A' as u32;121	const LOWER_A_CODE: u32 = 'a' as u32;122123	#[inline]124	fn checked_sub_if(condition: bool, lhs: u32, rhs: u32) -> Option<u32> {125		if condition {126			lhs.checked_sub(rhs)127		} else {128			None129		}130	}131132	let base = BASE as f64;133134	raw.chars().try_fold(0f64, |aggregate, digit| {135		let digit = digit as u32;136		let digit = if let Some(digit) = checked_sub_if(BASE > 10, digit, LOWER_A_CODE) {137			digit + 10138		} else if let Some(digit) = checked_sub_if(BASE > 10, digit, UPPER_A_CODE) {139			digit + 10140		} else {141			digit.checked_sub(ZERO_CODE).unwrap_or(BASE)142		};143144		if digit < BASE {145			Ok(base * aggregate + digit as f64)146		} else {147			throw!("{raw:?} is not a base {BASE} integer",);148		}149	})150}151152#[cfg(test)]153mod tests {154	use super::*;155156	#[test]157	fn parse_nat_base_8() {158		assert_eq!(parse_nat::<8>("0").unwrap(), 0.);159		assert_eq!(parse_nat::<8>("5").unwrap(), 5.);160		assert_eq!(parse_nat::<8>("32").unwrap(), 0o32 as f64);161		assert_eq!(parse_nat::<8>("761").unwrap(), 0o761 as f64);162	}163164	#[test]165	fn parse_nat_base_10() {166		assert_eq!(parse_nat::<10>("0").unwrap(), 0.);167		assert_eq!(parse_nat::<10>("3").unwrap(), 3.);168		assert_eq!(parse_nat::<10>("27").unwrap(), 27.);169		assert_eq!(parse_nat::<10>("123").unwrap(), 123.);170	}171172	#[test]173	fn parse_nat_base_16() {174		assert_eq!(parse_nat::<16>("0").unwrap(), 0.);175		assert_eq!(parse_nat::<16>("A").unwrap(), 10.);176		assert_eq!(parse_nat::<16>("a9").unwrap(), 0xA9 as f64);177		assert_eq!(parse_nat::<16>("BbC").unwrap(), 0xBBC as f64);178	}179}
after · crates/jrsonnet-stdlib/src/strings.rs
1use jrsonnet_evaluator::{2	error::{ErrorKind::*, Result},3	function::builtin,4	throw,5	typed::{Either2, VecVal, M1},6	val::{ArrValue, StrValue},7	Either, IStr, Val,8};9use jrsonnet_gcmodule::Cc;1011#[builtin]12pub const fn builtin_codepoint(str: char) -> Result<u32> {13	Ok(str as u32)14}1516#[builtin]17pub fn builtin_substr(str: IStr, from: usize, len: usize) -> Result<String> {18	Ok(str.chars().skip(from).take(len).collect())19}2021#[builtin]22pub fn builtin_char(n: u32) -> Result<char> {23	Ok(std::char::from_u32(n).ok_or_else(|| InvalidUnicodeCodepointGot(n))?)24}2526#[builtin]27pub fn builtin_str_replace(str: String, from: IStr, to: IStr) -> Result<String> {28	Ok(str.replace(&from as &str, &to as &str))29}3031#[builtin]32pub fn builtin_splitlimit(str: IStr, c: IStr, maxsplits: Either![usize, M1]) -> Result<VecVal> {33	use Either2::*;34	Ok(VecVal(Cc::new(match maxsplits {35		A(n) => str36			.splitn(n + 1, &c as &str)37			.map(|s| Val::Str(StrValue::Flat(s.into())))38			.collect(),39		B(_) => str40			.split(&c as &str)41			.map(|s| Val::Str(StrValue::Flat(s.into())))42			.collect(),43	})))44}4546#[builtin]47pub fn builtin_ascii_upper(str: IStr) -> Result<String> {48	Ok(str.to_ascii_uppercase())49}5051#[builtin]52pub fn builtin_ascii_lower(str: IStr) -> Result<String> {53	Ok(str.to_ascii_lowercase())54}5556#[builtin]57pub fn builtin_find_substr(pat: IStr, str: IStr) -> Result<ArrValue> {58	if pat.is_empty() || str.is_empty() || pat.len() > str.len() {59		return Ok(ArrValue::empty());60	}6162	let str = str.as_str();63	let pat = pat.as_bytes();64	let strb = str.as_bytes();6566	let max_pos = str.len() - pat.len();6768	let mut out: Vec<Val> = Vec::new();69	for (ch_idx, (i, _)) in str70		.char_indices()71		.take_while(|(i, _)| i <= &max_pos)72		.enumerate()73	{74		if &strb[i..i + pat.len()] == pat {75			out.push(Val::Num(ch_idx as f64))76		}77	}78	Ok(out.into())79}8081#[builtin]82pub fn builtin_parse_int(str: IStr) -> Result<f64> {83	if let Some(raw) = str.strip_prefix('-') {84		if raw.is_empty() {85			throw!("integer only consists of a minus")86		}8788		parse_nat::<10>(raw).map(|value| -value)89	} else {90		if str.is_empty() {91			throw!("empty integer")92		}9394		parse_nat::<10>(str.as_str())95	}96}9798#[builtin]99pub fn builtin_parse_octal(str: IStr) -> Result<f64> {100	if str.is_empty() {101		throw!("empty octal integer");102	}103104	parse_nat::<8>(str.as_str())105}106107#[builtin]108pub fn builtin_parse_hex(str: IStr) -> Result<f64> {109	if str.is_empty() {110		throw!("empty hexadecimal integer");111	}112113	parse_nat::<16>(str.as_str())114}115116fn parse_nat<const BASE: u32>(raw: &str) -> Result<f64> {117	debug_assert!(118		1 <= BASE && BASE <= 16,119		"integer base should be between 1 and 16"120	);121122	const ZERO_CODE: u32 = '0' as u32;123	const UPPER_A_CODE: u32 = 'A' as u32;124	const LOWER_A_CODE: u32 = 'a' as u32;125126	#[inline]127	fn checked_sub_if(condition: bool, lhs: u32, rhs: u32) -> Option<u32> {128		if condition {129			lhs.checked_sub(rhs)130		} else {131			None132		}133	}134135	let base = BASE as f64;136137	raw.chars().try_fold(0f64, |aggregate, digit| {138		let digit = digit as u32;139		let digit = if let Some(digit) = checked_sub_if(BASE > 10, digit, LOWER_A_CODE) {140			digit + 10141		} else if let Some(digit) = checked_sub_if(BASE > 10, digit, UPPER_A_CODE) {142			digit + 10143		} else {144			digit.checked_sub(ZERO_CODE).unwrap_or(BASE)145		};146147		if digit < BASE {148			Ok(base * aggregate + digit as f64)149		} else {150			throw!("{raw:?} is not a base {BASE} integer",);151		}152	})153}154155#[cfg(test)]156mod tests {157	use super::*;158159	#[test]160	fn parse_nat_base_8() {161		assert_eq!(parse_nat::<8>("0").unwrap(), 0.);162		assert_eq!(parse_nat::<8>("5").unwrap(), 5.);163		assert_eq!(parse_nat::<8>("32").unwrap(), 0o32 as f64);164		assert_eq!(parse_nat::<8>("761").unwrap(), 0o761 as f64);165	}166167	#[test]168	fn parse_nat_base_10() {169		assert_eq!(parse_nat::<10>("0").unwrap(), 0.);170		assert_eq!(parse_nat::<10>("3").unwrap(), 3.);171		assert_eq!(parse_nat::<10>("27").unwrap(), 27.);172		assert_eq!(parse_nat::<10>("123").unwrap(), 123.);173	}174175	#[test]176	fn parse_nat_base_16() {177		assert_eq!(parse_nat::<16>("0").unwrap(), 0.);178		assert_eq!(parse_nat::<16>("A").unwrap(), 10.);179		assert_eq!(parse_nat::<16>("a9").unwrap(), 0xA9 as f64);180		assert_eq!(parse_nat::<16>("BbC").unwrap(), 0xBBC as f64);181	}182}