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

difftreelog

perf(evaluator) faster std.equals

Лач2020-07-02parent: #5c0b9a1.patch.diff
in: master

4 files changed

modifiedcrates/jrsonnet-evaluator/build.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/build.rs
+++ b/crates/jrsonnet-evaluator/build.rs
@@ -35,7 +35,7 @@
 								Member::Field(FieldMember {
 									name: FieldName::Fixed(name),
 									..
-								}) if **name == *"join" || **name == *"manifestJsonEx" || **name == *"escapeStringJson"
+								}) if **name == *"join" || **name == *"manifestJsonEx" || **name == *"escapeStringJson" || **name == *"equals"
 							)
 						})
 						.collect(),
modifiedcrates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -484,7 +484,14 @@
 				0, a, vec![];
 				1, b, vec![];
 			], {
-				Val::Bool(a == b)
+				Val::Bool(primitive_equals(&a, &b)?)
+			}),
+			// faster
+			("std", "equals") => parse_args!(context, "std.equals", args, 2, [
+				0, a, vec![];
+				1, b, vec![];
+			], {
+				Val::Bool(equals(&a, &b)?)
 			}),
 			("std", "modulo") => parse_args!(context, "std.modulo", args, 2, [
 				0, a: [Val::Num]!!Val::Num, vec![ValType::Num];
modifiedcrates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -380,7 +380,7 @@
 #[cfg(test)]
 pub mod tests {
 	use super::Val;
-	use crate::EvaluationState;
+	use crate::{create_error, EvaluationState, primitive_equals};
 	use jrsonnet_parser::*;
 	use std::{path::PathBuf, rc::Rc};
 
@@ -411,11 +411,11 @@
 	fn eval_state_standard() {
 		let state = EvaluationState::default();
 		state.with_stdlib();
-		assert_eq!(
-			state
-				.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#)
-				.unwrap(),
-			Val::Bool(true)
+		assert!(
+			primitive_equals(
+				&state.parse_evaluate_raw(r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#).unwrap(),
+				&Val::Bool(true),
+			).unwrap()
 		);
 	}
 
@@ -445,14 +445,14 @@
 	/// Asserts given code returns `true`
 	macro_rules! assert_eval {
 		($str: expr) => {
-			assert_eq!(eval!($str), Val::Bool(true))
+			assert!(primitive_equals(&eval!($str), &Val::Bool(true)).unwrap())
 		};
 	}
 
 	/// Asserts given code returns `false`
 	macro_rules! assert_eval_neg {
 		($str: expr) => {
-			assert_eq!(eval!($str), Val::Bool(false))
+			assert!(primitive_equals(&eval!($str), &Val::Bool(false)).unwrap())
 		};
 	}
 	macro_rules! assert_json {
@@ -663,9 +663,11 @@
 
 	#[test]
 	fn string_is_string() {
-		assert_eq!(
-			eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),
-			Val::Bool(false)
+		assert!(
+			primitive_equals(
+				&eval!("local arr = 'hello'; (!std.isArray(arr)) && (!std.isString(arr))"),
+				&Val::Bool(false),
+			).unwrap()
 		);
 	}
 
@@ -767,4 +769,10 @@
 			)
 		})
 	}
+
+	#[test]
+	fn equality(){
+		println!("{:?}", jrsonnet_parser::parse("{ x: 1, y: 2 } == { x: 1, y: 2 }", &ParserSettings::default()));
+		assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")
+	}
 }
modifiedcrates/jrsonnet-evaluator/src/val.rsdiffbeforeafterboth
before · crates/jrsonnet-evaluator/src/val.rs
1use crate::{2	create_error_result, evaluate,3	function::{parse_function_call, place_args},4	Context, Error, ObjValue, Result,5};6use jrsonnet_parser::{ArgsDesc, LocExpr, ParamsDesc};7use std::{8	cell::RefCell,9	fmt::{Debug, Display},10	rc::Rc,11};1213enum LazyValInternals {14	Computed(Val),15	Waiting(Box<dyn Fn() -> Result<Val>>),16}17#[derive(Clone)]18pub struct LazyVal(Rc<RefCell<LazyValInternals>>);19impl LazyVal {20	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {21		LazyVal(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))22	}23	pub fn new_resolved(val: Val) -> Self {24		LazyVal(Rc::new(RefCell::new(LazyValInternals::Computed(val))))25	}26	pub fn evaluate(&self) -> Result<Val> {27		let new_value = match &*self.0.borrow() {28			LazyValInternals::Computed(v) => return Ok(v.clone()),29			LazyValInternals::Waiting(f) => f()?,30		};31		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());32		Ok(new_value)33	}34}3536#[macro_export]37macro_rules! lazy_val {38	($f: expr) => {39		$crate::LazyVal::new(Box::new($f))40	};41}42#[macro_export]43macro_rules! resolved_lazy_val {44	($f: expr) => {45		$crate::LazyVal::new_resolved($f)46	};47}48impl Debug for LazyVal {49	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {50		write!(f, "Lazy")51	}52}53impl PartialEq for LazyVal {54	fn eq(&self, other: &Self) -> bool {55		Rc::ptr_eq(&self.0, &other.0)56	}57}5859#[derive(Debug, PartialEq, Clone)]60pub struct FuncDesc {61	pub ctx: Context,62	pub params: ParamsDesc,63	pub body: LocExpr,64}65impl FuncDesc {66	/// This function is always inlined to make tailstrict work67	pub fn evaluate(&self, call_ctx: Context, args: &ArgsDesc, tailstrict: bool) -> Result<Val> {68		let ctx = parse_function_call(69			call_ctx,70			Some(self.ctx.clone()),71			&self.params,72			args,73			tailstrict,74		)?;75		evaluate(ctx, &self.body)76	}7778	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {79		let ctx = place_args(call_ctx, Some(self.ctx.clone()), &self.params, args)?;80		evaluate(ctx, &self.body)81	}82}8384#[derive(Debug, Clone, Copy, PartialEq)]85pub enum ValType {86	Bool,87	Null,88	Str,89	Num,90	Arr,91	Obj,92	Func,93}94impl ValType {95	pub fn name(&self) -> &'static str {96		use ValType::*;97		match self {98			Bool => "boolean",99			Null => "null",100			Str => "string",101			Num => "number",102			Arr => "array",103			Obj => "object",104			Func => "function",105		}106	}107}108impl Display for ValType {109	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {110		write!(f, "{}", self.name())111	}112}113114#[derive(Debug, PartialEq, Clone)]115pub enum Val {116	Bool(bool),117	Null,118	Str(Rc<str>),119	Num(f64),120	Lazy(LazyVal),121	Arr(Rc<Vec<Val>>),122	Obj(ObjValue),123	Func(FuncDesc),124125	// Library functions implemented in native126	Intristic(Rc<str>, Rc<str>),127}128macro_rules! matches_unwrap {129	($e: expr, $p: pat, $r: expr) => {130		match $e {131			$p => $r,132			_ => panic!("no match"),133			}134	};135}136impl Val {137	/// Creates Val::Num after checking for overflow. As numbers are f64, we can just check for finity138	pub fn new_checked_num(num: f64) -> Result<Val> {139		if num.is_finite() {140			Ok(Val::Num(num))141		} else {142			create_error_result(Error::RuntimeError("overflow".into()))143		}144	}145146	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {147		let this_type = self.value_type()?;148		if this_type != val_type {149			create_error_result(Error::TypeMismatch(context, vec![val_type], this_type))150		} else {151			Ok(())152		}153	}154	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {155		self.assert_type(context, ValType::Bool)?;156		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Bool(v), v))157	}158	pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {159		self.assert_type(context, ValType::Str)?;160		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Str(v), v))161	}162	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {163		self.assert_type(context, ValType::Num)?;164		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Num(v), v))165	}166	pub fn unwrap_if_lazy(&self) -> Result<Self> {167		Ok(if let Val::Lazy(v) = self {168			v.evaluate()?.unwrap_if_lazy()?169		} else {170			self.clone()171		})172	}173	pub fn value_type(&self) -> Result<ValType> {174		Ok(match self {175			Val::Str(..) => ValType::Str,176			Val::Num(..) => ValType::Num,177			Val::Arr(..) => ValType::Arr,178			Val::Obj(..) => ValType::Obj,179			Val::Func(..) => ValType::Func,180			Val::Bool(_) => ValType::Bool,181			Val::Null => ValType::Null,182			Val::Intristic(_, _) => ValType::Func,183			Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,184		})185	}186	#[cfg(feature = "faster")]187	pub fn into_json(self, padding: usize) -> Result<Rc<str>> {188		manifest_json_ex(&self, &" ".repeat(padding)).map(|s| s.into())189	}190	#[cfg(not(feature = "faster"))]191	pub fn into_json(self, padding: usize) -> Result<Rc<str>> {192		with_state(|s| {193			let ctx = s194				.create_default_context()?195				.with_var("__tmp__to_json__".into(), self)?;196			Ok(evaluate(197				ctx,198				&el!(Expr::Apply(199					el!(Expr::Index(200						el!(Expr::Var("std".into())),201						el!(Expr::Str("manifestJsonEx".into()))202					)),203					ArgsDesc(vec![204						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),205						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))206					]),207					false208				)),209			)?210			.try_cast_str("to json")?)211		})212	}213}214215pub fn manifest_json_ex(val: &Val, padding: &str) -> Result<String> {216	let mut out = String::new();217	manifest_json_ex_buf(val, &mut out, padding, &mut String::new())?;218	Ok(out)219}220fn manifest_json_ex_buf(221	val: &Val,222	buf: &mut String,223	padding: &str,224	cur_padding: &mut String,225) -> Result<()> {226	use std::fmt::Write;227	match val.unwrap_if_lazy()? {228		Val::Bool(v) => {229			if v {230				buf.push_str("true");231			} else {232				buf.push_str("false");233			}234		}235		Val::Null => buf.push_str("null"),236		Val::Str(s) => buf.push_str(&escape_string_json(&s)),237		Val::Num(n) => write!(buf, "{}", n).unwrap(),238		Val::Arr(items) => {239			buf.push_str("[\n");240			if !items.is_empty() {241				let old_len = cur_padding.len();242				cur_padding.push_str(padding);243				for (i, item) in items.iter().enumerate() {244					if i != 0 {245						buf.push_str(",\n")246					}247					buf.push_str(cur_padding);248					manifest_json_ex_buf(item, buf, padding, cur_padding)?;249				}250				cur_padding.truncate(old_len);251			}252			buf.push('\n');253			buf.push_str(cur_padding);254			buf.push(']');255		}256		Val::Obj(obj) => {257			buf.push_str("{\n");258			let fields = obj.visible_fields();259			if !fields.is_empty() {260				let old_len = cur_padding.len();261				cur_padding.push_str(padding);262				for (i, field) in fields.into_iter().enumerate() {263					if i != 0 {264						buf.push_str(",\n")265					}266					buf.push_str(cur_padding);267					buf.push_str(&escape_string_json(&field));268					buf.push_str(": ");269					manifest_json_ex_buf(&obj.get(field)?.unwrap(), buf, padding, cur_padding)?;270				}271				cur_padding.truncate(old_len);272			}273			buf.push('\n');274			buf.push_str(cur_padding);275			buf.push('}');276		}277		Val::Func(_) | Val::Intristic(_, _) => create_error_result(Error::RuntimeError("tried to manifest function".into()))?,278		Val::Lazy(_) => unreachable!(),279	};280	Ok(())281}282pub fn escape_string_json(s: &str) -> String {283	use std::fmt::Write;284	let mut out = String::new();285	out.push('"');286	for c in s.chars() {287		match c {288			'"' => out.push_str("\\\""),289			'\\' => out.push_str("\\\\"),290			'\u{0008}' => out.push_str("\\b"),291			'\u{000c}' => out.push_str("\\f"),292			'\n' => out.push_str("\\n"),293			'\r' => out.push_str("\\r"),294			'\t' => out.push_str("\\t"),295			c if c < 32 as char || (c >= 127 as char && c <= 159 as char) => {296				write!(out, "\\u{:04x}", c as u32).unwrap()297			}298			c => out.push(c),299		}300	}301	out.push('"');302	out303}304305#[test]306fn json_test() {307	assert_eq!(escape_string_json("\u{001f}"), "\"\\u001f\"")308}
after · crates/jrsonnet-evaluator/src/val.rs
1use crate::{2	create_error_result, evaluate,3	function::{parse_function_call, place_args},4	Context, Error, ObjValue, Result,5};6use jrsonnet_parser::{ArgsDesc, LocExpr, ParamsDesc};7use std::{8	cell::RefCell,9	fmt::{Debug, Display},10	rc::Rc,11};1213enum LazyValInternals {14	Computed(Val),15	Waiting(Box<dyn Fn() -> Result<Val>>),16}17#[derive(Clone)]18pub struct LazyVal(Rc<RefCell<LazyValInternals>>);19impl LazyVal {20	pub fn new(f: Box<dyn Fn() -> Result<Val>>) -> Self {21		LazyVal(Rc::new(RefCell::new(LazyValInternals::Waiting(f))))22	}23	pub fn new_resolved(val: Val) -> Self {24		LazyVal(Rc::new(RefCell::new(LazyValInternals::Computed(val))))25	}26	pub fn evaluate(&self) -> Result<Val> {27		let new_value = match &*self.0.borrow() {28			LazyValInternals::Computed(v) => return Ok(v.clone()),29			LazyValInternals::Waiting(f) => f()?,30		};31		*self.0.borrow_mut() = LazyValInternals::Computed(new_value.clone());32		Ok(new_value)33	}34}3536#[macro_export]37macro_rules! lazy_val {38	($f: expr) => {39		$crate::LazyVal::new(Box::new($f))40	};41}42#[macro_export]43macro_rules! resolved_lazy_val {44	($f: expr) => {45		$crate::LazyVal::new_resolved($f)46	};47}48impl Debug for LazyVal {49	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {50		write!(f, "Lazy")51	}52}53impl PartialEq for LazyVal {54	fn eq(&self, other: &Self) -> bool {55		Rc::ptr_eq(&self.0, &other.0)56	}57}5859#[derive(Debug, PartialEq, Clone)]60pub struct FuncDesc {61	pub ctx: Context,62	pub params: ParamsDesc,63	pub body: LocExpr,64}65impl FuncDesc {66	/// This function is always inlined to make tailstrict work67	pub fn evaluate(&self, call_ctx: Context, args: &ArgsDesc, tailstrict: bool) -> Result<Val> {68		let ctx = parse_function_call(69			call_ctx,70			Some(self.ctx.clone()),71			&self.params,72			args,73			tailstrict,74		)?;75		evaluate(ctx, &self.body)76	}7778	pub fn evaluate_values(&self, call_ctx: Context, args: &[Val]) -> Result<Val> {79		let ctx = place_args(call_ctx, Some(self.ctx.clone()), &self.params, args)?;80		evaluate(ctx, &self.body)81	}82}8384#[derive(Debug, Clone, Copy, PartialEq)]85pub enum ValType {86	Bool,87	Null,88	Str,89	Num,90	Arr,91	Obj,92	Func,93}94impl ValType {95	pub fn name(&self) -> &'static str {96		use ValType::*;97		match self {98			Bool => "boolean",99			Null => "null",100			Str => "string",101			Num => "number",102			Arr => "array",103			Obj => "object",104			Func => "function",105		}106	}107}108impl Display for ValType {109	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {110		write!(f, "{}", self.name())111	}112}113114#[derive(Debug, Clone)]115pub enum Val {116	Bool(bool),117	Null,118	Str(Rc<str>),119	Num(f64),120	Lazy(LazyVal),121	Arr(Rc<Vec<Val>>),122	Obj(ObjValue),123	Func(FuncDesc),124125	// Library functions implemented in native126	Intristic(Rc<str>, Rc<str>),127}128macro_rules! matches_unwrap {129	($e: expr, $p: pat, $r: expr) => {130		match $e {131			$p => $r,132			_ => panic!("no match"),133			}134	};135}136impl Val {137	/// Creates Val::Num after checking for overflow. As numbers are f64, we can just check for finity138	pub fn new_checked_num(num: f64) -> Result<Val> {139		if num.is_finite() {140			Ok(Val::Num(num))141		} else {142			create_error_result(Error::RuntimeError("overflow".into()))143		}144	}145146	pub fn assert_type(&self, context: &'static str, val_type: ValType) -> Result<()> {147		let this_type = self.value_type()?;148		if this_type != val_type {149			create_error_result(Error::TypeMismatch(context, vec![val_type], this_type))150		} else {151			Ok(())152		}153	}154	pub fn try_cast_bool(self, context: &'static str) -> Result<bool> {155		self.assert_type(context, ValType::Bool)?;156		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Bool(v), v))157	}158	pub fn try_cast_str(self, context: &'static str) -> Result<Rc<str>> {159		self.assert_type(context, ValType::Str)?;160		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Str(v), v))161	}162	pub fn try_cast_num(self, context: &'static str) -> Result<f64> {163		self.assert_type(context, ValType::Num)?;164		Ok(matches_unwrap!(self.unwrap_if_lazy()?, Val::Num(v), v))165	}166	pub fn unwrap_if_lazy(&self) -> Result<Self> {167		Ok(if let Val::Lazy(v) = self {168			v.evaluate()?.unwrap_if_lazy()?169		} else {170			self.clone()171		})172	}173	pub fn value_type(&self) -> Result<ValType> {174		Ok(match self {175			Val::Str(..) => ValType::Str,176			Val::Num(..) => ValType::Num,177			Val::Arr(..) => ValType::Arr,178			Val::Obj(..) => ValType::Obj,179			Val::Func(..) => ValType::Func,180			Val::Bool(_) => ValType::Bool,181			Val::Null => ValType::Null,182			Val::Intristic(_, _) => ValType::Func,183			Val::Lazy(_) => self.clone().unwrap_if_lazy()?.value_type()?,184		})185	}186	#[cfg(feature = "faster")]187	pub fn into_json(self, padding: usize) -> Result<Rc<str>> {188		manifest_json_ex(&self, &" ".repeat(padding)).map(|s| s.into())189	}190	#[cfg(not(feature = "faster"))]191	pub fn into_json(self, padding: usize) -> Result<Rc<str>> {192		with_state(|s| {193			let ctx = s194				.create_default_context()?195				.with_var("__tmp__to_json__".into(), self)?;196			Ok(evaluate(197				ctx,198				&el!(Expr::Apply(199					el!(Expr::Index(200						el!(Expr::Var("std".into())),201						el!(Expr::Str("manifestJsonEx".into()))202					)),203					ArgsDesc(vec![204						Arg(None, el!(Expr::Var("__tmp__to_json__".into()))),205						Arg(None, el!(Expr::Str(" ".repeat(padding).into())))206					]),207					false208				)),209			)?210			.try_cast_str("to json")?)211		})212	}213}214215fn is_function_like(val: &Val) -> bool {216	matches!(val, Val::Func(_) | Val::Intristic(_, _))217}218219/// Implements std.primitiveEquals builtin220pub fn primitive_equals(val_a: &Val, val_b: &Val) -> Result<bool> {221	Ok(match (val_a.unwrap_if_lazy()?, val_b.unwrap_if_lazy()?) {222		(Val::Bool(a), Val::Bool(b)) => a == b,223		(Val::Null, Val::Null) => true,224		(Val::Str(a), Val::Str(b)) => a == b,225		(Val::Num(a), Val::Num(b)) => (a - b).abs() <= f64::EPSILON,226		(Val::Arr(_), Val::Arr(_)) => create_error_result(Error::RuntimeError(227			"primitiveEquals operates on primitive types, got array".into(),228		))?,229		(Val::Obj(_), Val::Obj(_)) => create_error_result(Error::RuntimeError(230			"primitiveEquals operates on primitive types, got object".into(),231		))?,232		(a, b) if is_function_like(&a) && is_function_like(&b) => create_error_result(233			Error::RuntimeError("cannot test equality of functions".into()),234		)?,235		(_, _) => false,236	})237}238239/// Native implementation of std.equals240pub fn equals(val_a: &Val, val_b: &Val) -> Result<bool> {241	let val_a = val_a.unwrap_if_lazy()?;242	let val_b = val_b.unwrap_if_lazy()?;243244	if val_a.value_type()? != val_b.value_type()? {245		return Ok(false);246	}247	match (val_a, val_b) {248		// Cant test for ptr equality, because all fields needs to be evaluated249		(Val::Arr(a), Val::Arr(b)) => {250			if a.len() != b.len() {251				return Ok(false);252			}253			for (a, b) in a.iter().zip(b.iter()) {254				if !equals(&a.unwrap_if_lazy()?, &b.unwrap_if_lazy()?)? {255					return Ok(false);256				}257			}258			Ok(true)259		}260		(Val::Obj(a), Val::Obj(b)) => {261			let fields = a.visible_fields();262			if fields != b.visible_fields() {263				return Ok(false);264			}265			for field in fields {266				if !equals(&a.get(field.clone())?.unwrap(), &b.get(field)?.unwrap())? {267					return Ok(false);268				}269			}270			Ok(true)271		}272		(a, b) => Ok(primitive_equals(&a, &b)?),273	}274}275276pub fn manifest_json_ex(val: &Val, padding: &str) -> Result<String> {277	let mut out = String::new();278	manifest_json_ex_buf(val, &mut out, padding, &mut String::new())?;279	Ok(out)280}281fn manifest_json_ex_buf(282	val: &Val,283	buf: &mut String,284	padding: &str,285	cur_padding: &mut String,286) -> Result<()> {287	use std::fmt::Write;288	match val.unwrap_if_lazy()? {289		Val::Bool(v) => {290			if v {291				buf.push_str("true");292			} else {293				buf.push_str("false");294			}295		}296		Val::Null => buf.push_str("null"),297		Val::Str(s) => buf.push_str(&escape_string_json(&s)),298		Val::Num(n) => write!(buf, "{}", n).unwrap(),299		Val::Arr(items) => {300			buf.push_str("[\n");301			if !items.is_empty() {302				let old_len = cur_padding.len();303				cur_padding.push_str(padding);304				for (i, item) in items.iter().enumerate() {305					if i != 0 {306						buf.push_str(",\n")307					}308					buf.push_str(cur_padding);309					manifest_json_ex_buf(item, buf, padding, cur_padding)?;310				}311				cur_padding.truncate(old_len);312			}313			buf.push('\n');314			buf.push_str(cur_padding);315			buf.push(']');316		}317		Val::Obj(obj) => {318			buf.push_str("{\n");319			let fields = obj.visible_fields();320			if !fields.is_empty() {321				let old_len = cur_padding.len();322				cur_padding.push_str(padding);323				for (i, field) in fields.into_iter().enumerate() {324					if i != 0 {325						buf.push_str(",\n")326					}327					buf.push_str(cur_padding);328					buf.push_str(&escape_string_json(&field));329					buf.push_str(": ");330					manifest_json_ex_buf(&obj.get(field)?.unwrap(), buf, padding, cur_padding)?;331				}332				cur_padding.truncate(old_len);333			}334			buf.push('\n');335			buf.push_str(cur_padding);336			buf.push('}');337		}338		Val::Func(_) | Val::Intristic(_, _) => create_error_result(Error::RuntimeError("tried to manifest function".into()))?,339		Val::Lazy(_) => unreachable!(),340	};341	Ok(())342}343pub fn escape_string_json(s: &str) -> String {344	use std::fmt::Write;345	let mut out = String::new();346	out.push('"');347	for c in s.chars() {348		match c {349			'"' => out.push_str("\\\""),350			'\\' => out.push_str("\\\\"),351			'\u{0008}' => out.push_str("\\b"),352			'\u{000c}' => out.push_str("\\f"),353			'\n' => out.push_str("\\n"),354			'\r' => out.push_str("\\r"),355			'\t' => out.push_str("\\t"),356			c if c < 32 as char || (c >= 127 as char && c <= 159 as char) => {357				write!(out, "\\u{:04x}", c as u32).unwrap()358			}359			c => out.push(c),360		}361	}362	out.push('"');363	out364}365366#[test]367fn json_test() {368	assert_eq!(escape_string_json("\u{001f}"), "\"\\u001f\"")369}