difftreelog
refactor move push_frame out of State struct
in: master
14 files changed
crates/jrsonnet-evaluator/src/evaluate/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate/mod.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate/mod.rs
@@ -16,10 +16,11 @@
error::{suggest_object_fields, ErrorKind::*},
evaluate::operator::{evaluate_add_op, evaluate_binary_op_special, evaluate_unary_op},
function::{CallLocation, FuncDesc, FuncVal},
+ in_frame,
typed::Typed,
val::{CachedUnbound, IndexableVal, NumValue, StrValue, Thunk, ThunkValue},
Context, Error, GcHashMap, ObjValue, ObjValueBuilder, ObjectAssertion, Pending, Result,
- ResultExt, State, Unbound, Val,
+ ResultExt, Unbound, Val,
};
pub mod destructure;
pub mod operator;
@@ -71,7 +72,7 @@
pub fn evaluate_field_name(ctx: Context, field_name: &FieldName) -> Result<Option<IStr>> {
Ok(match field_name {
FieldName::Fixed(n) => Some(n.clone()),
- FieldName::Dyn(expr) => State::push(
+ FieldName::Dyn(expr) => in_frame(
CallLocation::new(&expr.span()),
|| "evaluating field name".to_string(),
|| {
@@ -374,7 +375,7 @@
if tailstrict {
body()?
} else {
- State::push(loc, || format!("function <{}> call", f.name()), body)?
+ in_frame(loc, || format!("function <{}> call", f.name()), body)?
}
}
v => bail!(OnlyFunctionsCanBeCalledGot(v.value_type())),
@@ -384,13 +385,13 @@
pub fn evaluate_assert(ctx: Context, assertion: &AssertStmt) -> Result<()> {
let value = &assertion.0;
let msg = &assertion.1;
- let assertion_result = State::push(
+ let assertion_result = in_frame(
CallLocation::new(&value.span()),
|| "assertion condition".to_owned(),
|| bool::from_untyped(evaluate(ctx.clone(), value)?),
)?;
if !assertion_result {
- State::push(
+ in_frame(
CallLocation::new(&value.span()),
|| "assertion failure".to_owned(),
|| {
@@ -457,7 +458,7 @@
}
BinaryOp(v1, o, v2) => evaluate_binary_op_special(ctx, v1, *o, v2)?,
UnaryOp(o, v) => evaluate_unary_op(*o, &evaluate(ctx, v)?)?,
- Var(name) => State::push(
+ Var(name) => in_frame(
CallLocation::new(&loc),
|| format!("variable <{name}> access"),
|| ctx.binding(name.clone())?.evaluate(),
@@ -645,7 +646,7 @@
evaluate_assert(ctx.clone(), assert)?;
evaluate(ctx, returned)?
}
- ErrorStmt(e) => State::push(
+ ErrorStmt(e) => in_frame(
CallLocation::new(&loc),
|| "error statement".to_owned(),
|| bail!(RuntimeError(evaluate(ctx, e)?.to_string()?,)),
@@ -655,7 +656,7 @@
cond_then,
cond_else,
} => {
- if State::push(
+ if in_frame(
CallLocation::new(&loc),
|| "if condition".to_owned(),
|| bool::from_untyped(evaluate(ctx.clone(), &cond.0)?),
@@ -676,7 +677,7 @@
desc: &'static str,
) -> Result<Option<T>> {
if let Some(value) = expr {
- Ok(Some(State::push(
+ Ok(Some(in_frame(
loc,
|| format!("slice {desc}"),
|| T::from_untyped(evaluate(ctx.clone(), value)?),
@@ -703,7 +704,7 @@
let s = ctx.state();
let resolved_path = s.resolve_from(tmp.source_path(), path as &str)?;
match i {
- Import(_) => State::push(
+ Import(_) => in_frame(
CallLocation::new(&loc),
|| format!("import {:?}", path.clone()),
|| s.import_resolved(resolved_path),
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -1,6 +1,5 @@
use std::{
any::Any,
- cell::RefCell,
env::current_dir,
fs,
io::{ErrorKind, Read},
@@ -41,8 +40,10 @@
/// this cannot be resolved using associated type, as evaluator uses object instead of generic for [`ImportResolver`]
fn load_file_contents(&self, resolved: &SourcePath) -> Result<Vec<u8>>;
- /// For downcasts
+ // For downcasts, will be removed after trait_upcasting_coercion
+ // stabilization.
fn as_any(&self) -> &dyn Any;
+ fn as_any_mut(&mut self) -> &mut dyn Any;
}
/// Dummy resolver, can't resolve/load any file
@@ -56,6 +57,9 @@
fn as_any(&self) -> &dyn Any {
self
}
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
+ }
}
#[allow(clippy::use_self)]
impl Default for Box<dyn ImportResolver> {
@@ -69,17 +73,15 @@
pub struct FileImportResolver {
/// Library directories to search for file.
/// Referred to as `jpath` in original jsonnet implementation.
- library_paths: RefCell<Vec<PathBuf>>,
+ library_paths: Vec<PathBuf>,
}
impl FileImportResolver {
- pub fn new(jpath: Vec<PathBuf>) -> Self {
- Self {
- library_paths: RefCell::new(jpath),
- }
+ pub fn new(library_paths: Vec<PathBuf>) -> Self {
+ Self { library_paths }
}
/// Dynamically add new jpath, used by bindings
- pub fn add_jpath(&self, path: PathBuf) {
- self.library_paths.borrow_mut().push(path);
+ pub fn add_jpath(&mut self, path: PathBuf) {
+ self.library_paths.push(path);
}
}
@@ -132,7 +134,7 @@
if let Some(direct) = check_path(&direct)? {
return Ok(direct);
}
- for library_path in self.library_paths.borrow().iter() {
+ for library_path in &self.library_paths {
let mut cloned = library_path.clone();
cloned.push(path);
if let Some(cloned) = check_path(&cloned)? {
@@ -165,11 +167,15 @@
Ok(out)
}
+ fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
+ self.resolve_from(&SourcePath::default(), path)
+ }
+
fn as_any(&self) -> &dyn Any {
self
}
- fn resolve_from_default(&self, path: &str) -> Result<SourcePath> {
- self.resolve_from(&SourcePath::default(), path)
+ fn as_any_mut(&mut self) -> &mut dyn Any {
+ self
}
}
crates/jrsonnet-evaluator/src/integrations/serde.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/integrations/serde.rs
+++ b/crates/jrsonnet-evaluator/src/integrations/serde.rs
@@ -11,8 +11,8 @@
};
use crate::{
- arr::ArrValue, runtime_error, val::NumValue, Error as JrError, ObjValue, ObjValueBuilder,
- Result, State, Val,
+ arr::ArrValue, in_description_frame, runtime_error, val::NumValue, Error as JrError, ObjValue,
+ ObjValueBuilder, Result, Val,
};
impl<'de> Deserialize<'de> for Val {
@@ -173,8 +173,7 @@
let mut seq = serializer.serialize_seq(Some(arr.len()))?;
for (i, element) in arr.iter().enumerate() {
let mut serde_error = None;
- // TODO: rewrite using try{} after stabilization
- State::push_description(
+ in_description_frame(
|| format!("array index [{i}]"),
|| {
let e = element?;
@@ -199,7 +198,7 @@
) {
let mut serde_error = None;
// TODO: rewrite using try{} after stabilization
- State::push_description(
+ in_description_frame(
|| format!("object field {field:?}"),
|| {
let v = value?;
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -45,7 +45,7 @@
#[doc(hidden)]
pub use jrsonnet_macros;
pub use jrsonnet_parser as parser;
-use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath, Span};
+use jrsonnet_parser::{LocExpr, ParserSettings, Source, SourcePath};
pub use obj::*;
use stack::check_depth;
pub use tla::apply_tla;
@@ -376,38 +376,6 @@
context_initializer.populate(source, &mut builder);
builder.build()
- }
-
- /// Executes code creating a new stack frame
- pub fn push<T>(
- e: CallLocation<'_>,
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<T>,
- ) -> Result<T> {
- let _guard = check_depth()?;
-
- f().with_description_src(e, frame_desc)
- }
-
- /// Executes code creating a new stack frame
- pub fn push_val(
- &self,
- e: &Span,
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<Val>,
- ) -> Result<Val> {
- let _guard = check_depth()?;
-
- f().with_description_src(e, frame_desc)
- }
- /// Executes code creating a new stack frame
- pub fn push_description<T>(
- frame_desc: impl FnOnce() -> String,
- f: impl FnOnce() -> Result<T>,
- ) -> Result<T> {
- let _guard = check_depth()?;
-
- f().with_description(frame_desc)
}
}
@@ -417,6 +385,26 @@
self.0.file_cache.borrow_mut()
}
}
+/// Executes code creating a new stack frame, to be replaced with try{}
+pub fn in_frame<T>(
+ e: CallLocation<'_>,
+ frame_desc: impl FnOnce() -> String,
+ f: impl FnOnce() -> Result<T>,
+) -> Result<T> {
+ let _guard = check_depth()?;
+
+ f().with_description_src(e, frame_desc)
+}
+
+/// Executes code creating a new stack frame, to be replaced with try{}
+pub fn in_description_frame<T>(
+ frame_desc: impl FnOnce() -> String,
+ f: impl FnOnce() -> Result<T>,
+) -> Result<T> {
+ let _guard = check_depth()?;
+
+ f().with_description(frame_desc)
+}
#[derive(Trace)]
pub struct InitialUnderscore(pub Thunk<Val>);
crates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/manifest.rs
+++ b/crates/jrsonnet-evaluator/src/manifest.rs
@@ -1,6 +1,6 @@
use std::{borrow::Cow, fmt::Write, ptr};
-use crate::{bail, Result, ResultExt, State, Val};
+use crate::{bail, in_description_frame, Result, ResultExt, Val};
pub trait ManifestFormat {
fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;
@@ -242,7 +242,7 @@
Minify | ToString => {}
};
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| manifest_json_ex_buf(&item, buf, cur_padding, options),
)?;
@@ -304,7 +304,7 @@
escape_string_json_buf(&key, buf);
buf.push_str(options.key_val_sep);
- State::push_description(
+ in_description_frame(
|| format!("field <{key}> manifestification"),
|| manifest_json_ex_buf(&value, buf, cur_padding, options),
)?;
@@ -412,7 +412,7 @@
for (i, v) in arr.iter().enumerate() {
let v = v.with_description(|| format!("elem <{i}> evaluation"))?;
out.push_str("---\n");
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| self.inner.manifest_buf(v, out),
)?;
crates/jrsonnet-evaluator/src/obj.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/obj.rs
+++ b/crates/jrsonnet-evaluator/src/obj.rs
@@ -17,10 +17,11 @@
error::{suggest_object_fields, Error, ErrorKind::*},
function::{CallLocation, FuncVal},
gc::{GcHashMap, GcHashSet, TraceBox},
+ in_frame,
operator::evaluate_add_op,
tb,
val::{ArrValue, ThunkValue},
- MaybeUnbound, Result, State, Thunk, Unbound, Val,
+ MaybeUnbound, Result, Thunk, Unbound, Val,
};
#[cfg(not(feature = "exp-preserve-order"))]
@@ -969,7 +970,7 @@
let location = member.location.clone();
let old = receiver.0.map.insert(name.clone(), member);
if old.is_some() {
- State::push(
+ in_frame(
CallLocation(location.as_ref()),
|| format!("field <{}> initializtion", name.clone()),
|| bail!(DuplicateFieldName(name.clone())),
crates/jrsonnet-evaluator/src/stdlib/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/stdlib/mod.rs
+++ b/crates/jrsonnet-evaluator/src/stdlib/mod.rs
@@ -3,12 +3,12 @@
use format::{format_arr, format_obj};
-use crate::{function::CallLocation, Result, State, Val};
+use crate::{function::CallLocation, in_frame, Result, Val};
pub mod format;
pub fn std_format(str: &str, vals: Val) -> Result<String> {
- State::push(
+ in_frame(
CallLocation::native(),
|| format!("std.format of {str}"),
|| {
crates/jrsonnet-evaluator/src/tla.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/tla.rs
+++ b/crates/jrsonnet-evaluator/src/tla.rs
@@ -3,12 +3,12 @@
use crate::{
function::{ArgsLike, CallLocation},
- Result, State, Val,
+ in_description_frame, Result, State, Val,
};
pub fn apply_tla<A: ArgsLike>(s: State, args: &A, val: Val) -> Result<Val> {
Ok(if let Val::Func(func) = val {
- State::push_description(
+ in_description_frame(
|| "during TLA call".to_owned(),
|| {
func.evaluate(
crates/jrsonnet-evaluator/src/typed/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/typed/mod.rs
+++ b/crates/jrsonnet-evaluator/src/typed/mod.rs
@@ -8,7 +8,7 @@
use crate::{
error::{Error, ErrorKind, Result},
- State, Val,
+ in_description_frame, Val,
};
#[derive(Debug, Error, Clone, Trace)]
@@ -89,7 +89,7 @@
path: impl Fn() -> ValuePathItem,
item: impl Fn() -> Result<()>,
) -> Result<()> {
- State::push_description(error_reason, || match item() {
+ in_description_frame(error_reason, || match item() {
Ok(()) => Ok(()),
Err(mut e) => {
if let ErrorKind::TypeError(e) = &mut e.error_mut() {
crates/jrsonnet-interner/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-interner/src/lib.rs
+++ b/crates/jrsonnet-interner/src/lib.rs
@@ -235,6 +235,7 @@
use crate::{PoolMap, POOL};
+ /// Type-erased interned string pool
pub enum PoolState {}
/// Dump current interned string pool, to be restored by
crates/jrsonnet-macros/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-macros/src/lib.rs
+++ b/crates/jrsonnet-macros/src/lib.rs
@@ -290,7 +290,7 @@
cfg_attrs,
} => {
let name = name.as_ref().map_or("<unnamed>", String::as_str);
- let eval = quote! {jrsonnet_evaluator::State::push_description(
+ let eval = quote! {jrsonnet_evaluator::in_description_frame(
|| format!("argument <{}> evaluation", #name),
|| <#ty>::from_untyped(value.evaluate()?),
)?};
crates/jrsonnet-stdlib/src/manifest/toml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/toml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/toml.rs
@@ -1,10 +1,10 @@
use std::borrow::Cow;
use jrsonnet_evaluator::{
- bail,
+ bail, in_description_frame,
manifest::{escape_string_json_buf, ManifestFormat},
val::ArrValue,
- IStr, ObjValue, Result, ResultExt, State, Val,
+ IStr, ObjValue, Result, ResultExt, Val,
};
pub struct TomlFormat<'s> {
@@ -124,7 +124,7 @@
buf.push_str(&options.padding);
}
- State::push_description(
+ in_description_frame(
|| format!("elem <{i}> manifestification"),
|| manifest_value(&e, true, buf, "", options),
)?;
@@ -161,7 +161,7 @@
escape_key_toml_buf(&k, buf);
buf.push_str(" = ");
- State::push_description(
+ in_description_frame(
|| format!("field <{k}> manifestification"),
|| manifest_value(&v, true, buf, "", options),
)?;
crates/jrsonnet-stdlib/src/manifest/xml.rsdiffbeforeafterboth--- a/crates/jrsonnet-stdlib/src/manifest/xml.rs
+++ b/crates/jrsonnet-stdlib/src/manifest/xml.rs
@@ -1,9 +1,9 @@
use jrsonnet_evaluator::{
- bail,
+ bail, in_description_frame,
manifest::{ManifestFormat, ToStringFormat},
typed::{ComplexValType, Either2, Typed, ValType},
val::ArrValue,
- Either, ObjValue, Result, ResultExt, State, Val,
+ Either, ObjValue, Result, ResultExt, Val,
};
pub struct XmlJsonmlFormat {
@@ -70,7 +70,7 @@
Ok(Self::Tag {
tag,
attrs,
- children: State::push_description(
+ children: in_description_frame(
|| "parsing children".to_owned(),
|| {
Typed::from_untyped(Val::Arr(arr.slice(
crates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth1use std::{borrow::Cow, fmt::Write};23use jrsonnet_evaluator::{4 bail,5 manifest::{escape_string_json_buf, ManifestFormat},6 Result, ResultExt, State, Val,7};89pub struct YamlFormat<'s> {10 /// Padding before fields, i.e11 /// ```yaml12 /// a:13 /// b:14 /// ## <- this15 /// ```16 padding: Cow<'s, str>,17 /// Padding before array elements in objects18 /// ```yaml19 /// a:20 /// - 121 /// ## <- this22 /// ```23 arr_element_padding: Cow<'s, str>,24 /// Should yaml keys appear unescaped, when possible25 /// ```yaml26 /// "safe_key": 127 /// # vs28 /// safe_key: 129 /// ```30 quote_keys: bool,31 /// If true - then order of fields is preserved as written,32 /// instead of sorting alphabetically33 #[cfg(feature = "exp-preserve-order")]34 preserve_order: bool,35}36impl YamlFormat<'_> {37 pub fn cli(38 padding: usize,39 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,40 ) -> Self {41 let padding = " ".repeat(padding);42 Self {43 padding: Cow::Owned(padding.clone()),44 arr_element_padding: Cow::Owned(padding),45 quote_keys: false,46 #[cfg(feature = "exp-preserve-order")]47 preserve_order,48 }49 }50 pub fn std_to_yaml(51 indent_array_in_object: bool,52 quote_keys: bool,53 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,54 ) -> Self {55 Self {56 padding: Cow::Borrowed(" "),57 arr_element_padding: Cow::Borrowed(if indent_array_in_object { " " } else { "" }),58 quote_keys,59 #[cfg(feature = "exp-preserve-order")]60 preserve_order,61 }62 }63}64impl ManifestFormat for YamlFormat<'_> {65 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {66 manifest_yaml_ex_buf(&val, buf, &mut String::new(), self)67 }68}6970/// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>71/// With added date check72fn yaml_needs_quotes(string: &str) -> bool {73 fn need_quotes_spaces(string: &str) -> bool {74 string.starts_with(' ') || string.ends_with(' ')75 }7677 string.is_empty()78 || need_quotes_spaces(string)79 || string.starts_with(|c| matches!(c, '&' | '*' | '?' | '|' | '-' | '<' | '>' | '=' | '!' | '%' | '@'))80 || string.contains(|c| matches!(c, ':' | '{' | '}' | '[' | ']' | ',' | '#' | '`' | '\"' | '\'' | '\\' | '\0'..='\x06' | '\t' | '\n' | '\r' | '\x0e'..='\x1a' | '\x1c'..='\x1f'))81 || [82 // http://yaml.org/type/bool.html83 "yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",84 "on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html85 "null", "Null", "NULL", "~",86 // > Quoted in std.jsonnet, however, in serde_yaml they were quoted:87 // > Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse88 // > them as string, not booleans, although it is violating the YAML 1.1 specification.89 // > See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.90 "y", "Y", "n", "N",91 "-.inf", "+.inf", ".inf",92 "-", "---", ""93 ].contains(&string)94 || (string.chars().all(|c| matches!(c, '0'..='9' | '-'))95 && string.chars().filter(|c| *c == '-').count() == 2)96 || string.starts_with('.')97 || string.starts_with("0x")98 || string.parse::<i64>().is_ok()99 || string.parse::<f64>().is_ok()100}101102#[allow(dead_code)]103fn manifest_yaml_ex(val: &Val, options: &YamlFormat<'_>) -> Result<String> {104 let mut out = String::new();105 manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;106 Ok(out)107}108109#[allow(clippy::too_many_lines)]110fn manifest_yaml_ex_buf(111 val: &Val,112 buf: &mut String,113 cur_padding: &mut String,114 options: &YamlFormat<'_>,115) -> Result<()> {116 match val {117 Val::Bool(v) => {118 if *v {119 buf.push_str("true");120 } else {121 buf.push_str("false");122 }123 }124 Val::Null => buf.push_str("null"),125 Val::Str(s) => {126 let s = s.clone().into_flat();127 if s.is_empty() {128 buf.push_str("\"\"");129 } else if let Some(s) = s.strip_suffix('\n') {130 buf.push('|');131 for line in s.split('\n') {132 buf.push('\n');133 buf.push_str(cur_padding);134 buf.push_str(&options.padding);135 buf.push_str(line);136 }137 } else if s.contains('\n') {138 buf.push_str("|-");139 for line in s.split('\n') {140 buf.push('\n');141 buf.push_str(cur_padding);142 buf.push_str(&options.padding);143 buf.push_str(line);144 }145 } else if !options.quote_keys && !yaml_needs_quotes(&s) {146 buf.push_str(&s);147 } else {148 escape_string_json_buf(&s, buf);149 }150 }151 Val::Num(n) => write!(buf, "{}", *n).unwrap(),152 #[cfg(feature = "exp-bigint")]153 Val::BigInt(n) => write!(buf, "{}", *n).unwrap(),154 Val::Arr(a) => {155 let mut had_items = false;156 for (i, item) in a.iter().enumerate() {157 had_items = true;158 let item = item.with_description(|| format!("elem <{i}> evaluation"))?;159 if i != 0 {160 buf.push('\n');161 buf.push_str(cur_padding);162 }163 buf.push('-');164 match &item {165 Val::Arr(a) if !a.is_empty() => {166 buf.push('\n');167 buf.push_str(cur_padding);168 buf.push_str(&options.padding);169 }170 _ => buf.push(' '),171 }172 let extra_padding = match &item {173 Val::Arr(a) => !a.is_empty(),174 Val::Obj(o) => !o.is_empty(),175 _ => false,176 };177 let prev_len = cur_padding.len();178 if extra_padding {179 cur_padding.push_str(&options.padding);180 }181 State::push_description(182 || format!("elem <{i}> manifestification"),183 || manifest_yaml_ex_buf(&item, buf, cur_padding, options),184 )?;185 cur_padding.truncate(prev_len);186 }187 if !had_items {188 buf.push_str("[]");189 }190 }191 Val::Obj(o) => {192 let mut had_fields = false;193 for (i, (key, value)) in o194 .iter(195 #[cfg(feature = "exp-preserve-order")]196 options.preserve_order,197 )198 .enumerate()199 {200 had_fields = true;201 let value = value.with_description(|| format!("field <{key}> evaluation"))?;202 if i != 0 {203 buf.push('\n');204 buf.push_str(cur_padding);205 }206 if !options.quote_keys && !yaml_needs_quotes(&key) {207 buf.push_str(&key);208 } else {209 escape_string_json_buf(&key, buf);210 }211 buf.push(':');212 let prev_len = cur_padding.len();213 match &value {214 Val::Arr(a) if !a.is_empty() => {215 buf.push('\n');216 buf.push_str(cur_padding);217 buf.push_str(&options.arr_element_padding);218 cur_padding.push_str(&options.arr_element_padding);219 }220 Val::Obj(o) if !o.is_empty() => {221 buf.push('\n');222 buf.push_str(cur_padding);223 buf.push_str(&options.padding);224 cur_padding.push_str(&options.padding);225 }226 _ => buf.push(' '),227 }228 State::push_description(229 || format!("field <{key}> manifestification"),230 || manifest_yaml_ex_buf(&value, buf, cur_padding, options),231 )?;232 cur_padding.truncate(prev_len);233 }234 if !had_fields {235 buf.push_str("{}");236 }237 }238 Val::Func(_) => bail!("tried to manifest function"),239 }240 Ok(())241}1use std::{borrow::Cow, fmt::Write};23use jrsonnet_evaluator::{4 bail, in_description_frame,5 manifest::{escape_string_json_buf, ManifestFormat},6 Result, ResultExt, Val,7};89pub struct YamlFormat<'s> {10 /// Padding before fields, i.e11 /// ```yaml12 /// a:13 /// b:14 /// ## <- this15 /// ```16 padding: Cow<'s, str>,17 /// Padding before array elements in objects18 /// ```yaml19 /// a:20 /// - 121 /// ## <- this22 /// ```23 arr_element_padding: Cow<'s, str>,24 /// Should yaml keys appear unescaped, when possible25 /// ```yaml26 /// "safe_key": 127 /// # vs28 /// safe_key: 129 /// ```30 quote_keys: bool,31 /// If true - then order of fields is preserved as written,32 /// instead of sorting alphabetically33 #[cfg(feature = "exp-preserve-order")]34 preserve_order: bool,35}36impl YamlFormat<'_> {37 pub fn cli(38 padding: usize,39 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,40 ) -> Self {41 let padding = " ".repeat(padding);42 Self {43 padding: Cow::Owned(padding.clone()),44 arr_element_padding: Cow::Owned(padding),45 quote_keys: false,46 #[cfg(feature = "exp-preserve-order")]47 preserve_order,48 }49 }50 pub fn std_to_yaml(51 indent_array_in_object: bool,52 quote_keys: bool,53 #[cfg(feature = "exp-preserve-order")] preserve_order: bool,54 ) -> Self {55 Self {56 padding: Cow::Borrowed(" "),57 arr_element_padding: Cow::Borrowed(if indent_array_in_object { " " } else { "" }),58 quote_keys,59 #[cfg(feature = "exp-preserve-order")]60 preserve_order,61 }62 }63}64impl ManifestFormat for YamlFormat<'_> {65 fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {66 manifest_yaml_ex_buf(&val, buf, &mut String::new(), self)67 }68}6970/// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>71/// With added date check72fn yaml_needs_quotes(string: &str) -> bool {73 fn need_quotes_spaces(string: &str) -> bool {74 string.starts_with(' ') || string.ends_with(' ')75 }7677 string.is_empty()78 || need_quotes_spaces(string)79 || string.starts_with(|c| matches!(c, '&' | '*' | '?' | '|' | '-' | '<' | '>' | '=' | '!' | '%' | '@'))80 || string.contains(|c| matches!(c, ':' | '{' | '}' | '[' | ']' | ',' | '#' | '`' | '\"' | '\'' | '\\' | '\0'..='\x06' | '\t' | '\n' | '\r' | '\x0e'..='\x1a' | '\x1c'..='\x1f'))81 || [82 // http://yaml.org/type/bool.html83 "yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",84 "on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html85 "null", "Null", "NULL", "~",86 // > Quoted in std.jsonnet, however, in serde_yaml they were quoted:87 // > Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse88 // > them as string, not booleans, although it is violating the YAML 1.1 specification.89 // > See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.90 "y", "Y", "n", "N",91 "-.inf", "+.inf", ".inf",92 "-", "---", ""93 ].contains(&string)94 || (string.chars().all(|c| matches!(c, '0'..='9' | '-'))95 && string.chars().filter(|c| *c == '-').count() == 2)96 || string.starts_with('.')97 || string.starts_with("0x")98 || string.parse::<i64>().is_ok()99 || string.parse::<f64>().is_ok()100}101102#[allow(dead_code)]103fn manifest_yaml_ex(val: &Val, options: &YamlFormat<'_>) -> Result<String> {104 let mut out = String::new();105 manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;106 Ok(out)107}108109#[allow(clippy::too_many_lines)]110fn manifest_yaml_ex_buf(111 val: &Val,112 buf: &mut String,113 cur_padding: &mut String,114 options: &YamlFormat<'_>,115) -> Result<()> {116 match val {117 Val::Bool(v) => {118 if *v {119 buf.push_str("true");120 } else {121 buf.push_str("false");122 }123 }124 Val::Null => buf.push_str("null"),125 Val::Str(s) => {126 let s = s.clone().into_flat();127 if s.is_empty() {128 buf.push_str("\"\"");129 } else if let Some(s) = s.strip_suffix('\n') {130 buf.push('|');131 for line in s.split('\n') {132 buf.push('\n');133 buf.push_str(cur_padding);134 buf.push_str(&options.padding);135 buf.push_str(line);136 }137 } else if s.contains('\n') {138 buf.push_str("|-");139 for line in s.split('\n') {140 buf.push('\n');141 buf.push_str(cur_padding);142 buf.push_str(&options.padding);143 buf.push_str(line);144 }145 } else if !options.quote_keys && !yaml_needs_quotes(&s) {146 buf.push_str(&s);147 } else {148 escape_string_json_buf(&s, buf);149 }150 }151 Val::Num(n) => write!(buf, "{}", *n).unwrap(),152 #[cfg(feature = "exp-bigint")]153 Val::BigInt(n) => write!(buf, "{}", *n).unwrap(),154 Val::Arr(a) => {155 let mut had_items = false;156 for (i, item) in a.iter().enumerate() {157 had_items = true;158 let item = item.with_description(|| format!("elem <{i}> evaluation"))?;159 if i != 0 {160 buf.push('\n');161 buf.push_str(cur_padding);162 }163 buf.push('-');164 match &item {165 Val::Arr(a) if !a.is_empty() => {166 buf.push('\n');167 buf.push_str(cur_padding);168 buf.push_str(&options.padding);169 }170 _ => buf.push(' '),171 }172 let extra_padding = match &item {173 Val::Arr(a) => !a.is_empty(),174 Val::Obj(o) => !o.is_empty(),175 _ => false,176 };177 let prev_len = cur_padding.len();178 if extra_padding {179 cur_padding.push_str(&options.padding);180 }181 in_description_frame(182 || format!("elem <{i}> manifestification"),183 || manifest_yaml_ex_buf(&item, buf, cur_padding, options),184 )?;185 cur_padding.truncate(prev_len);186 }187 if !had_items {188 buf.push_str("[]");189 }190 }191 Val::Obj(o) => {192 let mut had_fields = false;193 for (i, (key, value)) in o194 .iter(195 #[cfg(feature = "exp-preserve-order")]196 options.preserve_order,197 )198 .enumerate()199 {200 had_fields = true;201 let value = value.with_description(|| format!("field <{key}> evaluation"))?;202 if i != 0 {203 buf.push('\n');204 buf.push_str(cur_padding);205 }206 if !options.quote_keys && !yaml_needs_quotes(&key) {207 buf.push_str(&key);208 } else {209 escape_string_json_buf(&key, buf);210 }211 buf.push(':');212 let prev_len = cur_padding.len();213 match &value {214 Val::Arr(a) if !a.is_empty() => {215 buf.push('\n');216 buf.push_str(cur_padding);217 buf.push_str(&options.arr_element_padding);218 cur_padding.push_str(&options.arr_element_padding);219 }220 Val::Obj(o) if !o.is_empty() => {221 buf.push('\n');222 buf.push_str(cur_padding);223 buf.push_str(&options.padding);224 cur_padding.push_str(&options.padding);225 }226 _ => buf.push(' '),227 }228 in_description_frame(229 || format!("field <{key}> manifestification"),230 || manifest_yaml_ex_buf(&value, buf, cur_padding, options),231 )?;232 cur_padding.truncate(prev_len);233 }234 if !had_fields {235 buf.push_str("{}");236 }237 }238 Val::Func(_) => bail!("tried to manifest function"),239 }240 Ok(())241}